streamstore 0.21.1

DEPRECATED: Use s2-sdk instead
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
//! Types for interacting with S2 services.

use std::{
    collections::HashSet,
    ops::{Deref, RangeTo},
    str::FromStr,
    sync::OnceLock,
    time::Duration,
};

use bytes::Bytes;
use rand::Rng;
use regex::Regex;
use sync_docs::sync_docs;

use crate::api;

pub(crate) const MIB_BYTES: u64 = 1024 * 1024;
pub(crate) const RETRY_AFTER_MS_METADATA_KEY: &str = "retry-after-ms";

/// Error related to conversion from one type to another.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{0}")]
pub struct ConvertError(String);

impl<T: Into<String>> From<T> for ConvertError {
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

/// Metered size of the object in bytes.
///
/// Bytes are calculated using the "metered bytes" formula:
///
/// ```python
/// metered_bytes = lambda record: 8 + 2 * len(record.headers) + sum((len(h.key) + len(h.value)) for h in record.headers) + len(record.body)
/// ```
pub trait MeteredBytes {
    /// Return the metered bytes of the object.
    fn metered_bytes(&self) -> u64;
}

impl<T: MeteredBytes> MeteredBytes for Vec<T> {
    fn metered_bytes(&self) -> u64 {
        self.iter().fold(0, |acc, item| acc + item.metered_bytes())
    }
}

macro_rules! metered_impl {
    ($ty:ty) => {
        impl MeteredBytes for $ty {
            fn metered_bytes(&self) -> u64 {
                let bytes = 8
                    + (2 * self.headers.len())
                    + self
                        .headers
                        .iter()
                        .map(|h| h.name.len() + h.value.len())
                        .sum::<usize>()
                    + self.body.len();
                bytes as u64
            }
        }
    };
}

#[sync_docs]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BasinScope {
    AwsUsEast1,
}

impl From<BasinScope> for api::BasinScope {
    fn from(value: BasinScope) -> Self {
        match value {
            BasinScope::AwsUsEast1 => Self::AwsUsEast1,
        }
    }
}

impl From<api::BasinScope> for Option<BasinScope> {
    fn from(value: api::BasinScope) -> Self {
        match value {
            api::BasinScope::Unspecified => None,
            api::BasinScope::AwsUsEast1 => Some(BasinScope::AwsUsEast1),
        }
    }
}

impl FromStr for BasinScope {
    type Err = ConvertError;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "aws:us-east-1" => Ok(Self::AwsUsEast1),
            _ => Err("invalid basin scope value".into()),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct CreateBasinRequest {
    pub basin: BasinName,
    pub config: Option<BasinConfig>,
    pub scope: Option<BasinScope>,
}

impl CreateBasinRequest {
    /// Create a new request with basin name.
    pub fn new(basin: BasinName) -> Self {
        Self {
            basin,
            config: None,
            scope: None,
        }
    }

    /// Overwrite basin configuration.
    pub fn with_config(self, config: BasinConfig) -> Self {
        Self {
            config: Some(config),
            ..self
        }
    }

    /// Overwrite basin scope.
    pub fn with_scope(self, scope: BasinScope) -> Self {
        Self {
            scope: Some(scope),
            ..self
        }
    }
}

impl From<CreateBasinRequest> for api::CreateBasinRequest {
    fn from(value: CreateBasinRequest) -> Self {
        let CreateBasinRequest {
            basin,
            config,
            scope,
        } = value;
        Self {
            basin: basin.0,
            config: config.map(Into::into),
            scope: scope.map(api::BasinScope::from).unwrap_or_default().into(),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct BasinConfig {
    pub default_stream_config: Option<StreamConfig>,
    pub create_stream_on_append: bool,
    pub create_stream_on_read: bool,
}

impl BasinConfig {
    /// Create a new basin config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite the default stream config.
    pub fn with_default_stream_config(self, default_stream_config: StreamConfig) -> Self {
        Self {
            default_stream_config: Some(default_stream_config),
            ..self
        }
    }

    /// Overwrite `create_stream_on_append`.
    pub fn with_create_stream_on_append(self, create_stream_on_append: bool) -> Self {
        Self {
            create_stream_on_append,
            ..self
        }
    }

    /// Overwrite `create_stream_on_read`.
    pub fn with_create_stream_on_read(self, create_stream_on_read: bool) -> Self {
        Self {
            create_stream_on_read,
            ..self
        }
    }
}

impl From<BasinConfig> for api::BasinConfig {
    fn from(value: BasinConfig) -> Self {
        let BasinConfig {
            default_stream_config,
            create_stream_on_append,
            create_stream_on_read,
        } = value;
        Self {
            default_stream_config: default_stream_config.map(Into::into),
            create_stream_on_append,
            create_stream_on_read,
        }
    }
}

impl From<api::BasinConfig> for BasinConfig {
    fn from(value: api::BasinConfig) -> Self {
        let api::BasinConfig {
            default_stream_config,
            create_stream_on_append,
            create_stream_on_read,
        } = value;
        Self {
            default_stream_config: default_stream_config.map(Into::into),
            create_stream_on_append,
            create_stream_on_read,
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimestampingMode {
    ClientPrefer,
    ClientRequire,
    Arrival,
}

impl From<TimestampingMode> for api::TimestampingMode {
    fn from(value: TimestampingMode) -> Self {
        match value {
            TimestampingMode::ClientPrefer => Self::ClientPrefer,
            TimestampingMode::ClientRequire => Self::ClientRequire,
            TimestampingMode::Arrival => Self::Arrival,
        }
    }
}

impl From<api::TimestampingMode> for Option<TimestampingMode> {
    fn from(value: api::TimestampingMode) -> Self {
        match value {
            api::TimestampingMode::Unspecified => None,
            api::TimestampingMode::ClientPrefer => Some(TimestampingMode::ClientPrefer),
            api::TimestampingMode::ClientRequire => Some(TimestampingMode::ClientRequire),
            api::TimestampingMode::Arrival => Some(TimestampingMode::Arrival),
        }
    }
}

#[sync_docs(TimestampingConfig = "Timestamping")]
#[derive(Debug, Clone, Default)]
/// Timestamping behavior.
pub struct TimestampingConfig {
    pub mode: Option<TimestampingMode>,
    pub uncapped: Option<bool>,
}

impl TimestampingConfig {
    /// Create a new timestamping config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite timestamping mode.
    pub fn with_mode(self, mode: TimestampingMode) -> Self {
        Self {
            mode: Some(mode),
            ..self
        }
    }

    /// Overwrite the uncapped knob.
    pub fn with_uncapped(self, uncapped: bool) -> Self {
        Self {
            uncapped: Some(uncapped),
            ..self
        }
    }
}

impl From<TimestampingConfig> for api::stream_config::Timestamping {
    fn from(value: TimestampingConfig) -> Self {
        Self {
            mode: value
                .mode
                .map(api::TimestampingMode::from)
                .unwrap_or_default()
                .into(),
            uncapped: value.uncapped,
        }
    }
}

impl From<api::stream_config::Timestamping> for TimestampingConfig {
    fn from(value: api::stream_config::Timestamping) -> Self {
        let mode = value.mode().into();
        let uncapped = value.uncapped;
        Self { mode, uncapped }
    }
}

#[sync_docs(DeleteOnEmptyConfig = "DeleteOnEmpty", min_age = "min_age_secs")]
#[derive(Debug, Clone, Default)]
/// Delete-on-empty config.
pub struct DeleteOnEmptyConfig {
    pub min_age: Duration,
}

impl DeleteOnEmptyConfig {
    /// Create a new delete-on-empty config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite min age.
    pub fn with_min_age(self, min_age: Duration) -> Self {
        Self { min_age }
    }
}

impl From<DeleteOnEmptyConfig> for api::stream_config::DeleteOnEmpty {
    fn from(value: DeleteOnEmptyConfig) -> Self {
        Self {
            min_age_secs: value.min_age.as_secs(),
        }
    }
}

impl From<api::stream_config::DeleteOnEmpty> for DeleteOnEmptyConfig {
    fn from(value: api::stream_config::DeleteOnEmpty) -> Self {
        Self {
            min_age: Duration::from_secs(value.min_age_secs),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct StreamConfig {
    pub storage_class: Option<StorageClass>,
    pub retention_policy: Option<RetentionPolicy>,
    pub timestamping: Option<TimestampingConfig>,
    pub delete_on_empty: Option<DeleteOnEmptyConfig>,
}

impl StreamConfig {
    /// Create a new stream config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite storage class.
    pub fn with_storage_class(self, storage_class: StorageClass) -> Self {
        Self {
            storage_class: Some(storage_class),
            ..self
        }
    }

    /// Overwrite retention policy.
    pub fn with_retention_policy(self, retention_policy: RetentionPolicy) -> Self {
        Self {
            retention_policy: Some(retention_policy),
            ..self
        }
    }

    /// Overwrite timestamping config.
    pub fn with_timestamping(self, timestamping: TimestampingConfig) -> Self {
        Self {
            timestamping: Some(timestamping),
            ..self
        }
    }

    /// Overwrite delete-on-empty config.
    pub fn with_delete_on_empty(self, delete_on_empty: DeleteOnEmptyConfig) -> Self {
        Self {
            delete_on_empty: Some(delete_on_empty),
            ..self
        }
    }
}

impl From<StreamConfig> for api::StreamConfig {
    fn from(value: StreamConfig) -> Self {
        let StreamConfig {
            storage_class,
            retention_policy,
            timestamping,
            delete_on_empty,
        } = value;
        Self {
            storage_class: storage_class
                .map(api::StorageClass::from)
                .unwrap_or_default()
                .into(),
            retention_policy: retention_policy.map(Into::into),
            timestamping: timestamping.map(Into::into),
            delete_on_empty: delete_on_empty.map(Into::into),
        }
    }
}

impl From<api::StreamConfig> for StreamConfig {
    fn from(value: api::StreamConfig) -> Self {
        Self {
            storage_class: value.storage_class().into(),
            retention_policy: value.retention_policy.map(Into::into),
            timestamping: value.timestamping.map(Into::into),
            delete_on_empty: value.delete_on_empty.map(Into::into),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageClass {
    Standard,
    Express,
}

impl From<StorageClass> for api::StorageClass {
    fn from(value: StorageClass) -> Self {
        match value {
            StorageClass::Standard => Self::Standard,
            StorageClass::Express => Self::Express,
        }
    }
}

impl From<api::StorageClass> for Option<StorageClass> {
    fn from(value: api::StorageClass) -> Self {
        match value {
            api::StorageClass::Unspecified => None,
            api::StorageClass::Standard => Some(StorageClass::Standard),
            api::StorageClass::Express => Some(StorageClass::Express),
        }
    }
}

impl FromStr for StorageClass {
    type Err = ConvertError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "standard" => Ok(Self::Standard),
            "express" => Ok(Self::Express),
            v => Err(format!("unknown storage class: {v}").into()),
        }
    }
}

#[sync_docs(Age = "Age")]
#[derive(Debug, Clone)]
pub enum RetentionPolicy {
    Age(Duration),
    Infinite(()),
}

impl From<RetentionPolicy> for api::stream_config::RetentionPolicy {
    fn from(value: RetentionPolicy) -> Self {
        match value {
            RetentionPolicy::Age(duration) => Self::Age(duration.as_secs()),
            RetentionPolicy::Infinite(_) => {
                Self::Infinite(api::stream_config::InfiniteRetention {})
            }
        }
    }
}

impl From<api::stream_config::RetentionPolicy> for RetentionPolicy {
    fn from(value: api::stream_config::RetentionPolicy) -> Self {
        match value {
            api::stream_config::RetentionPolicy::Age(secs) => Self::Age(Duration::from_secs(secs)),
            api::stream_config::RetentionPolicy::Infinite(_) => Self::Infinite(()),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BasinState {
    Active,
    Creating,
    Deleting,
}

impl From<BasinState> for api::BasinState {
    fn from(value: BasinState) -> Self {
        match value {
            BasinState::Active => Self::Active,
            BasinState::Creating => Self::Creating,
            BasinState::Deleting => Self::Deleting,
        }
    }
}

impl From<api::BasinState> for Option<BasinState> {
    fn from(value: api::BasinState) -> Self {
        match value {
            api::BasinState::Unspecified => None,
            api::BasinState::Active => Some(BasinState::Active),
            api::BasinState::Creating => Some(BasinState::Creating),
            api::BasinState::Deleting => Some(BasinState::Deleting),
        }
    }
}

impl std::fmt::Display for BasinState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BasinState::Active => write!(f, "active"),
            BasinState::Creating => write!(f, "creating"),
            BasinState::Deleting => write!(f, "deleting"),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct BasinInfo {
    pub name: String,
    pub scope: Option<BasinScope>,
    pub state: Option<BasinState>,
}

impl From<BasinInfo> for api::BasinInfo {
    fn from(value: BasinInfo) -> Self {
        let BasinInfo { name, scope, state } = value;
        Self {
            name,
            scope: scope.map(api::BasinScope::from).unwrap_or_default().into(),
            state: state.map(api::BasinState::from).unwrap_or_default().into(),
        }
    }
}

impl From<api::BasinInfo> for BasinInfo {
    fn from(value: api::BasinInfo) -> Self {
        let scope = value.scope().into();
        let state = value.state().into();
        let name = value.name;
        Self { name, scope, state }
    }
}

impl TryFrom<api::CreateBasinResponse> for BasinInfo {
    type Error = ConvertError;
    fn try_from(value: api::CreateBasinResponse) -> Result<Self, Self::Error> {
        let api::CreateBasinResponse { info } = value;
        let info = info.ok_or("missing basin info")?;
        Ok(info.into())
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ListStreamsRequest {
    pub prefix: String,
    pub start_after: String,
    pub limit: Option<usize>,
}

impl ListStreamsRequest {
    /// Create a new request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite prefix.
    pub fn with_prefix(self, prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            ..self
        }
    }

    /// Overwrite start after.
    pub fn with_start_after(self, start_after: impl Into<String>) -> Self {
        Self {
            start_after: start_after.into(),
            ..self
        }
    }

    /// Overwrite limit.
    pub fn with_limit(self, limit: impl Into<Option<usize>>) -> Self {
        Self {
            limit: limit.into(),
            ..self
        }
    }
}

impl TryFrom<ListStreamsRequest> for api::ListStreamsRequest {
    type Error = ConvertError;
    fn try_from(value: ListStreamsRequest) -> Result<Self, Self::Error> {
        let ListStreamsRequest {
            prefix,
            start_after,
            limit,
        } = value;
        Ok(Self {
            prefix,
            start_after,
            limit: limit.map(|n| n as u64),
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct StreamInfo {
    pub name: String,
    pub created_at: u32,
    pub deleted_at: Option<u32>,
}

impl From<api::StreamInfo> for StreamInfo {
    fn from(value: api::StreamInfo) -> Self {
        Self {
            name: value.name,
            created_at: value.created_at,
            deleted_at: value.deleted_at,
        }
    }
}

impl TryFrom<api::CreateStreamResponse> for StreamInfo {
    type Error = ConvertError;

    fn try_from(value: api::CreateStreamResponse) -> Result<Self, Self::Error> {
        let api::CreateStreamResponse { info } = value;
        let info = info.ok_or("missing stream info")?;
        Ok(info.into())
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct ListStreamsResponse {
    pub streams: Vec<StreamInfo>,
    pub has_more: bool,
}

impl From<api::ListStreamsResponse> for ListStreamsResponse {
    fn from(value: api::ListStreamsResponse) -> Self {
        let api::ListStreamsResponse { streams, has_more } = value;
        let streams = streams.into_iter().map(Into::into).collect();
        Self { streams, has_more }
    }
}

impl TryFrom<api::GetBasinConfigResponse> for BasinConfig {
    type Error = ConvertError;

    fn try_from(value: api::GetBasinConfigResponse) -> Result<Self, Self::Error> {
        let api::GetBasinConfigResponse { config } = value;
        let config = config.ok_or("missing basin config")?;
        Ok(config.into())
    }
}

impl TryFrom<api::GetStreamConfigResponse> for StreamConfig {
    type Error = ConvertError;

    fn try_from(value: api::GetStreamConfigResponse) -> Result<Self, Self::Error> {
        let api::GetStreamConfigResponse { config } = value;
        let config = config.ok_or("missing stream config")?;
        Ok(config.into())
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct CreateStreamRequest {
    pub stream: String,
    pub config: Option<StreamConfig>,
}

impl CreateStreamRequest {
    /// Create a new request with stream name.
    pub fn new(stream: impl Into<String>) -> Self {
        Self {
            stream: stream.into(),
            config: None,
        }
    }

    /// Overwrite stream config.
    pub fn with_config(self, config: StreamConfig) -> Self {
        Self {
            config: Some(config),
            ..self
        }
    }
}

impl From<CreateStreamRequest> for api::CreateStreamRequest {
    fn from(value: CreateStreamRequest) -> Self {
        let CreateStreamRequest { stream, config } = value;
        Self {
            stream,
            config: config.map(Into::into),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ListBasinsRequest {
    pub prefix: String,
    pub start_after: String,
    pub limit: Option<usize>,
}

impl ListBasinsRequest {
    /// Create a new request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite prefix.
    pub fn with_prefix(self, prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            ..self
        }
    }

    /// Overwrite start after.
    pub fn with_start_after(self, start_after: impl Into<String>) -> Self {
        Self {
            start_after: start_after.into(),
            ..self
        }
    }

    /// Overwrite limit.
    pub fn with_limit(self, limit: impl Into<Option<usize>>) -> Self {
        Self {
            limit: limit.into(),
            ..self
        }
    }
}

impl TryFrom<ListBasinsRequest> for api::ListBasinsRequest {
    type Error = ConvertError;
    fn try_from(value: ListBasinsRequest) -> Result<Self, Self::Error> {
        let ListBasinsRequest {
            prefix,
            start_after,
            limit,
        } = value;
        Ok(Self {
            prefix,
            start_after,
            limit: limit
                .map(TryInto::try_into)
                .transpose()
                .map_err(|_| "request limit does not fit into u64 bounds")?,
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct ListBasinsResponse {
    pub basins: Vec<BasinInfo>,
    pub has_more: bool,
}

impl TryFrom<api::ListBasinsResponse> for ListBasinsResponse {
    type Error = ConvertError;
    fn try_from(value: api::ListBasinsResponse) -> Result<Self, ConvertError> {
        let api::ListBasinsResponse { basins, has_more } = value;
        Ok(Self {
            basins: basins.into_iter().map(Into::into).collect(),
            has_more,
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct DeleteBasinRequest {
    pub basin: BasinName,
    /// Delete basin if it exists else do nothing.
    pub if_exists: bool,
}

impl DeleteBasinRequest {
    /// Create a new request.
    pub fn new(basin: BasinName) -> Self {
        Self {
            basin,
            if_exists: false,
        }
    }

    /// Overwrite the if exists parameter.
    pub fn with_if_exists(self, if_exists: bool) -> Self {
        Self { if_exists, ..self }
    }
}

impl From<DeleteBasinRequest> for api::DeleteBasinRequest {
    fn from(value: DeleteBasinRequest) -> Self {
        let DeleteBasinRequest { basin, .. } = value;
        Self { basin: basin.0 }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct DeleteStreamRequest {
    pub stream: String,
    /// Delete stream if it exists else do nothing.
    pub if_exists: bool,
}

impl DeleteStreamRequest {
    /// Create a new request.
    pub fn new(stream: impl Into<String>) -> Self {
        Self {
            stream: stream.into(),
            if_exists: false,
        }
    }

    /// Overwrite the if exists parameter.
    pub fn with_if_exists(self, if_exists: bool) -> Self {
        Self { if_exists, ..self }
    }
}

impl From<DeleteStreamRequest> for api::DeleteStreamRequest {
    fn from(value: DeleteStreamRequest) -> Self {
        let DeleteStreamRequest { stream, .. } = value;
        Self { stream }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct ReconfigureBasinRequest {
    pub basin: BasinName,
    pub config: Option<BasinConfig>,
    pub mask: Option<Vec<String>>,
}

impl ReconfigureBasinRequest {
    /// Create a new request with basin name.
    pub fn new(basin: BasinName) -> Self {
        Self {
            basin,
            config: None,
            mask: None,
        }
    }

    /// Overwrite basin config.
    pub fn with_config(self, config: BasinConfig) -> Self {
        Self {
            config: Some(config),
            ..self
        }
    }

    /// Overwrite field mask.
    pub fn with_mask(self, mask: impl Into<Vec<String>>) -> Self {
        Self {
            mask: Some(mask.into()),
            ..self
        }
    }
}

impl From<ReconfigureBasinRequest> for api::ReconfigureBasinRequest {
    fn from(value: ReconfigureBasinRequest) -> Self {
        let ReconfigureBasinRequest {
            basin,
            config,
            mask,
        } = value;
        Self {
            basin: basin.0,
            config: config.map(Into::into),
            mask: mask.map(|paths| prost_types::FieldMask { paths }),
        }
    }
}

impl TryFrom<api::ReconfigureBasinResponse> for BasinConfig {
    type Error = ConvertError;
    fn try_from(value: api::ReconfigureBasinResponse) -> Result<Self, Self::Error> {
        let api::ReconfigureBasinResponse { config } = value;
        let config = config.ok_or("missing basin config")?;
        Ok(config.into())
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct ReconfigureStreamRequest {
    pub stream: String,
    pub config: Option<StreamConfig>,
    pub mask: Option<Vec<String>>,
}

impl ReconfigureStreamRequest {
    /// Create a new request with stream name.
    pub fn new(stream: impl Into<String>) -> Self {
        Self {
            stream: stream.into(),
            config: None,
            mask: None,
        }
    }

    /// Overwrite stream config.
    pub fn with_config(self, config: StreamConfig) -> Self {
        Self {
            config: Some(config),
            ..self
        }
    }

    /// Overwrite field mask.
    pub fn with_mask(self, mask: impl Into<Vec<String>>) -> Self {
        Self {
            mask: Some(mask.into()),
            ..self
        }
    }
}

impl From<ReconfigureStreamRequest> for api::ReconfigureStreamRequest {
    fn from(value: ReconfigureStreamRequest) -> Self {
        let ReconfigureStreamRequest {
            stream,
            config,
            mask,
        } = value;
        Self {
            stream,
            config: config.map(Into::into),
            mask: mask.map(|paths| prost_types::FieldMask { paths }),
        }
    }
}

impl TryFrom<api::ReconfigureStreamResponse> for StreamConfig {
    type Error = ConvertError;
    fn try_from(value: api::ReconfigureStreamResponse) -> Result<Self, Self::Error> {
        let api::ReconfigureStreamResponse { config } = value;
        let config = config.ok_or("missing stream config")?;
        Ok(config.into())
    }
}

impl From<api::CheckTailResponse> for StreamPosition {
    fn from(value: api::CheckTailResponse) -> Self {
        let api::CheckTailResponse {
            next_seq_num,
            last_timestamp,
        } = value;
        StreamPosition {
            seq_num: next_seq_num,
            timestamp: last_timestamp,
        }
    }
}

/// Position of a record in a stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamPosition {
    /// Sequence number assigned by the service.
    pub seq_num: u64,
    /// Timestamp, which may be user-specified or assigned by the service.
    /// If it is assigned by the service, it will represent milliseconds since Unix epoch.
    pub timestamp: u64,
}

#[sync_docs]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Header {
    pub name: Bytes,
    pub value: Bytes,
}

impl Header {
    /// Create a new header from name and value.
    pub fn new(name: impl Into<Bytes>, value: impl Into<Bytes>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }

    /// Create a new header from value.
    pub fn from_value(value: impl Into<Bytes>) -> Self {
        Self {
            name: Bytes::new(),
            value: value.into(),
        }
    }
}

impl From<Header> for api::Header {
    fn from(value: Header) -> Self {
        let Header { name, value } = value;
        Self { name, value }
    }
}

impl From<api::Header> for Header {
    fn from(value: api::Header) -> Self {
        let api::Header { name, value } = value;
        Self { name, value }
    }
}

/// A fencing token can be enforced on append requests.
///
/// Must not be more than 36 bytes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FencingToken(String);

impl FencingToken {
    const MAX_BYTES: usize = 36;

    /// Generate a random alphanumeric fencing token of `n` bytes.
    pub fn generate(n: usize) -> Result<Self, ConvertError> {
        rand::rng()
            .sample_iter(&rand::distr::Alphanumeric)
            .take(n)
            .map(char::from)
            .collect::<String>()
            .parse()
    }
}

impl Deref for FencingToken {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::Display for FencingToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for FencingToken {
    type Err = ConvertError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        value.to_string().try_into()
    }
}

impl TryFrom<String> for FencingToken {
    type Error = ConvertError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.len() > Self::MAX_BYTES {
            Err(format!("Fencing token cannot exceed {} bytes", Self::MAX_BYTES).into())
        } else {
            Ok(Self(value))
        }
    }
}

impl From<FencingToken> for String {
    fn from(value: FencingToken) -> Self {
        value.0
    }
}

/// Command to send through a `CommandRecord`.
#[derive(Debug, Clone)]
pub enum Command {
    /// Enforce a fencing token.
    ///
    /// Fencing is strongly consistent, and subsequent appends that specify a
    /// fencing token will be rejected if it does not match.
    Fence {
        /// Fencing token to enforce.
        ///
        /// Set empty to clear the token.
        fencing_token: FencingToken,
    },
    /// Request a trim till the sequence number.
    ///
    /// Trimming is eventually consistent, and trimmed records may be visible
    /// for a brief period
    Trim {
        /// Trim point.
        ///
        /// This sequence number is only allowed to advance, and any regression
        /// will be ignored.
        seq_num: u64,
    },
}

/// A command record is a special kind of [`AppendRecord`] that can be used to
/// send command messages.
///
/// Such a record is signalled by a sole header with empty name. The header
/// value represents the operation and record body acts as the payload.
#[derive(Debug, Clone)]
pub struct CommandRecord {
    /// Command kind.
    pub command: Command,
    /// Timestamp for the record.
    pub timestamp: Option<u64>,
}

impl CommandRecord {
    const FENCE: &[u8] = b"fence";
    const TRIM: &[u8] = b"trim";

    /// Create a new fence command record.
    pub fn fence(fencing_token: FencingToken) -> Self {
        Self {
            command: Command::Fence { fencing_token },
            timestamp: None,
        }
    }

    /// Create a new trim command record.
    pub fn trim(seq_num: impl Into<u64>) -> Self {
        Self {
            command: Command::Trim {
                seq_num: seq_num.into(),
            },
            timestamp: None,
        }
    }

    /// Overwrite timestamp.
    pub fn with_timestamp(self, timestamp: u64) -> Self {
        Self {
            timestamp: Some(timestamp),
            ..self
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppendRecord {
    timestamp: Option<u64>,
    headers: Vec<Header>,
    body: Bytes,
    #[cfg(test)]
    max_bytes: u64,
}

metered_impl!(AppendRecord);

impl AppendRecord {
    const MAX_BYTES: u64 = MIB_BYTES;

    fn validated(self) -> Result<Self, ConvertError> {
        #[cfg(test)]
        let max_bytes = self.max_bytes;
        #[cfg(not(test))]
        let max_bytes = Self::MAX_BYTES;

        if self.metered_bytes() > max_bytes {
            Err("AppendRecord should have metered size less than 1 MiB".into())
        } else {
            Ok(self)
        }
    }

    /// Try creating a new append record with body.
    pub fn new(body: impl Into<Bytes>) -> Result<Self, ConvertError> {
        Self {
            timestamp: None,
            headers: Vec::new(),
            body: body.into(),
            #[cfg(test)]
            max_bytes: Self::MAX_BYTES,
        }
        .validated()
    }

    #[cfg(test)]
    pub(crate) fn with_max_bytes(
        max_bytes: u64,
        body: impl Into<Bytes>,
    ) -> Result<Self, ConvertError> {
        Self {
            timestamp: None,
            headers: Vec::new(),
            body: body.into(),
            max_bytes,
        }
        .validated()
    }

    /// Overwrite headers.
    pub fn with_headers(self, headers: impl Into<Vec<Header>>) -> Result<Self, ConvertError> {
        Self {
            headers: headers.into(),
            ..self
        }
        .validated()
    }

    /// Overwrite timestamp.
    pub fn with_timestamp(self, timestamp: u64) -> Self {
        Self {
            timestamp: Some(timestamp),
            ..self
        }
    }

    /// Body of the record.
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// Headers of the record.
    pub fn headers(&self) -> &[Header] {
        &self.headers
    }

    /// Timestamp for the record.
    pub fn timestamp(&self) -> Option<u64> {
        self.timestamp
    }

    /// Consume the record and return parts.
    pub fn into_parts(self) -> AppendRecordParts {
        AppendRecordParts {
            timestamp: self.timestamp,
            headers: self.headers,
            body: self.body,
        }
    }

    /// Try creating the record from parts.
    pub fn try_from_parts(parts: AppendRecordParts) -> Result<Self, ConvertError> {
        let record = Self::new(parts.body)?.with_headers(parts.headers)?;
        if let Some(timestamp) = parts.timestamp {
            Ok(record.with_timestamp(timestamp))
        } else {
            Ok(record)
        }
    }
}

impl From<AppendRecord> for api::AppendRecord {
    fn from(value: AppendRecord) -> Self {
        Self {
            timestamp: value.timestamp,
            headers: value.headers.into_iter().map(Into::into).collect(),
            body: value.body,
        }
    }
}

impl From<CommandRecord> for AppendRecord {
    fn from(value: CommandRecord) -> Self {
        let (header_value, body) = match value.command {
            Command::Fence { fencing_token } => (
                CommandRecord::FENCE,
                Bytes::copy_from_slice(fencing_token.as_bytes()),
            ),
            Command::Trim { seq_num } => (
                CommandRecord::TRIM,
                Bytes::copy_from_slice(&seq_num.to_be_bytes()),
            ),
        };
        AppendRecordParts {
            timestamp: value.timestamp,
            headers: vec![Header::from_value(header_value)],
            body,
        }
        .try_into()
        .expect("command record is a valid append record")
    }
}

#[sync_docs(AppendRecordParts = "AppendRecord")]
#[derive(Debug, Clone)]
pub struct AppendRecordParts {
    pub timestamp: Option<u64>,
    pub headers: Vec<Header>,
    pub body: Bytes,
}

impl From<AppendRecord> for AppendRecordParts {
    fn from(value: AppendRecord) -> Self {
        value.into_parts()
    }
}

impl TryFrom<AppendRecordParts> for AppendRecord {
    type Error = ConvertError;

    fn try_from(value: AppendRecordParts) -> Result<Self, Self::Error> {
        Self::try_from_parts(value)
    }
}

/// A collection of append records that can be sent together in a batch.
#[derive(Debug, Clone)]
pub struct AppendRecordBatch {
    records: Vec<AppendRecord>,
    metered_bytes: u64,
    max_capacity: usize,
    #[cfg(test)]
    max_bytes: u64,
}

impl PartialEq for AppendRecordBatch {
    fn eq(&self, other: &Self) -> bool {
        if self.records.eq(&other.records) {
            assert_eq!(self.metered_bytes, other.metered_bytes);
            true
        } else {
            false
        }
    }
}

impl Eq for AppendRecordBatch {}

impl Default for AppendRecordBatch {
    fn default() -> Self {
        Self::new()
    }
}

impl AppendRecordBatch {
    /// Maximum number of records that a batch can hold.
    ///
    /// A record batch cannot be created with a bigger capacity.
    pub const MAX_CAPACITY: usize = 1000;

    /// Maximum metered bytes of the batch.
    pub const MAX_BYTES: u64 = MIB_BYTES;

    /// Create an empty record batch.
    pub fn new() -> Self {
        Self::with_max_capacity(Self::MAX_CAPACITY)
    }

    /// Create an empty record batch with custom max capacity.
    ///
    /// The capacity should not be more than [`Self::MAX_CAPACITY`].
    pub fn with_max_capacity(max_capacity: usize) -> Self {
        assert!(
            max_capacity > 0 && max_capacity <= Self::MAX_CAPACITY,
            "Batch capacity must be between 1 and 1000"
        );

        Self {
            records: Vec::with_capacity(max_capacity),
            metered_bytes: 0,
            max_capacity,
            #[cfg(test)]
            max_bytes: Self::MAX_BYTES,
        }
    }

    #[cfg(test)]
    pub(crate) fn with_max_capacity_and_bytes(max_capacity: usize, max_bytes: u64) -> Self {
        #[cfg(test)]
        assert!(
            max_bytes > 0 || max_bytes <= Self::MAX_BYTES,
            "Batch size must be between 1 byte and 1 MiB"
        );

        Self {
            max_bytes,
            ..Self::with_max_capacity(max_capacity)
        }
    }

    /// Try creating a record batch from an iterator.
    ///
    /// If all the items of the iterator cannot be drained into the batch, the
    /// error returned contains a batch containing all records it could fit
    /// along-with the left over items from the iterator.
    pub fn try_from_iter<R, T>(iter: T) -> Result<Self, (Self, Vec<AppendRecord>)>
    where
        R: Into<AppendRecord>,
        T: IntoIterator<Item = R>,
    {
        let mut records = Self::new();
        let mut pending = Vec::new();

        let mut iter = iter.into_iter();

        for record in iter.by_ref() {
            if let Err(record) = records.push(record) {
                pending.push(record);
                break;
            }
        }

        if pending.is_empty() {
            Ok(records)
        } else {
            pending.extend(iter.map(Into::into));
            Err((records, pending))
        }
    }

    /// Returns true if the batch contains no records.
    pub fn is_empty(&self) -> bool {
        if self.records.is_empty() {
            assert_eq!(self.metered_bytes, 0);
            true
        } else {
            false
        }
    }

    /// Returns the number of records contained in the batch.
    pub fn len(&self) -> usize {
        self.records.len()
    }

    #[cfg(test)]
    fn max_bytes(&self) -> u64 {
        self.max_bytes
    }

    #[cfg(not(test))]
    fn max_bytes(&self) -> u64 {
        Self::MAX_BYTES
    }

    /// Returns true if the batch cannot fit any more records.
    pub fn is_full(&self) -> bool {
        self.records.len() >= self.max_capacity || self.metered_bytes >= self.max_bytes()
    }

    /// Try to append a new record into the batch.
    pub fn push(&mut self, record: impl Into<AppendRecord>) -> Result<(), AppendRecord> {
        assert!(self.records.len() <= self.max_capacity);
        assert!(self.metered_bytes <= self.max_bytes());

        let record = record.into();
        let record_size = record.metered_bytes();
        if self.records.len() >= self.max_capacity
            || self.metered_bytes + record_size > self.max_bytes()
        {
            Err(record)
        } else {
            self.records.push(record);
            self.metered_bytes += record_size;
            Ok(())
        }
    }
}

impl MeteredBytes for AppendRecordBatch {
    fn metered_bytes(&self) -> u64 {
        self.metered_bytes
    }
}

impl IntoIterator for AppendRecordBatch {
    type Item = AppendRecord;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.records.into_iter()
    }
}

impl<'a> IntoIterator for &'a AppendRecordBatch {
    type Item = &'a AppendRecord;
    type IntoIter = std::slice::Iter<'a, AppendRecord>;

    fn into_iter(self) -> Self::IntoIter {
        self.records.iter()
    }
}

impl AsRef<[AppendRecord]> for AppendRecordBatch {
    fn as_ref(&self) -> &[AppendRecord] {
        &self.records
    }
}

#[sync_docs]
#[derive(Debug, Default, Clone)]
pub struct AppendInput {
    pub records: AppendRecordBatch,
    pub match_seq_num: Option<u64>,
    pub fencing_token: Option<FencingToken>,
}

impl MeteredBytes for AppendInput {
    fn metered_bytes(&self) -> u64 {
        self.records.metered_bytes()
    }
}

impl AppendInput {
    /// Create a new append input from record batch.
    pub fn new(records: impl Into<AppendRecordBatch>) -> Self {
        Self {
            records: records.into(),
            match_seq_num: None,
            fencing_token: None,
        }
    }

    /// Overwrite match sequence number.
    pub fn with_match_seq_num(self, match_seq_num: impl Into<u64>) -> Self {
        Self {
            match_seq_num: Some(match_seq_num.into()),
            ..self
        }
    }

    /// Overwrite fencing token.
    pub fn with_fencing_token(self, fencing_token: FencingToken) -> Self {
        Self {
            fencing_token: Some(fencing_token),
            ..self
        }
    }

    pub(crate) fn into_api_type(self, stream: impl Into<String>) -> api::AppendInput {
        let Self {
            records,
            match_seq_num,
            fencing_token,
        } = self;

        api::AppendInput {
            stream: stream.into(),
            records: records.into_iter().map(Into::into).collect(),
            match_seq_num,
            fencing_token: fencing_token.map(|f| f.0),
        }
    }
}

/// Acknowledgment to an append request.
#[derive(Debug, Clone)]
pub struct AppendAck {
    /// Sequence number and timestamp of the first record that was appended.
    pub start: StreamPosition,
    /// Sequence number of the last record that was appended + 1,
    /// and timestamp of the last record that was appended.
    /// The difference between `end.seq_num` and `start.seq_num`
    /// will be the number of records appended.
    pub end: StreamPosition,
    /// Sequence number that will be assigned to the next record on the stream,
    /// and timestamp of the last record on the stream.
    /// This can be greater than the `end` position in case of concurrent appends.
    pub tail: StreamPosition,
}

impl From<api::AppendOutput> for AppendAck {
    fn from(value: api::AppendOutput) -> Self {
        let api::AppendOutput {
            start_seq_num,
            start_timestamp,
            end_seq_num,
            end_timestamp,
            next_seq_num,
            last_timestamp,
        } = value;
        let start = StreamPosition {
            seq_num: start_seq_num,
            timestamp: start_timestamp,
        };
        let end = StreamPosition {
            seq_num: end_seq_num,
            timestamp: end_timestamp,
        };
        let tail = StreamPosition {
            seq_num: next_seq_num,
            timestamp: last_timestamp,
        };
        Self { start, end, tail }
    }
}

impl TryFrom<api::AppendResponse> for AppendAck {
    type Error = ConvertError;
    fn try_from(value: api::AppendResponse) -> Result<Self, Self::Error> {
        let api::AppendResponse { output } = value;
        let output = output.ok_or("missing append output")?;
        Ok(output.into())
    }
}

impl TryFrom<api::AppendSessionResponse> for AppendAck {
    type Error = ConvertError;
    fn try_from(value: api::AppendSessionResponse) -> Result<Self, Self::Error> {
        let api::AppendSessionResponse { output } = value;
        let output = output.ok_or("missing append output")?;
        Ok(output.into())
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ReadLimit {
    pub count: Option<u64>,
    pub bytes: Option<u64>,
}

impl ReadLimit {
    /// Create a new read limit.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite count limit.
    pub fn with_count(self, count: u64) -> Self {
        Self {
            count: Some(count),
            ..self
        }
    }

    /// Overwrite bytes limit.
    pub fn with_bytes(self, bytes: u64) -> Self {
        Self {
            bytes: Some(bytes),
            ..self
        }
    }
}

/// Starting point for read requests.
#[derive(Debug, Clone)]
pub enum ReadStart {
    /// Sequence number.
    SeqNum(u64),
    /// Timestamp.
    Timestamp(u64),
    /// Number of records before the tail, i.e. the next sequence number.
    TailOffset(u64),
}

impl Default for ReadStart {
    fn default() -> Self {
        Self::SeqNum(0)
    }
}

impl From<ReadStart> for api::read_request::Start {
    fn from(start: ReadStart) -> Self {
        match start {
            ReadStart::SeqNum(seq_num) => api::read_request::Start::SeqNum(seq_num),
            ReadStart::Timestamp(timestamp) => api::read_request::Start::Timestamp(timestamp),
            ReadStart::TailOffset(offset) => api::read_request::Start::TailOffset(offset),
        }
    }
}

impl From<ReadStart> for api::read_session_request::Start {
    fn from(start: ReadStart) -> Self {
        match start {
            ReadStart::SeqNum(seq_num) => api::read_session_request::Start::SeqNum(seq_num),
            ReadStart::Timestamp(timestamp) => {
                api::read_session_request::Start::Timestamp(timestamp)
            }
            ReadStart::TailOffset(offset) => api::read_session_request::Start::TailOffset(offset),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ReadRequest {
    pub start: ReadStart,
    pub limit: ReadLimit,
    pub until: Option<RangeTo<u64>>,
    pub clamp: bool,
}

impl ReadRequest {
    /// Create a new request with the specified starting point.
    pub fn new(start: ReadStart) -> Self {
        Self {
            start,
            ..Default::default()
        }
    }

    /// Overwrite limit.
    pub fn with_limit(self, limit: ReadLimit) -> Self {
        Self { limit, ..self }
    }

    /// Provide an `until` timestamp.
    pub fn with_until(self, until: RangeTo<u64>) -> Self {
        Self {
            until: Some(until),
            ..self
        }
    }

    /// Clamp the start position at the tail position.
    pub fn with_clamp(self, clamp: bool) -> Self {
        Self { clamp, ..self }
    }
}

impl ReadRequest {
    pub(crate) fn try_into_api_type(
        self,
        stream: impl Into<String>,
    ) -> Result<api::ReadRequest, ConvertError> {
        let Self {
            start,
            limit,
            until,
            clamp,
        } = self;

        let limit = if limit.count > Some(1000) {
            Err("read limit: count must not exceed 1000 for unary request")
        } else if limit.bytes > Some(MIB_BYTES) {
            Err("read limit: bytes must not exceed 1MiB for unary request")
        } else {
            Ok(api::ReadLimit {
                count: limit.count,
                bytes: limit.bytes,
            })
        }?;

        Ok(api::ReadRequest {
            stream: stream.into(),
            start: Some(start.into()),
            limit: Some(limit),
            until: until.map(|range| range.end),
            clamp,
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct SequencedRecord {
    pub seq_num: u64,
    pub timestamp: u64,
    pub headers: Vec<Header>,
    pub body: Bytes,
}

metered_impl!(SequencedRecord);

impl From<api::SequencedRecord> for SequencedRecord {
    fn from(value: api::SequencedRecord) -> Self {
        let api::SequencedRecord {
            seq_num,
            timestamp,
            headers,
            body,
        } = value;
        Self {
            seq_num,
            timestamp,
            headers: headers.into_iter().map(Into::into).collect(),
            body,
        }
    }
}

impl SequencedRecord {
    /// Try representing the sequenced record as a command record.
    pub fn as_command_record(&self) -> Option<CommandRecord> {
        if self.headers.len() != 1 {
            return None;
        }

        let header = self.headers.first().expect("pre-validated length");

        if !header.name.is_empty() {
            return None;
        }

        match header.value.as_ref() {
            CommandRecord::FENCE => {
                let fencing_token = std::str::from_utf8(&self.body).ok()?.parse().ok()?;
                Some(CommandRecord {
                    command: Command::Fence { fencing_token },
                    timestamp: Some(self.timestamp),
                })
            }
            CommandRecord::TRIM => {
                let body: &[u8] = &self.body;
                let seq_num = u64::from_be_bytes(body.try_into().ok()?);
                Some(CommandRecord {
                    command: Command::Trim { seq_num },
                    timestamp: Some(self.timestamp),
                })
            }
            _ => None,
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct SequencedRecordBatch {
    pub records: Vec<SequencedRecord>,
}

impl MeteredBytes for SequencedRecordBatch {
    fn metered_bytes(&self) -> u64 {
        self.records.metered_bytes()
    }
}

impl From<api::SequencedRecordBatch> for SequencedRecordBatch {
    fn from(value: api::SequencedRecordBatch) -> Self {
        let api::SequencedRecordBatch { records } = value;
        Self {
            records: records.into_iter().map(Into::into).collect(),
        }
    }
}

#[sync_docs(ReadOutput = "Output")]
#[derive(Debug, Clone)]
pub enum ReadOutput {
    Batch(SequencedRecordBatch),
    NextSeqNum(u64),
}

impl From<api::read_output::Output> for ReadOutput {
    fn from(value: api::read_output::Output) -> Self {
        match value {
            api::read_output::Output::Batch(batch) => Self::Batch(batch.into()),
            api::read_output::Output::NextSeqNum(next_seq_num) => Self::NextSeqNum(next_seq_num),
        }
    }
}

impl TryFrom<api::ReadOutput> for ReadOutput {
    type Error = ConvertError;
    fn try_from(value: api::ReadOutput) -> Result<Self, Self::Error> {
        let api::ReadOutput { output } = value;
        let output = output.ok_or("missing read output")?;
        Ok(output.into())
    }
}

impl TryFrom<api::ReadResponse> for ReadOutput {
    type Error = ConvertError;
    fn try_from(value: api::ReadResponse) -> Result<Self, Self::Error> {
        let api::ReadResponse { output } = value;
        let output = output.ok_or("missing output in read response")?;
        output.try_into()
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ReadSessionRequest {
    pub start: ReadStart,
    pub limit: ReadLimit,
    pub until: Option<RangeTo<u64>>,
    pub clamp: bool,
}

impl ReadSessionRequest {
    /// Create a new request with the specified starting point.
    pub fn new(start: ReadStart) -> Self {
        Self {
            start,
            ..Default::default()
        }
    }

    /// Overwrite limit.
    pub fn with_limit(self, limit: ReadLimit) -> Self {
        Self { limit, ..self }
    }

    /// Provide an `until` timestamp.
    pub fn with_until(self, until: RangeTo<u64>) -> Self {
        Self {
            until: Some(until),
            ..self
        }
    }

    /// Clamp the start position at the tail position.
    pub fn with_clamp(self, clamp: bool) -> Self {
        Self { clamp, ..self }
    }

    pub(crate) fn into_api_type(self, stream: impl Into<String>) -> api::ReadSessionRequest {
        let Self {
            start,
            limit,
            until,
            clamp,
        } = self;
        api::ReadSessionRequest {
            stream: stream.into(),
            start: Some(start.into()),
            limit: Some(api::ReadLimit {
                count: limit.count,
                bytes: limit.bytes,
            }),
            heartbeats: false,
            until: until.map(|range| range.end),
            clamp,
        }
    }
}

impl TryFrom<api::ReadSessionResponse> for ReadOutput {
    type Error = ConvertError;
    fn try_from(value: api::ReadSessionResponse) -> Result<Self, Self::Error> {
        let api::ReadSessionResponse { output } = value;
        let output = output.ok_or("missing output in read session response")?;
        output.try_into()
    }
}

/// Name of a basin.
///
/// Must be between 8 and 48 characters in length. Must comprise lowercase
/// letters, numbers, and hyphens. Cannot begin or end with a hyphen.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BasinName(String);

impl Deref for BasinName {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl TryFrom<String> for BasinName {
    type Error = ConvertError;

    fn try_from(name: String) -> Result<Self, Self::Error> {
        if name.len() < 8 || name.len() > 48 {
            return Err("Basin name must be between 8 and 48 characters in length".into());
        }

        static BASIN_NAME_REGEX: OnceLock<Regex> = OnceLock::new();
        let regex = BASIN_NAME_REGEX.get_or_init(|| {
            Regex::new(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
                .expect("Failed to compile basin name regex")
        });

        if !regex.is_match(&name) {
            return Err(
                "Basin name must comprise lowercase letters, numbers, and hyphens. \
                It cannot begin or end with a hyphen."
                    .into(),
            );
        }

        Ok(Self(name))
    }
}

impl FromStr for BasinName {
    type Err = ConvertError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.to_string().try_into()
    }
}

impl std::fmt::Display for BasinName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<BasinName> for String {
    fn from(value: BasinName) -> Self {
        value.0
    }
}

/// Access token ID.
/// Must be between 1 and 96 characters.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AccessTokenId(String);

impl Deref for AccessTokenId {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl TryFrom<String> for AccessTokenId {
    type Error = ConvertError;

    fn try_from(name: String) -> Result<Self, Self::Error> {
        if name.is_empty() {
            return Err("Access token ID must not be empty".into());
        }

        if name.len() > 96 {
            return Err("Access token ID must not exceed 96 characters".into());
        }

        Ok(Self(name))
    }
}

impl From<AccessTokenId> for String {
    fn from(value: AccessTokenId) -> Self {
        value.0
    }
}

impl FromStr for AccessTokenId {
    type Err = ConvertError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.to_string().try_into()
    }
}

impl std::fmt::Display for AccessTokenId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<AccessTokenInfo> for api::IssueAccessTokenRequest {
    fn from(value: AccessTokenInfo) -> Self {
        Self {
            info: Some(value.into()),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct AccessTokenInfo {
    pub id: AccessTokenId,
    pub expires_at: Option<u32>,
    pub auto_prefix_streams: bool,
    pub scope: Option<AccessTokenScope>,
}

impl AccessTokenInfo {
    /// Create a new access token info.
    pub fn new(id: AccessTokenId) -> Self {
        Self {
            id,
            expires_at: None,
            auto_prefix_streams: false,
            scope: None,
        }
    }

    /// Overwrite expiration time.
    pub fn with_expires_at(self, expires_at: u32) -> Self {
        Self {
            expires_at: Some(expires_at),
            ..self
        }
    }

    /// Overwrite auto prefix streams.
    pub fn with_auto_prefix_streams(self, auto_prefix_streams: bool) -> Self {
        Self {
            auto_prefix_streams,
            ..self
        }
    }

    /// Overwrite scope.
    pub fn with_scope(self, scope: AccessTokenScope) -> Self {
        Self {
            scope: Some(scope),
            ..self
        }
    }
}

impl From<AccessTokenInfo> for api::AccessTokenInfo {
    fn from(value: AccessTokenInfo) -> Self {
        let AccessTokenInfo {
            id,
            expires_at,
            auto_prefix_streams,
            scope,
        } = value;
        Self {
            id: id.into(),
            expires_at,
            auto_prefix_streams,
            scope: scope.map(Into::into),
        }
    }
}

impl TryFrom<api::AccessTokenInfo> for AccessTokenInfo {
    type Error = ConvertError;

    fn try_from(value: api::AccessTokenInfo) -> Result<Self, Self::Error> {
        let api::AccessTokenInfo {
            id,
            expires_at,
            auto_prefix_streams,
            scope,
        } = value;
        Ok(Self {
            id: id.try_into()?,
            expires_at,
            auto_prefix_streams,
            scope: scope.map(Into::into),
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Operation {
    ListBasins,
    CreateBasin,
    DeleteBasin,
    ReconfigureBasin,
    GetBasinConfig,
    IssueAccessToken,
    RevokeAccessToken,
    ListAccessTokens,
    ListStreams,
    CreateStream,
    DeleteStream,
    GetStreamConfig,
    ReconfigureStream,
    CheckTail,
    Append,
    Read,
    Trim,
    Fence,
    AccountMetrics,
    BasinMetrics,
    StreamMetrics,
}

impl FromStr for Operation {
    type Err = ConvertError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "list-basins" => Ok(Self::ListBasins),
            "create-basin" => Ok(Self::CreateBasin),
            "delete-basin" => Ok(Self::DeleteBasin),
            "reconfigure-basin" => Ok(Self::ReconfigureBasin),
            "get-basin-config" => Ok(Self::GetBasinConfig),
            "issue-access-token" => Ok(Self::IssueAccessToken),
            "revoke-access-token" => Ok(Self::RevokeAccessToken),
            "list-access-tokens" => Ok(Self::ListAccessTokens),
            "list-streams" => Ok(Self::ListStreams),
            "create-stream" => Ok(Self::CreateStream),
            "delete-stream" => Ok(Self::DeleteStream),
            "get-stream-config" => Ok(Self::GetStreamConfig),
            "reconfigure-stream" => Ok(Self::ReconfigureStream),
            "check-tail" => Ok(Self::CheckTail),
            "append" => Ok(Self::Append),
            "read" => Ok(Self::Read),
            "trim" => Ok(Self::Trim),
            "fence" => Ok(Self::Fence),
            "account-metrics" => Ok(Self::AccountMetrics),
            "basin-metrics" => Ok(Self::BasinMetrics),
            "stream-metrics" => Ok(Self::StreamMetrics),
            _ => Err("invalid operation".into()),
        }
    }
}

impl From<Operation> for api::Operation {
    fn from(value: Operation) -> Self {
        match value {
            Operation::ListBasins => Self::ListBasins,
            Operation::CreateBasin => Self::CreateBasin,
            Operation::DeleteBasin => Self::DeleteBasin,
            Operation::ReconfigureBasin => Self::ReconfigureBasin,
            Operation::GetBasinConfig => Self::GetBasinConfig,
            Operation::IssueAccessToken => Self::IssueAccessToken,
            Operation::RevokeAccessToken => Self::RevokeAccessToken,
            Operation::ListAccessTokens => Self::ListAccessTokens,
            Operation::ListStreams => Self::ListStreams,
            Operation::CreateStream => Self::CreateStream,
            Operation::DeleteStream => Self::DeleteStream,
            Operation::GetStreamConfig => Self::GetStreamConfig,
            Operation::ReconfigureStream => Self::ReconfigureStream,
            Operation::CheckTail => Self::CheckTail,
            Operation::Append => Self::Append,
            Operation::Read => Self::Read,
            Operation::Trim => Self::Trim,
            Operation::Fence => Self::Fence,
            Operation::AccountMetrics => Self::AccountMetrics,
            Operation::BasinMetrics => Self::BasinMetrics,
            Operation::StreamMetrics => Self::StreamMetrics,
        }
    }
}

impl From<api::Operation> for Option<Operation> {
    fn from(value: api::Operation) -> Self {
        match value {
            api::Operation::Unspecified => None,
            api::Operation::ListBasins => Some(Operation::ListBasins),
            api::Operation::CreateBasin => Some(Operation::CreateBasin),
            api::Operation::DeleteBasin => Some(Operation::DeleteBasin),
            api::Operation::ReconfigureBasin => Some(Operation::ReconfigureBasin),
            api::Operation::GetBasinConfig => Some(Operation::GetBasinConfig),
            api::Operation::IssueAccessToken => Some(Operation::IssueAccessToken),
            api::Operation::RevokeAccessToken => Some(Operation::RevokeAccessToken),
            api::Operation::ListAccessTokens => Some(Operation::ListAccessTokens),
            api::Operation::ListStreams => Some(Operation::ListStreams),
            api::Operation::CreateStream => Some(Operation::CreateStream),
            api::Operation::DeleteStream => Some(Operation::DeleteStream),
            api::Operation::GetStreamConfig => Some(Operation::GetStreamConfig),
            api::Operation::ReconfigureStream => Some(Operation::ReconfigureStream),
            api::Operation::CheckTail => Some(Operation::CheckTail),
            api::Operation::Append => Some(Operation::Append),
            api::Operation::Read => Some(Operation::Read),
            api::Operation::Trim => Some(Operation::Trim),
            api::Operation::Fence => Some(Operation::Fence),
            api::Operation::AccountMetrics => Some(Operation::AccountMetrics),
            api::Operation::BasinMetrics => Some(Operation::BasinMetrics),
            api::Operation::StreamMetrics => Some(Operation::StreamMetrics),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct AccessTokenScope {
    pub basins: Option<ResourceSet>,
    pub streams: Option<ResourceSet>,
    pub access_tokens: Option<ResourceSet>,
    pub op_groups: Option<PermittedOperationGroups>,
    pub ops: HashSet<Operation>,
}

impl AccessTokenScope {
    /// Create a new access token scope.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite resource set for access tokens.
    pub fn with_basins(self, basins: ResourceSet) -> Self {
        Self {
            basins: Some(basins),
            ..self
        }
    }

    /// Overwrite resource set for streams.
    pub fn with_streams(self, streams: ResourceSet) -> Self {
        Self {
            streams: Some(streams),
            ..self
        }
    }

    /// Overwrite resource set for access tokens.
    pub fn with_tokens(self, access_tokens: ResourceSet) -> Self {
        Self {
            access_tokens: Some(access_tokens),
            ..self
        }
    }

    /// Overwrite operation groups.
    pub fn with_op_groups(self, op_groups: PermittedOperationGroups) -> Self {
        Self {
            op_groups: Some(op_groups),
            ..self
        }
    }

    /// Overwrite operations.
    pub fn with_ops(self, ops: impl IntoIterator<Item = Operation>) -> Self {
        Self {
            ops: ops.into_iter().collect(),
            ..self
        }
    }

    /// Add an operation to operations.
    pub fn with_op(self, op: Operation) -> Self {
        let mut ops = self.ops;
        ops.insert(op);
        Self { ops, ..self }
    }
}

impl From<AccessTokenScope> for api::AccessTokenScope {
    fn from(value: AccessTokenScope) -> Self {
        let AccessTokenScope {
            basins,
            streams,
            access_tokens,
            op_groups,
            ops,
        } = value;
        Self {
            basins: basins.map(Into::into),
            streams: streams.map(Into::into),
            access_tokens: access_tokens.map(Into::into),
            op_groups: op_groups.map(Into::into),
            ops: ops
                .into_iter()
                .map(api::Operation::from)
                .map(Into::into)
                .collect(),
        }
    }
}

impl From<api::AccessTokenScope> for AccessTokenScope {
    fn from(value: api::AccessTokenScope) -> Self {
        let api::AccessTokenScope {
            basins,
            streams,
            access_tokens,
            op_groups,
            ops,
        } = value;
        Self {
            basins: basins.and_then(|set| set.matching.map(Into::into)),
            streams: streams.and_then(|set| set.matching.map(Into::into)),
            access_tokens: access_tokens.and_then(|set| set.matching.map(Into::into)),
            op_groups: op_groups.map(Into::into),
            ops: ops
                .into_iter()
                .map(api::Operation::try_from)
                .flat_map(Result::ok)
                .flat_map(<Option<Operation>>::from)
                .collect(),
        }
    }
}

impl From<ResourceSet> for api::ResourceSet {
    fn from(value: ResourceSet) -> Self {
        Self {
            matching: Some(value.into()),
        }
    }
}

#[sync_docs(ResourceSet = "Matching")]
#[derive(Debug, Clone)]
pub enum ResourceSet {
    Exact(String),
    Prefix(String),
}

impl From<ResourceSet> for api::resource_set::Matching {
    fn from(value: ResourceSet) -> Self {
        match value {
            ResourceSet::Exact(name) => api::resource_set::Matching::Exact(name),
            ResourceSet::Prefix(name) => api::resource_set::Matching::Prefix(name),
        }
    }
}

impl From<api::resource_set::Matching> for ResourceSet {
    fn from(value: api::resource_set::Matching) -> Self {
        match value {
            api::resource_set::Matching::Exact(name) => ResourceSet::Exact(name),
            api::resource_set::Matching::Prefix(name) => ResourceSet::Prefix(name),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct PermittedOperationGroups {
    pub account: Option<ReadWritePermissions>,
    pub basin: Option<ReadWritePermissions>,
    pub stream: Option<ReadWritePermissions>,
}

impl PermittedOperationGroups {
    /// Create a new permitted operation groups.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite account read-write permissions.
    pub fn with_account(self, account: ReadWritePermissions) -> Self {
        Self {
            account: Some(account),
            ..self
        }
    }

    /// Overwrite basin read-write permissions.
    pub fn with_basin(self, basin: ReadWritePermissions) -> Self {
        Self {
            basin: Some(basin),
            ..self
        }
    }

    /// Overwrite stream read-write permissions.
    pub fn with_stream(self, stream: ReadWritePermissions) -> Self {
        Self {
            stream: Some(stream),
            ..self
        }
    }
}

impl From<PermittedOperationGroups> for api::PermittedOperationGroups {
    fn from(value: PermittedOperationGroups) -> Self {
        let PermittedOperationGroups {
            account,
            basin,
            stream,
        } = value;
        Self {
            account: account.map(Into::into),
            basin: basin.map(Into::into),
            stream: stream.map(Into::into),
        }
    }
}

impl From<api::PermittedOperationGroups> for PermittedOperationGroups {
    fn from(value: api::PermittedOperationGroups) -> Self {
        let api::PermittedOperationGroups {
            account,
            basin,
            stream,
        } = value;
        Self {
            account: account.map(Into::into),
            basin: basin.map(Into::into),
            stream: stream.map(Into::into),
        }
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ReadWritePermissions {
    pub read: bool,
    pub write: bool,
}

impl ReadWritePermissions {
    /// Create a new read-write permission.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite read permission.
    pub fn with_read(self, read: bool) -> Self {
        Self { read, ..self }
    }

    /// Overwrite write permission.
    pub fn with_write(self, write: bool) -> Self {
        Self { write, ..self }
    }
}

impl From<ReadWritePermissions> for api::ReadWritePermissions {
    fn from(value: ReadWritePermissions) -> Self {
        let ReadWritePermissions { read, write } = value;
        Self { read, write }
    }
}

impl From<api::ReadWritePermissions> for ReadWritePermissions {
    fn from(value: api::ReadWritePermissions) -> Self {
        let api::ReadWritePermissions { read, write } = value;
        Self { read, write }
    }
}

impl From<api::IssueAccessTokenResponse> for String {
    fn from(value: api::IssueAccessTokenResponse) -> Self {
        value.access_token
    }
}

impl From<AccessTokenId> for api::RevokeAccessTokenRequest {
    fn from(value: AccessTokenId) -> Self {
        Self { id: value.into() }
    }
}

impl TryFrom<api::RevokeAccessTokenResponse> for AccessTokenInfo {
    type Error = ConvertError;
    fn try_from(value: api::RevokeAccessTokenResponse) -> Result<Self, Self::Error> {
        let token_info = value.info.ok_or("access token info is missing")?;
        token_info.try_into()
    }
}

#[sync_docs]
#[derive(Debug, Clone, Default)]
pub struct ListAccessTokensRequest {
    pub prefix: String,
    pub start_after: String,
    pub limit: Option<usize>,
}

impl ListAccessTokensRequest {
    /// Create a new request with prefix.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overwrite prefix.
    pub fn with_prefix(self, prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            ..self
        }
    }

    /// Overwrite start after.
    pub fn with_start_after(self, start_after: impl Into<String>) -> Self {
        Self {
            start_after: start_after.into(),
            ..self
        }
    }

    /// Overwrite limit.
    pub fn with_limit(self, limit: impl Into<Option<usize>>) -> Self {
        Self {
            limit: limit.into(),
            ..self
        }
    }
}

impl TryFrom<ListAccessTokensRequest> for api::ListAccessTokensRequest {
    type Error = ConvertError;
    fn try_from(value: ListAccessTokensRequest) -> Result<Self, Self::Error> {
        let ListAccessTokensRequest {
            prefix,
            start_after,
            limit,
        } = value;
        Ok(Self {
            prefix,
            start_after,
            limit: limit
                .map(TryInto::try_into)
                .transpose()
                .map_err(|_| "request limit does not fit into u64 bounds")?,
        })
    }
}

#[sync_docs]
#[derive(Debug, Clone)]
pub struct ListAccessTokensResponse {
    pub access_tokens: Vec<AccessTokenInfo>,
    pub has_more: bool,
}

impl TryFrom<api::ListAccessTokensResponse> for ListAccessTokensResponse {
    type Error = ConvertError;
    fn try_from(value: api::ListAccessTokensResponse) -> Result<Self, Self::Error> {
        let api::ListAccessTokensResponse {
            access_tokens,
            has_more,
        } = value;
        let access_tokens = access_tokens
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self {
            access_tokens,
            has_more,
        })
    }
}