alien-bindings 3.3.10

Alien direct in-process resource bindings
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
use crate::error::{map_cloud_client_error, ErrorData, Result};
use crate::traits::{Binding, Kv, KvEntry, PutCondition, PutOptions, ScanResult};
use alien_aws_clients::dynamodb::*;
use alien_error::{AlienError, Context, IntoAlienError};
use async_trait::async_trait;
use base64::{prelude::BASE64_URL_SAFE_NO_PAD, Engine};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use uuid::Uuid;

use super::{decode_version, encode_version, validate_key, validate_value};

const HASH_BUCKET_COUNT: u8 = 16;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CursorState {
    version: u8,
    prefix: String,
    bucket: u8,
    last_key: Option<String>,
}

/// AWS DynamoDB implementation of the KV trait.
///
/// Credential refresh is handled automatically by the underlying `AwsCredentialProvider`
/// inside `DynamoDbClient`.
pub struct AwsDynamodbKv {
    client: DynamoDbClient,
    table_name: String,
}

impl Debug for AwsDynamodbKv {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AwsDynamodbKv")
            .field("table_name", &self.table_name)
            .finish()
    }
}

impl AwsDynamodbKv {
    pub fn new(table_name: String, client: DynamoDbClient) -> Self {
        Self { client, table_name }
    }

    /// Creates a hash bucket for load distribution
    fn hash_bucket(&self, key: &str) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        key.hash(&mut hasher);
        let bucket_id = hasher.finish() % u64::from(HASH_BUCKET_COUNT);
        format!("bucket_{}", bucket_id)
    }

    /// Checks if an item has expired based on TTL
    fn is_expired(&self, ttl_epoch: Option<i64>) -> bool {
        if let Some(ttl_timestamp) = ttl_epoch {
            let now = Utc::now().timestamp();
            now >= ttl_timestamp
        } else {
            false
        }
    }

    fn primary_key(&self, key: &str) -> HashMap<String, AttributeValue> {
        HashMap::from([
            ("pk".to_string(), AttributeValue::s(self.hash_bucket(key))),
            ("sk".to_string(), AttributeValue::s(key.to_string())),
        ])
    }

    async fn load_item(&self, key: &str) -> Result<Option<HashMap<String, AttributeValue>>> {
        let request = GetItemRequest::builder()
            .table_name(self.table_name.clone())
            .key(self.primary_key(key))
            .consistent_read(true)
            .build();
        self.client
            .get_item(request)
            .await
            .map(|response| response.item)
            .map_err(|error| {
                map_cloud_client_error(
                    error,
                    format!("Failed to get item with key '{}'", key),
                    Some(key.to_string()),
                )
            })
    }

    fn item_ttl(item: &HashMap<String, AttributeValue>) -> Option<i64> {
        item.get("ttl")
            .and_then(|attribute| attribute.n.as_deref())
            .and_then(|value| value.parse::<i64>().ok())
    }

    fn item_value(key: &str, item: &HashMap<String, AttributeValue>) -> Result<Vec<u8>> {
        item.get("value")
            .and_then(|attribute| attribute.b.as_ref())
            .and_then(|value| base64::prelude::BASE64_STANDARD.decode(value).ok())
            .ok_or_else(|| {
                AlienError::new(ErrorData::CloudPlatformError {
                    message: format!("Missing or invalid value attribute for key '{}'", key),
                    resource_id: Some(key.to_string()),
                })
            })
    }

    fn encode_cursor(state: &CursorState) -> Result<String> {
        let json =
            serde_json::to_vec(state)
                .into_alien_error()
                .context(ErrorData::InvalidInput {
                    operation_context: "DynamoDB KV scan cursor encoding".to_string(),
                    details: "Failed to serialize cursor state".to_string(),
                    field_name: Some("cursor".to_string()),
                })?;
        Ok(BASE64_URL_SAFE_NO_PAD.encode(json))
    }

    fn decode_cursor(prefix: &str, cursor: &str) -> Result<CursorState> {
        let decoded = BASE64_URL_SAFE_NO_PAD
            .decode(cursor)
            .into_alien_error()
            .context(ErrorData::InvalidInput {
                operation_context: "DynamoDB KV scan cursor decoding".to_string(),
                details: "Invalid cursor encoding".to_string(),
                field_name: Some("cursor".to_string()),
            })?;
        let state: CursorState = serde_json::from_slice(&decoded)
            .into_alien_error()
            .context(ErrorData::InvalidInput {
                operation_context: "DynamoDB KV scan cursor decoding".to_string(),
                details: "Invalid cursor data".to_string(),
                field_name: Some("cursor".to_string()),
            })?;
        if state.version != 1 || state.prefix != prefix || state.bucket >= HASH_BUCKET_COUNT {
            return Err(AlienError::new(ErrorData::InvalidInput {
                operation_context: "DynamoDB KV scan cursor validation".to_string(),
                details: "Cursor does not belong to this prefix scan".to_string(),
                field_name: Some("cursor".to_string()),
            }));
        }
        if state
            .last_key
            .as_ref()
            .is_some_and(|last_key| !last_key.starts_with(prefix))
        {
            return Err(AlienError::new(ErrorData::InvalidInput {
                operation_context: "DynamoDB KV scan cursor validation".to_string(),
                details: "Cursor key does not match the scan prefix".to_string(),
                field_name: Some("cursor".to_string()),
            }));
        }
        Ok(state)
    }
}

impl Binding for AwsDynamodbKv {}

#[async_trait]
impl Kv for AwsDynamodbKv {
    async fn get(&self, key: &str) -> Result<Option<KvEntry>> {
        validate_key(key)?;

        let Some(item) = self.load_item(key).await? else {
            return Ok(None);
        };
        let ttl = Self::item_ttl(&item);
        if self.is_expired(ttl) {
            return Ok(None);
        }
        let backend_version = item
            .get("version")
            .and_then(|value| value.s.clone())
            .ok_or_else(|| {
                AlienError::new(ErrorData::CloudPlatformError {
                    message: format!("Missing or invalid version attribute for key '{}'", key),
                    resource_id: Some(key.to_string()),
                })
            })?;
        Ok(Some(KvEntry {
            key: key.to_string(),
            value: Self::item_value(key, &item)?,
            version: encode_version(
                key,
                backend_version,
                ttl.map(|expires_at| expires_at.saturating_mul(1000)),
            )?,
        }))
    }

    async fn put(&self, key: &str, value: Vec<u8>, options: Option<PutOptions>) -> Result<bool> {
        validate_key(key)?;
        validate_value(&value)?;

        let bucket = self.hash_bucket(key);
        let options = options.unwrap_or_default();

        let mut item = HashMap::new();
        item.insert("pk".to_string(), AttributeValue::s(bucket));
        item.insert("sk".to_string(), AttributeValue::s(key.to_string()));
        item.insert(
            "value".to_string(),
            AttributeValue::b(base64::prelude::BASE64_STANDARD.encode(&value)),
        );
        item.insert(
            "version".to_string(),
            AttributeValue::s(Uuid::new_v4().simple().to_string()),
        );

        if let Some(ttl) = options.ttl {
            let expires_at = (Utc::now() + ttl).timestamp();
            item.insert("ttl".to_string(), AttributeValue::n(expires_at.to_string()));
        }

        let request = if matches!(options.condition, PutCondition::Absent) {
            // Expired rows count as ABSENT, exactly like the local provider's
            // atomic takeover: DynamoDB's background TTL sweeper can lag the
            // logical expiry by hours, and without the `#ttl <= :now` arm a
            // conditional put (e.g. a command lease takeover after the
            // previous holder died) would be blocked until the sweeper
            // physically deletes the row.
            let mut expression_attribute_names = HashMap::new();
            expression_attribute_names.insert("#ttl".to_string(), "ttl".to_string());
            let mut expression_attribute_values = HashMap::new();
            expression_attribute_values.insert(
                ":now".to_string(),
                AttributeValue::n(Utc::now().timestamp().to_string()),
            );
            PutItemRequest::builder()
                .table_name(self.table_name.clone())
                .item(item)
                .condition_expression(
                    "(attribute_not_exists(pk) AND attribute_not_exists(sk))                      OR (attribute_exists(#ttl) AND #ttl <= :now)"
                        .to_string(),
                )
                .expression_attribute_names(expression_attribute_names)
                .expression_attribute_values(expression_attribute_values)
                .build()
        } else if let PutCondition::Version(ref version) = options.condition {
            let expected = decode_version(key, version)?;
            if expected.expired {
                return Ok(false);
            }
            PutItemRequest::builder()
                .table_name(self.table_name.clone())
                .item(item)
                .condition_expression(
                    "#version = :version AND (attribute_not_exists(#ttl) OR #ttl > :now)"
                        .to_string(),
                )
                .expression_attribute_names(HashMap::from([
                    ("#version".to_string(), "version".to_string()),
                    ("#ttl".to_string(), "ttl".to_string()),
                ]))
                .expression_attribute_values(HashMap::from([
                    (
                        ":version".to_string(),
                        AttributeValue::s(expected.backend_version),
                    ),
                    (
                        ":now".to_string(),
                        AttributeValue::n(Utc::now().timestamp().to_string()),
                    ),
                ]))
                .build()
        } else {
            PutItemRequest::builder()
                .table_name(self.table_name.clone())
                .item(item)
                .build()
        };

        match self.client.put_item(request).await {
            Ok(_) => Ok(true),
            Err(e) => {
                if !matches!(options.condition, PutCondition::None) {
                    if let Some(alien_client_core::ErrorData::RemoteResourceConflict { .. }) =
                        &e.error
                    {
                        return Ok(false);
                    }
                }
                Err(map_cloud_client_error(
                    e,
                    format!("Failed to put item with key '{}'", key),
                    Some(key.to_string()),
                ))
            }
        }
    }

    async fn delete(&self, key: &str, if_version: Option<&str>) -> Result<bool> {
        validate_key(key)?;

        let request = if let Some(version) = if_version {
            let expected = decode_version(key, version)?;
            if expected.expired {
                return Ok(false);
            }
            DeleteItemRequest::builder()
                .table_name(self.table_name.clone())
                .key(self.primary_key(key))
                .condition_expression(
                    "#version = :version AND (attribute_not_exists(#ttl) OR #ttl > :now)"
                        .to_string(),
                )
                .expression_attribute_names(HashMap::from([
                    ("#version".to_string(), "version".to_string()),
                    ("#ttl".to_string(), "ttl".to_string()),
                ]))
                .expression_attribute_values(HashMap::from([
                    (
                        ":version".to_string(),
                        AttributeValue::s(expected.backend_version),
                    ),
                    (
                        ":now".to_string(),
                        AttributeValue::n(Utc::now().timestamp().to_string()),
                    ),
                ]))
                .build()
        } else {
            DeleteItemRequest::builder()
                .table_name(self.table_name.clone())
                .key(self.primary_key(key))
                .build()
        };

        match self.client.delete_item(request).await {
            Ok(_) => Ok(true),
            Err(error)
                if if_version.is_some()
                    && matches!(
                        error.error.as_ref(),
                        Some(alien_client_core::ErrorData::RemoteResourceConflict { .. })
                    ) =>
            {
                Ok(false)
            }
            Err(error) => Err(map_cloud_client_error(
                error,
                format!("Failed to delete item with key '{}'", key),
                Some(key.to_string()),
            )),
        }
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        validate_key(key)?;

        let bucket = self.hash_bucket(key);
        let mut primary_key = HashMap::new();
        primary_key.insert("pk".to_string(), AttributeValue::s(bucket));
        primary_key.insert("sk".to_string(), AttributeValue::s(key.to_string()));

        // Use expression attribute names to avoid reserved keyword 'ttl'
        let mut expression_attribute_names = HashMap::new();
        expression_attribute_names.insert("#ttl".to_string(), "ttl".to_string());

        let request = GetItemRequest::builder()
            .table_name(self.table_name.clone())
            .key(primary_key)
            .projection_expression("pk, #ttl".to_string()) // Get key and TTL for expiry check
            .expression_attribute_names(expression_attribute_names)
            .consistent_read(true)
            .build();

        let response = self.client.get_item(request).await.map_err(|e| {
            map_cloud_client_error(
                e,
                format!("Failed to check existence of item with key '{}'", key),
                Some(key.to_string()),
            )
        })?;

        if let Some(item) = response.item {
            // Check TTL expiry (logical expiry contract)
            if let Some(ttl_attr) = item.get("ttl") {
                if let Some(ttl_epoch) = ttl_attr.n.as_ref().and_then(|s| s.parse::<i64>().ok()) {
                    if self.is_expired(Some(ttl_epoch)) {
                        return Ok(false); // Logically expired
                    }
                }
            }
            Ok(true)
        } else {
            Ok(false)
        }
    }

    async fn scan_prefix(
        &self,
        prefix: &str,
        limit: Option<usize>,
        cursor: Option<String>,
    ) -> Result<ScanResult> {
        validate_key(prefix)?;
        let limit = limit.unwrap_or(1000);
        let initial = cursor
            .as_deref()
            .map(|cursor| Self::decode_cursor(prefix, cursor))
            .transpose()?
            .unwrap_or(CursorState {
                version: 1,
                prefix: prefix.to_string(),
                bucket: 0,
                last_key: None,
            });
        if limit == 0 {
            return Ok(ScanResult {
                items: Vec::new(),
                next_cursor: cursor,
            });
        }

        let mut items = Vec::with_capacity(limit);
        let mut bucket_id = initial.bucket;
        let mut last_key = initial.last_key;

        while bucket_id < HASH_BUCKET_COUNT {
            let bucket = format!("bucket_{}", bucket_id);
            let mut expression_attribute_values = HashMap::new();
            expression_attribute_values
                .insert(":bucket".to_string(), AttributeValue::s(bucket.clone()));
            expression_attribute_values
                .insert(":prefix".to_string(), AttributeValue::s(prefix.to_string()));

            let exclusive_start_key = last_key.as_ref().map(|key| {
                HashMap::from([
                    ("pk".to_string(), AttributeValue::s(bucket.clone())),
                    ("sk".to_string(), AttributeValue::s(key.clone())),
                ])
            });
            let request = QueryRequest::builder()
                .table_name(self.table_name.clone())
                .key_condition_expression("pk = :bucket AND begins_with(sk, :prefix)".to_string())
                .expression_attribute_values(expression_attribute_values)
                .limit(i32::try_from(limit - items.len()).unwrap_or(i32::MAX))
                .maybe_exclusive_start_key(exclusive_start_key)
                .build();

            let response = self.client.query(request).await.map_err(|e| {
                map_cloud_client_error(
                    e,
                    format!("Failed to scan prefix '{}' in bucket {}", prefix, bucket_id),
                    Some(prefix.to_string()),
                )
            })?;

            for item in response.items {
                if let Some(ttl_attr) = item.get("ttl") {
                    if let Some(ttl_epoch) = ttl_attr.n.as_ref().and_then(|s| s.parse::<i64>().ok())
                    {
                        if self.is_expired(Some(ttl_epoch)) {
                            continue; // Skip expired items
                        }
                    }
                }

                if let (Some(key_attr), Some(value_attr)) = (item.get("sk"), item.get("value")) {
                    if let (Some(key), Some(base64_value)) =
                        (key_attr.s.as_ref(), value_attr.b.as_ref())
                    {
                        if let Ok(value) = base64::prelude::BASE64_STANDARD.decode(base64_value) {
                            let ttl = Self::item_ttl(&item);
                            if let Some(backend_version) =
                                item.get("version").and_then(|value| value.s.clone())
                            {
                                items.push(KvEntry {
                                    key: key.clone(),
                                    value,
                                    version: encode_version(
                                        key,
                                        backend_version,
                                        ttl.map(|expires_at| expires_at.saturating_mul(1000)),
                                    )?,
                                });
                            } else {
                                return Err(AlienError::new(ErrorData::CloudPlatformError {
                                    message: format!(
                                        "Missing or invalid version attribute for key '{}'",
                                        key
                                    ),
                                    resource_id: Some(key.clone()),
                                }));
                            }
                        }
                    }
                }
            }

            let provider_last_key = response
                .last_evaluated_key
                .as_ref()
                .and_then(|key| key.get("sk"))
                .and_then(|value| value.s.clone());

            if items.len() == limit {
                let (next_bucket, next_key) = match provider_last_key {
                    Some(key) => (bucket_id, Some(key)),
                    None if bucket_id + 1 < HASH_BUCKET_COUNT => (bucket_id + 1, None),
                    None => {
                        return Ok(ScanResult {
                            items,
                            next_cursor: None,
                        });
                    }
                };
                return Ok(ScanResult {
                    items,
                    next_cursor: Some(Self::encode_cursor(&CursorState {
                        version: 1,
                        prefix: prefix.to_string(),
                        bucket: next_bucket,
                        last_key: next_key,
                    })?),
                });
            }

            if let Some(key) = provider_last_key {
                last_key = Some(key);
            } else {
                bucket_id += 1;
                last_key = None;
            }
        }

        Ok(ScanResult {
            items,
            next_cursor: None,
        })
    }
}