winterbaume-keyspaces 0.2.0

Amazon Keyspaces service implementation for winterbaume
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
use aws_sdk_keyspaces::config::BehaviorVersion;
use winterbaume_core::MockAws;
use winterbaume_keyspaces::{KeyspacesService, KeyspacesStateView};

async fn make_client() -> aws_sdk_keyspaces::Client {
    let mock = MockAws::builder()
        .with_service(KeyspacesService::new())
        .build();
    let config = aws_config::defaults(BehaviorVersion::latest())
        .http_client(mock.http_client())
        .credentials_provider(mock.credentials_provider())
        .region(aws_sdk_keyspaces::config::Region::new("us-east-1"))
        .load()
        .await;
    aws_sdk_keyspaces::Client::new(&config)
}

// ---------- Keyspace CRUD ----------

#[tokio::test]
async fn test_create_and_get_keyspace() {
    let client = make_client().await;

    let create_resp = client
        .create_keyspace()
        .keyspace_name("my_ks")
        .send()
        .await
        .expect("create_keyspace should succeed");
    assert!(create_resp.resource_arn().contains("my_ks"));

    let get_resp = client
        .get_keyspace()
        .keyspace_name("my_ks")
        .send()
        .await
        .expect("get_keyspace should succeed");
    assert_eq!(get_resp.keyspace_name(), "my_ks");
    assert_eq!(get_resp.replication_strategy().as_str(), "SINGLE_REGION");
}

#[tokio::test]
async fn test_create_keyspace_duplicate() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("dup_ks")
        .send()
        .await
        .expect("first create should succeed");

    let err = client
        .create_keyspace()
        .keyspace_name("dup_ks")
        .send()
        .await
        .expect_err("duplicate create should fail");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("Conflict"),
        "expected ConflictException: {msg}"
    );
}

#[tokio::test]
async fn test_delete_keyspace() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("del_ks")
        .send()
        .await
        .unwrap();

    client
        .delete_keyspace()
        .keyspace_name("del_ks")
        .send()
        .await
        .expect("delete should succeed");

    let err = client
        .get_keyspace()
        .keyspace_name("del_ks")
        .send()
        .await
        .expect_err("get after delete should fail");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("ResourceNotFound"),
        "expected ResourceNotFoundException: {msg}"
    );
}

#[tokio::test]
async fn test_list_keyspaces() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("ks_a")
        .send()
        .await
        .unwrap();
    client
        .create_keyspace()
        .keyspace_name("ks_b")
        .send()
        .await
        .unwrap();

    let resp = client
        .list_keyspaces()
        .send()
        .await
        .expect("list should succeed");
    let names: Vec<_> = resp
        .keyspaces()
        .iter()
        .map(|ks| ks.keyspace_name().to_string())
        .collect();
    assert!(names.contains(&"ks_a".to_string()));
    assert!(names.contains(&"ks_b".to_string()));
}

#[tokio::test]
async fn test_update_keyspace() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("upd_ks")
        .send()
        .await
        .unwrap();

    let resp = client
        .update_keyspace()
        .keyspace_name("upd_ks")
        .replication_specification(
            aws_sdk_keyspaces::types::ReplicationSpecification::builder()
                .replication_strategy(aws_sdk_keyspaces::types::Rs::MultiRegion)
                .region_list("us-east-1")
                .region_list("us-west-2")
                .build()
                .unwrap(),
        )
        .send()
        .await
        .expect("update should succeed");
    assert!(resp.resource_arn().contains("upd_ks"));

    let get_resp = client
        .get_keyspace()
        .keyspace_name("upd_ks")
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.replication_strategy().as_str(), "MULTI_REGION");
}

// ---------- Table CRUD ----------

#[tokio::test]
async fn test_create_and_get_table() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("tbl_ks")
        .send()
        .await
        .unwrap();

    let schema = aws_sdk_keyspaces::types::SchemaDefinition::builder()
        .all_columns(
            aws_sdk_keyspaces::types::ColumnDefinition::builder()
                .name("id")
                .r#type("text")
                .build()
                .unwrap(),
        )
        .partition_keys(
            aws_sdk_keyspaces::types::PartitionKey::builder()
                .name("id")
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    let resp = client
        .create_table()
        .keyspace_name("tbl_ks")
        .table_name("my_table")
        .schema_definition(schema)
        .send()
        .await
        .expect("create_table should succeed");
    assert!(resp.resource_arn().contains("my_table"));

    let get = client
        .get_table()
        .keyspace_name("tbl_ks")
        .table_name("my_table")
        .send()
        .await
        .expect("get_table should succeed");
    assert_eq!(get.keyspace_name(), "tbl_ks");
    assert_eq!(get.table_name(), "my_table");
    assert_eq!(
        get.status().expect("status should be set").as_str(),
        "ACTIVE"
    );
}

#[tokio::test]
async fn test_delete_table() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("del_tbl_ks")
        .send()
        .await
        .unwrap();

    let schema = aws_sdk_keyspaces::types::SchemaDefinition::builder()
        .all_columns(
            aws_sdk_keyspaces::types::ColumnDefinition::builder()
                .name("pk")
                .r#type("text")
                .build()
                .unwrap(),
        )
        .partition_keys(
            aws_sdk_keyspaces::types::PartitionKey::builder()
                .name("pk")
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    client
        .create_table()
        .keyspace_name("del_tbl_ks")
        .table_name("del_tbl")
        .schema_definition(schema)
        .send()
        .await
        .unwrap();

    client
        .delete_table()
        .keyspace_name("del_tbl_ks")
        .table_name("del_tbl")
        .send()
        .await
        .expect("delete_table should succeed");

    let err = client
        .get_table()
        .keyspace_name("del_tbl_ks")
        .table_name("del_tbl")
        .send()
        .await
        .expect_err("get after delete should fail");
    assert!(format!("{err:?}").contains("ResourceNotFound"));
}

#[tokio::test]
async fn test_list_tables() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("list_ks")
        .send()
        .await
        .unwrap();

    for name in &["tbl_1", "tbl_2"] {
        let schema = aws_sdk_keyspaces::types::SchemaDefinition::builder()
            .all_columns(
                aws_sdk_keyspaces::types::ColumnDefinition::builder()
                    .name("pk")
                    .r#type("text")
                    .build()
                    .unwrap(),
            )
            .partition_keys(
                aws_sdk_keyspaces::types::PartitionKey::builder()
                    .name("pk")
                    .build()
                    .unwrap(),
            )
            .build()
            .unwrap();

        client
            .create_table()
            .keyspace_name("list_ks")
            .table_name(*name)
            .schema_definition(schema)
            .send()
            .await
            .unwrap();
    }

    let resp = client
        .list_tables()
        .keyspace_name("list_ks")
        .send()
        .await
        .expect("list_tables should succeed");
    let names: Vec<_> = resp
        .tables()
        .iter()
        .map(|t| t.table_name().to_string())
        .collect();
    assert_eq!(names.len(), 2);
    assert!(names.contains(&"tbl_1".to_string()));
    assert!(names.contains(&"tbl_2".to_string()));
}

// ---------- Tag operations ----------

#[tokio::test]
async fn test_tag_and_list_tags() {
    let client = make_client().await;

    let resp = client
        .create_keyspace()
        .keyspace_name("tag_ks")
        .send()
        .await
        .unwrap();
    let arn = resp.resource_arn().to_string();

    client
        .tag_resource()
        .resource_arn(&arn)
        .tags(
            aws_sdk_keyspaces::types::Tag::builder()
                .key("env")
                .value("test")
                .build()
                .unwrap(),
        )
        .send()
        .await
        .expect("tag_resource should succeed");

    let tags_resp = client
        .list_tags_for_resource()
        .resource_arn(&arn)
        .send()
        .await
        .expect("list_tags should succeed");
    let tags = tags_resp.tags();
    assert_eq!(tags.len(), 1);
    assert_eq!(tags[0].key(), "env");
    assert_eq!(tags[0].value(), "test");

    // Untag
    client
        .untag_resource()
        .resource_arn(&arn)
        .tags(
            aws_sdk_keyspaces::types::Tag::builder()
                .key("env")
                .value("test")
                .build()
                .unwrap(),
        )
        .send()
        .await
        .expect("untag should succeed");

    let tags_resp = client
        .list_tags_for_resource()
        .resource_arn(&arn)
        .send()
        .await
        .unwrap();
    assert!(tags_resp.tags().is_empty());
}

// ---------- Restore table ----------

#[tokio::test]
async fn test_restore_table() {
    let client = make_client().await;

    client
        .create_keyspace()
        .keyspace_name("restore_ks")
        .send()
        .await
        .unwrap();

    let schema = aws_sdk_keyspaces::types::SchemaDefinition::builder()
        .all_columns(
            aws_sdk_keyspaces::types::ColumnDefinition::builder()
                .name("pk")
                .r#type("text")
                .build()
                .unwrap(),
        )
        .partition_keys(
            aws_sdk_keyspaces::types::PartitionKey::builder()
                .name("pk")
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    client
        .create_table()
        .keyspace_name("restore_ks")
        .table_name("src_table")
        .schema_definition(schema)
        .send()
        .await
        .unwrap();

    let resp = client
        .restore_table()
        .source_keyspace_name("restore_ks")
        .source_table_name("src_table")
        .target_keyspace_name("restore_ks")
        .target_table_name("dst_table")
        .send()
        .await
        .expect("restore_table should succeed");
    assert!(resp.restored_table_arn().contains("dst_table"));

    // Verify the restored table exists
    let get = client
        .get_table()
        .keyspace_name("restore_ks")
        .table_name("dst_table")
        .send()
        .await
        .expect("get restored table should succeed");
    assert_eq!(get.table_name(), "dst_table");
}

// ---------- Error paths ----------

#[tokio::test]
async fn test_get_nonexistent_keyspace() {
    let client = make_client().await;

    let err = client
        .get_keyspace()
        .keyspace_name("no_such_ks")
        .send()
        .await
        .expect_err("should fail");
    assert!(format!("{err:?}").contains("ResourceNotFound"));
}

#[tokio::test]
async fn test_create_table_in_nonexistent_keyspace() {
    let client = make_client().await;

    let schema = aws_sdk_keyspaces::types::SchemaDefinition::builder()
        .all_columns(
            aws_sdk_keyspaces::types::ColumnDefinition::builder()
                .name("pk")
                .r#type("text")
                .build()
                .unwrap(),
        )
        .partition_keys(
            aws_sdk_keyspaces::types::PartitionKey::builder()
                .name("pk")
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    let err = client
        .create_table()
        .keyspace_name("no_such_ks")
        .table_name("tbl")
        .schema_definition(schema)
        .send()
        .await
        .expect_err("should fail");
    assert!(format!("{err:?}").contains("ResourceNotFound"));
}

// ---------- State views ----------

#[tokio::test]
async fn test_snapshot_restore() {
    use winterbaume_core::StatefulService;
    let svc = KeyspacesService::new();

    // Create some state via a view
    let mut initial_view = KeyspacesStateView::default();
    initial_view.keyspaces.insert(
        "snap_ks".to_string(),
        winterbaume_keyspaces::views::KeyspaceView {
            name: "snap_ks".to_string(),
            arn: "arn:aws:cassandra:us-east-1:123456789012:/keyspace/snap_ks/".to_string(),
            replication_strategy: "SINGLE_REGION".to_string(),
            replication_regions: vec![],
            tags: Default::default(),
            creation_timestamp: None,
            status: "ACTIVE".to_string(),
        },
    );
    svc.restore("123456789012", "us-east-1", initial_view)
        .await
        .unwrap();

    let view = svc.snapshot("123456789012", "us-east-1").await;
    assert!(view.keyspaces.contains_key("snap_ks"));

    // Restore to different scope
    svc.restore("123456789012", "eu-west-1", view.clone())
        .await
        .unwrap();
    let view2 = svc.snapshot("123456789012", "eu-west-1").await;
    assert!(view2.keyspaces.contains_key("snap_ks"));
}

#[tokio::test]
async fn test_merge_additive() {
    use winterbaume_core::StatefulService;
    let svc = KeyspacesService::new();

    // Create initial state via restore
    let mut initial = KeyspacesStateView::default();
    initial.keyspaces.insert(
        "existing_ks".to_string(),
        winterbaume_keyspaces::views::KeyspaceView {
            name: "existing_ks".to_string(),
            arn: "arn:aws:cassandra:us-east-1:123456789012:/keyspace/existing_ks/".to_string(),
            replication_strategy: "SINGLE_REGION".to_string(),
            replication_regions: vec![],
            tags: Default::default(),
            creation_timestamp: None,
            status: "ACTIVE".to_string(),
        },
    );
    svc.restore("123456789012", "us-east-1", initial)
        .await
        .unwrap();

    // Merge new keyspace
    let mut view = KeyspacesStateView::default();
    view.keyspaces.insert(
        "merged_ks".to_string(),
        winterbaume_keyspaces::views::KeyspaceView {
            name: "merged_ks".to_string(),
            arn: "arn:aws:cassandra:us-east-1:123456789012:/keyspace/merged_ks/".to_string(),
            replication_strategy: "SINGLE_REGION".to_string(),
            replication_regions: vec![],
            tags: Default::default(),
            creation_timestamp: None,
            status: "ACTIVE".to_string(),
        },
    );

    svc.merge("123456789012", "us-east-1", view).await.unwrap();

    let snap = svc.snapshot("123456789012", "us-east-1").await;
    // Both keyspaces should exist
    assert!(snap.keyspaces.contains_key("existing_ks"));
    assert!(snap.keyspaces.contains_key("merged_ks"));
}

// ---------- State change notifications ----------

#[tokio::test]
async fn test_state_change_listener_fires() {
    use std::sync::{Arc, Mutex};

    use winterbaume_core::StatefulService;
    let svc = KeyspacesService::new();
    let events: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(vec![]));
    let events2 = Arc::clone(&events);
    svc.notifier().subscribe(move |account_id, region, _view| {
        events2
            .lock()
            .unwrap()
            .push((account_id.to_string(), region.to_string()));
    });

    svc.restore("123456789012", "us-east-1", Default::default())
        .await
        .unwrap();
    let got = events.lock().unwrap();
    assert_eq!(got.len(), 1);
    assert_eq!(
        got[0],
        ("123456789012".to_string(), "us-east-1".to_string())
    );
}

#[tokio::test]
async fn test_state_change_listener_snapshot_reflects_mutation() {
    use std::sync::{Arc, Mutex};

    use winterbaume_core::StatefulService;
    let svc = KeyspacesService::new();

    // Pre-seed state
    let mut view = KeyspacesStateView::default();
    view.keyspaces.insert(
        "notified_ks".to_string(),
        winterbaume_keyspaces::views::KeyspaceView {
            name: "notified_ks".to_string(),
            arn: "arn:aws:cassandra:us-east-1:123456789012:/keyspace/notified_ks/".to_string(),
            replication_strategy: "SINGLE_REGION".to_string(),
            replication_regions: vec![],
            tags: Default::default(),
            creation_timestamp: None,
            status: "ACTIVE".to_string(),
        },
    );
    svc.restore("123456789012", "us-east-1", view)
        .await
        .unwrap();

    // Re-register and capture snapshot
    let snapshots: Arc<Mutex<Vec<KeyspacesStateView>>> = Arc::new(Mutex::new(vec![]));
    let snapshots2 = Arc::clone(&snapshots);
    svc.notifier().subscribe(move |_account_id, _region, view| {
        snapshots2.lock().unwrap().push(view.clone());
    });

    let mut view2 = KeyspacesStateView::default();
    view2.keyspaces.insert(
        "notified_ks_2".to_string(),
        winterbaume_keyspaces::views::KeyspaceView {
            name: "notified_ks_2".to_string(),
            arn: "arn:aws:cassandra:us-east-1:123456789012:/keyspace/notified_ks_2/".to_string(),
            replication_strategy: "SINGLE_REGION".to_string(),
            replication_regions: vec![],
            tags: Default::default(),
            creation_timestamp: None,
            status: "ACTIVE".to_string(),
        },
    );
    svc.restore("123456789012", "us-east-1", view2)
        .await
        .unwrap();
    let got = snapshots.lock().unwrap();
    assert_eq!(got.len(), 1);
    assert!(got[0].keyspaces.contains_key("notified_ks_2"));
}