pywatt_sdk 0.5.3

Standardized SDK for building PyWatt modules in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use async_trait::async_trait;
use std::collections::HashMap;
use std::time::Duration;

use crate::data::cache::{CacheConfig, CacheError, CacheResult, CacheService, CacheStats, CacheType};
use crate::ipc::send_request;
use crate::ipc_types::{
    ServiceOperation, ServiceOperationResult, ServiceRequest, ServiceResponse, ServiceType,
};
use base64::{Engine as _, engine::general_purpose::STANDARD};

// ProxyCacheService for handling cache operations via IPC
pub struct ProxyCacheService {
    connection_id: String,
    cache_type: CacheType,
    default_ttl: Duration,
}

impl ProxyCacheService {
    pub async fn connect(config: &CacheConfig) -> CacheResult<Self> {
        // Create a unique ID for this connection request
        let request_id = format!("cache_request_{}", uuid::Uuid::new_v4());

        // Create a service request
        let request = ServiceRequest {
            id: request_id.clone(),
            service_type: ServiceType::Cache,
            config: Some(serde_json::to_value(config).map_err(|e| {
                CacheError::Configuration(format!("Failed to serialize cache config: {}", e))
            })?),
        };

        // Send the request to the orchestrator
        let response = send_request(&request)
            .await
            .map_err(|e| CacheError::Connection(format!("Failed to send request: {}", e)))?;

        // Deserialize the response
        let service_response: ServiceResponse = serde_json::from_str(&response)
            .map_err(|e| CacheError::Connection(format!("Failed to parse response: {}", e)))?;

        // Check if the request was successful
        if !service_response.success {
            return Err(CacheError::Connection(
                service_response
                    .error
                    .unwrap_or_else(|| "Unknown connection error".to_string()),
            ));
        }

        // Get the connection ID
        let connection_id = service_response
            .connection_id
            .ok_or_else(|| CacheError::Connection("No connection ID returned".to_string()))?;

        Ok(Self {
            connection_id,
            cache_type: match config.cache_type {
                CacheType::Redis => CacheType::Redis,
                CacheType::Memcached => CacheType::Memcached,
                CacheType::InMemory => CacheType::InMemory,
                CacheType::File => CacheType::File,
            },
            default_ttl: config.get_default_ttl(),
        })
    }
}

#[async_trait]
impl CacheService for ProxyCacheService {
    async fn get(&self, key: &str) -> CacheResult<Option<Vec<u8>>> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "get".to_string(),
            params: serde_json::json!({
                "key": key,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if value.is_null() {
                    return Ok(None);
                }

                if let Some(s) = value.as_str() {
                    // Value is base64 encoded
                    match STANDARD.decode(s) {
                        Ok(bytes) => Ok(Some(bytes)),
                        Err(e) => Err(CacheError::Serialization(format!("Invalid base64: {}", e))),
                    }
                } else if let Some(array) = value.as_array() {
                    // Value is a byte array
                    let bytes: Result<Vec<u8>, _> = array
                        .iter()
                        .map(|v| {
                            if let Some(n) = v.as_u64() {
                                if n <= 255 {
                                    Ok(n as u8)
                                } else {
                                    Err(CacheError::Serialization(format!(
                                        "Invalid byte value: {}",
                                        n
                                    )))
                                }
                            } else {
                                Err(CacheError::Serialization("Invalid byte value".to_string()))
                            }
                        })
                        .collect();

                    Ok(Some(bytes?))
                } else {
                    Err(CacheError::Serialization(
                        "Invalid value format".to_string(),
                    ))
                }
            }
            None => Ok(None),
        }
    }

    async fn set(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> CacheResult<()> {
        // Convert value to base64 for transport
        let value_base64 = STANDARD.encode(value);

        // Convert ttl to seconds
        let ttl_seconds = ttl.map(|d| d.as_secs());

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "set".to_string(),
            params: serde_json::json!({
                "key": key,
                "value": value_base64,
                "ttl_seconds": ttl_seconds,
            }),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Operation(
                result
                    .error
                    .unwrap_or_else(|| "Set operation failed".to_string()),
            ))
        }
    }

    async fn delete(&self, key: &str) -> CacheResult<bool> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "delete".to_string(),
            params: serde_json::json!({
                "key": key,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(success) = value.as_bool() {
                    Ok(success)
                } else {
                    Err(CacheError::Operation("Invalid delete result".to_string()))
                }
            }
            None => Ok(false), // Assume not found
        }
    }

    async fn exists(&self, key: &str) -> CacheResult<bool> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "exists".to_string(),
            params: serde_json::json!({
                "key": key,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(exists) = value.as_bool() {
                    Ok(exists)
                } else {
                    Err(CacheError::Operation("Invalid exists result".to_string()))
                }
            }
            None => Ok(false), // Assume not found
        }
    }

    async fn set_nx(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> CacheResult<bool> {
        // Convert value to base64 for transport
        let value_base64 = STANDARD.encode(value);

        // Convert ttl to seconds
        let ttl_seconds = ttl.map(|d| d.as_secs());

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "set_nx".to_string(),
            params: serde_json::json!({
                "key": key,
                "value": value_base64,
                "ttl_seconds": ttl_seconds,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(success) = value.as_bool() {
                    Ok(success)
                } else {
                    Err(CacheError::Operation("Invalid set_nx result".to_string()))
                }
            }
            None => Ok(false), // Assume not set
        }
    }

    async fn get_set(&self, key: &str, value: &[u8]) -> CacheResult<Option<Vec<u8>>> {
        // Convert value to base64 for transport
        let value_base64 = STANDARD.encode(value);

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "get_set".to_string(),
            params: serde_json::json!({
                "key": key,
                "value": value_base64,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if value.is_null() {
                    return Ok(None);
                }

                if let Some(s) = value.as_str() {
                    // Value is base64 encoded
                    match STANDARD.decode(s) {
                        Ok(bytes) => Ok(Some(bytes)),
                        Err(e) => Err(CacheError::Serialization(format!("Invalid base64: {}", e))),
                    }
                } else {
                    Err(CacheError::Serialization(
                        "Invalid value format".to_string(),
                    ))
                }
            }
            None => Ok(None),
        }
    }

    async fn increment(&self, key: &str, delta: i64) -> CacheResult<i64> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "increment".to_string(),
            params: serde_json::json!({
                "key": key,
                "delta": delta,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(n) = value.as_i64() {
                    Ok(n)
                } else {
                    Err(CacheError::Operation(
                        "Invalid increment result".to_string(),
                    ))
                }
            }
            None => Err(CacheError::Operation(
                "No result from increment operation".to_string(),
            )),
        }
    }

    async fn set_many(
        &self,
        items: &HashMap<String, Vec<u8>>,
        ttl: Option<Duration>,
    ) -> CacheResult<()> {
        // Convert values to base64 for transport
        let mut items_base64 = HashMap::new();
        for (key, value) in items {
            items_base64.insert(key.clone(), STANDARD.encode(value));
        }

        // Convert ttl to seconds
        let ttl_seconds = ttl.map(|d| d.as_secs());

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "set_many".to_string(),
            params: serde_json::json!({
                "items": items_base64,
                "ttl_seconds": ttl_seconds,
            }),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Operation(
                result
                    .error
                    .unwrap_or_else(|| "Set many operation failed".to_string()),
            ))
        }
    }

    async fn get_many(&self, keys: &[String]) -> CacheResult<HashMap<String, Vec<u8>>> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "get_many".to_string(),
            params: serde_json::json!({
                "keys": keys,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let map: HashMap<String, String> = serde_json::from_value(value).map_err(|e| {
                    CacheError::Serialization(format!("Failed to deserialize result: {}", e))
                })?;

                let mut result_map = HashMap::new();
                for (key, value_base64) in map {
                    match STANDARD.decode(&value_base64) {
                        Ok(bytes) => {
                            result_map.insert(key, bytes);
                        }
                        Err(e) => {
                            return Err(CacheError::Serialization(format!(
                                "Invalid base64: {}",
                                e
                            )));
                        }
                    }
                }

                Ok(result_map)
            }
            None => Ok(HashMap::new()), // Return empty map if no results
        }
    }

    async fn delete_many(&self, keys: &[String]) -> CacheResult<u64> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "delete_many".to_string(),
            params: serde_json::json!({
                "keys": keys,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(n) = value.as_u64() {
                    Ok(n)
                } else {
                    Err(CacheError::Operation(
                        "Invalid delete_many result".to_string(),
                    ))
                }
            }
            None => Ok(0), // Assume none deleted
        }
    }

    async fn clear(&self, namespace: Option<&str>) -> CacheResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "clear".to_string(),
            params: serde_json::json!({
                "namespace": namespace,
            }),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Operation(
                result
                    .error
                    .unwrap_or_else(|| "Clear operation failed".to_string()),
            ))
        }
    }

    async fn lock(&self, key: &str, ttl: Duration) -> CacheResult<Option<String>> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "lock".to_string(),
            params: serde_json::json!({
                "key": key,
                "ttl_seconds": ttl.as_secs(),
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if value.is_null() {
                    return Ok(None);
                }

                if let Some(s) = value.as_str() {
                    Ok(Some(s.to_string()))
                } else {
                    Err(CacheError::Operation(
                        "Invalid lock token format".to_string(),
                    ))
                }
            }
            None => Ok(None), // Lock not acquired
        }
    }

    async fn unlock(&self, key: &str, lock_token: &str) -> CacheResult<bool> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "unlock".to_string(),
            params: serde_json::json!({
                "key": key,
                "lock_token": lock_token,
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if let Some(success) = value.as_bool() {
                    Ok(success)
                } else {
                    Err(CacheError::Operation("Invalid unlock result".to_string()))
                }
            }
            None => Ok(false), // Assume unlock failed
        }
    }

    fn get_cache_type(&self) -> CacheType {
        self.cache_type
    }

    async fn ping(&self) -> CacheResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "ping".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Connection(
                result.error.unwrap_or_else(|| "Ping failed".to_string()),
            ))
        }
    }

    async fn close(&self) -> CacheResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "close".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Connection(
                result.error.unwrap_or_else(|| "Close failed".to_string()),
            ))
        }
    }

    fn get_default_ttl(&self) -> Duration {
        self.default_ttl
    }

    async fn stats(&self) -> CacheResult<CacheStats> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "stats".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => serde_json::from_value(value).map_err(|e| {
                CacheError::Serialization(format!("Failed to deserialize stats: {}", e))
            }),
            None => Err(CacheError::Operation("No stats available".to_string())),
        }
    }

    async fn flush(&self) -> CacheResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Cache,
            operation: "flush".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(CacheError::Operation(
                result
                    .error
                    .unwrap_or_else(|| "Flush operation failed".to_string()),
            ))
        }
    }
}

// Helper function to send an operation and receive the result
async fn send_operation(operation: ServiceOperation) -> CacheResult<ServiceOperationResult> {
    let response = send_request(&operation)
        .await
        .map_err(|e| CacheError::Operation(format!("Failed to send operation: {}", e)))?;

    let result: ServiceOperationResult = serde_json::from_str(&response)
        .map_err(|e| CacheError::Operation(format!("Failed to parse response: {}", e)))?;

    if !result.success {
        let error_msg = result.error.unwrap_or_else(|| "Unknown error".to_string());
        return Err(CacheError::Operation(error_msg));
    }

    Ok(result)
}

// Add IPC error to the CacheError enum
impl From<String> for CacheError {
    fn from(error: String) -> Self {
        CacheError::Connection(format!("IPC error: {}", error))
    }
}