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
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
use std::env;
use std::sync::Arc;
use std::time::Duration as StdDuration;
use async_trait::async_trait;
use chrono::{Duration, Utc};
use reqwest::header::AUTHORIZATION;
use reqwest::{Client, Method, Url};
use serde::de::DeserializeOwned;
use thiserror::Error;
use tokio::sync::{Mutex, OnceCell, Semaphore};
use tokio::time::sleep;
use secrecy::ExposeSecret;
use secrecy::Secret;
use crate::model::{
Activity, Asset, AssetActivityParams, AssetSummary, Assignment, Balance, BroadcastResponse,
CategoriesRequest, CategoryAdd, CategoryEdit, CategoryResponse, ChangePasswordRequest,
ChangePasswordResponse, CreateAssetAssignmentRequest, EditAssetRequest, GaidBalanceEntry,
GaidRequest, IssuanceRequest, IssuanceResponse, Outpoint, Ownership, Password, TokenData,
TokenInfo, TokenRequest, TokenResponse, Utxo,
};
/// Environment variables used for token environment detection
#[derive(Debug)]
struct EnvironmentVariables {
username: String,
password: String,
amp_tests: String,
base_url: String,
}
/// Token environment detection for automatic strategy selection
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenEnvironment {
/// Mock environment - use isolated token management without persistence
Mock,
/// Live environment - use full token management with persistence
Live,
/// Auto-detect environment based on credentials and settings
Auto,
}
impl TokenEnvironment {
/// Detects the current token environment based on environment variables and credential patterns
///
/// Detection logic:
/// 1. If `AMP_TESTS=live` is set, returns `Live`
/// 2. If credentials contain "mock" string, returns `Mock`
/// 3. If real credentials are present without live test flag, returns `Live`
/// 4. Fallback to `Mock` for safety
#[must_use]
pub fn detect() -> Self {
let env_vars = Self::read_environment_variables();
Self::log_detection_start(&env_vars);
if Self::is_explicit_live_environment(&env_vars.amp_tests) {
return Self::Live;
}
if Self::has_mock_credentials(&env_vars.username, &env_vars.password, &env_vars.base_url) {
Self::log_detection_result("mock environment via mock credentials");
return Self::Mock;
}
if Self::has_real_credentials(&env_vars.username, &env_vars.password) {
Self::log_detection_result("live environment via real credentials");
return Self::Live;
}
Self::log_detection_result("mock environment via fallback (no credentials)");
Self::Mock
}
/// Reads environment variables needed for token environment detection
fn read_environment_variables() -> EnvironmentVariables {
EnvironmentVariables {
username: env::var("AMP_USERNAME").unwrap_or_default(),
password: env::var("AMP_PASSWORD").unwrap_or_default(),
amp_tests: env::var("AMP_TESTS").unwrap_or_default(),
base_url: env::var("AMP_API_BASE_URL").unwrap_or_default(),
}
}
/// Logs the start of environment detection with current variable values
fn log_detection_start(env_vars: &EnvironmentVariables) {
tracing::debug!(
"Detecting token environment - AMP_TESTS: '{}', username: '{}', base_url: '{}'",
env_vars.amp_tests,
env_vars.username,
env_vars.base_url
);
}
/// Checks if the environment is explicitly set to live testing
fn is_explicit_live_environment(amp_tests: &str) -> bool {
if amp_tests == "live" {
Self::log_detection_result("live environment via AMP_TESTS=live");
true
} else {
false
}
}
/// Checks if real (non-empty) credentials are present
const fn has_real_credentials(username: &str, password: &str) -> bool {
!username.is_empty() && !password.is_empty()
}
/// Logs the final detection result
fn log_detection_result(reason: &str) {
tracing::info!("Detected {}", reason);
}
/// Checks if the provided credentials indicate a mock environment
///
/// Mock credentials are detected by:
/// - Username containing "mock" (case-insensitive)
/// - Password containing "mock" (case-insensitive)
/// - Base URL containing localhost, 127.0.0.1, or "mock"
#[must_use]
pub fn has_mock_credentials(username: &str, password: &str, base_url: &str) -> bool {
let username_lower = username.to_lowercase();
let password_lower = password.to_lowercase();
let base_url_lower = base_url.to_lowercase();
let has_mock_username = username_lower.contains("mock");
let has_mock_password = password_lower.contains("mock");
let has_mock_url = base_url_lower.contains("localhost")
|| base_url_lower.contains("127.0.0.1")
|| base_url_lower.contains("mock");
let is_mock = has_mock_username || has_mock_password || has_mock_url;
tracing::debug!(
"Mock credential check - username: {}, password: {}, url: {}, result: {}",
has_mock_username,
has_mock_password,
has_mock_url,
is_mock
);
is_mock
}
/// Creates a token strategy based on the environment type
///
/// # Arguments
/// * `mock_token` - Optional mock token to use for mock environments
///
/// # Errors
/// Returns an error if strategy creation fails
pub async fn create_strategy(
&self,
mock_token: Option<String>,
) -> Result<Box<dyn TokenStrategy>, Error> {
match self {
Self::Mock => Ok(Self::create_mock_strategy(mock_token)),
Self::Live => Self::create_live_strategy().await,
Self::Auto => Self::create_auto_detected_strategy(mock_token).await,
}
}
/// Creates a mock token strategy with the provided or default token
fn create_mock_strategy(mock_token: Option<String>) -> Box<dyn TokenStrategy> {
let token = mock_token.unwrap_or_else(|| "default_mock_token".to_string());
tracing::debug!("Creating mock token strategy with token");
Box::new(MockTokenStrategy::new(token))
}
/// Creates a live token strategy
async fn create_live_strategy() -> Result<Box<dyn TokenStrategy>, Error> {
tracing::debug!("Creating live token strategy");
let strategy = LiveTokenStrategy::new().await?;
Ok(Box::new(strategy))
}
/// Creates a strategy based on auto-detected environment
async fn create_auto_detected_strategy(
mock_token: Option<String>,
) -> Result<Box<dyn TokenStrategy>, Error> {
tracing::debug!("Auto-detecting environment for strategy creation");
let detected = Self::detect();
match detected {
Self::Mock => Ok(Self::create_auto_detected_mock_strategy(mock_token)),
Self::Live => Self::create_auto_detected_live_strategy().await,
Self::Auto => Self::handle_unexpected_auto_detection(),
}
}
/// Creates a mock strategy for auto-detected mock environment
fn create_auto_detected_mock_strategy(mock_token: Option<String>) -> Box<dyn TokenStrategy> {
let token = mock_token.unwrap_or_else(|| "default_mock_token".to_string());
tracing::debug!("Auto-detected mock environment, creating mock strategy");
Box::new(MockTokenStrategy::new(token))
}
/// Creates a live strategy for auto-detected live environment
async fn create_auto_detected_live_strategy() -> Result<Box<dyn TokenStrategy>, Error> {
tracing::debug!("Auto-detected live environment, creating live strategy");
let strategy = LiveTokenStrategy::new().await?;
Ok(Box::new(strategy))
}
/// Handles the unexpected case where `detect()` returns Auto
fn handle_unexpected_auto_detection() -> Result<Box<dyn TokenStrategy>, Error> {
tracing::error!("Unexpected Auto environment from detect()");
Err(Error::Token(TokenError::validation(
"Environment detection returned Auto, which should not happen".to_string(),
)))
}
/// Creates a token strategy with automatic environment detection
///
/// This is a convenience method that combines environment detection with strategy creation.
///
/// # Arguments
/// * `mock_token` - Optional mock token to use if mock environment is detected
///
/// # Errors
/// Returns an error if strategy creation fails
pub async fn create_auto_strategy(
mock_token: Option<String>,
) -> Result<Box<dyn TokenStrategy>, Error> {
let environment = Self::detect();
environment.create_strategy(mock_token).await
}
/// Determines if token persistence should be enabled for this environment
#[must_use]
pub fn should_persist_tokens(&self) -> bool {
match self {
Self::Mock => false,
Self::Live => true,
Self::Auto => Self::detect().should_persist_tokens(),
}
}
/// Returns true if this is a mock environment
#[must_use]
pub fn is_mock(&self) -> bool {
matches!(self, Self::Mock) || (matches!(self, Self::Auto) && Self::detect().is_mock())
}
/// Returns true if this is a live environment
#[must_use]
pub fn is_live(&self) -> bool {
matches!(self, Self::Live) || (matches!(self, Self::Auto) && Self::detect().is_live())
}
}
/// Token management strategy trait for different token handling approaches
#[async_trait]
pub trait TokenStrategy: Send + Sync + std::fmt::Debug {
/// Gets a valid authentication token
async fn get_token(&self) -> Result<String, Error>;
/// Clears stored token (for testing)
async fn clear_token(&self) -> Result<(), Error>;
/// Returns whether this strategy should persist tokens
fn should_persist(&self) -> bool;
/// Returns the strategy type for debugging
fn strategy_type(&self) -> &'static str;
/// Returns self as Any for downcasting (used internally)
fn as_any(&self) -> &dyn std::any::Any;
}
/// Mock token strategy for isolated testing without persistence
#[derive(Debug, Clone)]
pub struct MockTokenStrategy {
token: String,
}
impl MockTokenStrategy {
/// Creates a new mock token strategy with the provided token
#[must_use]
pub const fn new(token: String) -> Self {
Self { token }
}
/// Creates a mock token strategy with a default test token
#[must_use]
pub fn with_default_token() -> Self {
Self::new("mock_token_default".to_string())
}
/// Creates a mock token strategy for a specific test case
#[must_use]
pub fn for_test(test_name: &str) -> Self {
Self::new(format!("mock_token_{test_name}"))
}
}
#[async_trait]
impl TokenStrategy for MockTokenStrategy {
async fn get_token(&self) -> Result<String, Error> {
tracing::debug!("Using mock token strategy - returning pre-set token");
Ok(self.token.clone())
}
async fn clear_token(&self) -> Result<(), Error> {
tracing::debug!("Mock token strategy - clear_token is a no-op");
Ok(())
}
fn should_persist(&self) -> bool {
false
}
fn strategy_type(&self) -> &'static str {
"mock"
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// Live token strategy that wraps the existing `TokenManager` for full token management
#[derive(Debug)]
pub struct LiveTokenStrategy {
token_manager: Arc<TokenManager>,
}
impl LiveTokenStrategy {
/// Creates a new live token strategy using the global `TokenManager` instance
///
/// # Errors
/// Returns an error if the `TokenManager` cannot be initialized
pub async fn new() -> Result<Self, Error> {
let token_manager = TokenManager::get_global_instance().await?;
Ok(Self { token_manager })
}
/// Creates a new live token strategy with a custom `TokenManager`
#[must_use]
pub const fn with_token_manager(token_manager: Arc<TokenManager>) -> Self {
Self { token_manager }
}
/// Creates a live token strategy with custom retry configuration
///
/// # Errors
/// Returns an error if the `TokenManager` cannot be initialized
pub async fn with_config(config: RetryConfig) -> Result<Self, Error> {
let base_url = get_amp_api_base_url()?;
let token_manager =
Arc::new(TokenManager::with_config_and_base_url(config, base_url).await?);
Ok(Self { token_manager })
}
/// Creates a live token strategy optimized for testing
///
/// # Errors
/// Returns an error if the `TokenManager` cannot be initialized
pub async fn for_testing() -> Result<Self, Error> {
let config = RetryConfig::for_tests();
Self::with_config(config).await
}
/// Gets current token information for debugging and monitoring
///
/// # Errors
/// Returns an error if token information retrieval fails
pub async fn get_token_info(&self) -> Result<Option<TokenInfo>, Error> {
self.token_manager.get_token_info().await
}
}
#[async_trait]
impl TokenStrategy for LiveTokenStrategy {
async fn get_token(&self) -> Result<String, Error> {
tracing::debug!("Using live token strategy - full token management");
self.token_manager.get_token().await
}
async fn clear_token(&self) -> Result<(), Error> {
self.token_manager.clear_token().await
}
fn should_persist(&self) -> bool {
true
}
fn strategy_type(&self) -> &'static str {
"live"
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Missing {0} environment variable")]
MissingEnvVar(String),
#[error("AMP request failed: {0}")]
RequestFailed(String),
#[error("Failed to parse AMP response: {0}")]
ResponseParsingFailed(String),
#[error("AMP token request failed with status {status}: {error_text}")]
TokenRequestFailed {
status: reqwest::StatusCode,
error_text: String,
},
#[error("Failed to parse url: {0}")]
UrlParse(#[from] url::ParseError),
#[error("Reqwest error: {0}")]
Reqwest(#[from] reqwest::Error),
#[error("Invalid retry configuration: {0}")]
InvalidRetryConfig(String),
#[error("Token management error: {0}")]
Token(#[from] TokenError),
}
/// Detailed error types for token management operations
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum TokenError {
#[error("Token refresh failed: {0}")]
RefreshFailed(String),
#[error("Token obtain failed after {attempts} attempts: {last_error}")]
ObtainFailed { attempts: u32, last_error: String },
#[error("Rate limited: retry after {retry_after_seconds} seconds")]
RateLimited { retry_after_seconds: u64 },
#[error("Request timeout after {timeout_seconds} seconds")]
Timeout { timeout_seconds: u64 },
#[error("Serialization error: {0}")]
Serialization(String),
#[error("Token storage error: {0}")]
Storage(String),
#[error("Token validation error: {0}")]
Validation(String),
}
impl TokenError {
/// Creates a new `RefreshFailed` error
#[must_use]
pub fn refresh_failed<S: Into<String>>(message: S) -> Self {
Self::RefreshFailed(message.into())
}
/// Creates a new `ObtainFailed` error
#[must_use]
pub const fn obtain_failed(attempts: u32, last_error: String) -> Self {
Self::ObtainFailed {
attempts,
last_error,
}
}
/// Creates a new `RateLimited` error
#[must_use]
pub const fn rate_limited(retry_after_seconds: u64) -> Self {
Self::RateLimited {
retry_after_seconds,
}
}
/// Creates a new Timeout error
#[must_use]
pub const fn timeout(timeout_seconds: u64) -> Self {
Self::Timeout { timeout_seconds }
}
/// Creates a new Serialization error
#[must_use]
pub fn serialization<S: Into<String>>(message: S) -> Self {
Self::Serialization(message.into())
}
/// Creates a new Storage error
#[must_use]
pub fn storage<S: Into<String>>(message: S) -> Self {
Self::Storage(message.into())
}
/// Creates a new Validation error
#[must_use]
pub fn validation<S: Into<String>>(message: S) -> Self {
Self::Validation(message.into())
}
/// Returns true if this error indicates a retryable condition
#[must_use]
pub const fn is_retryable(&self) -> bool {
matches!(
self,
Self::RefreshFailed(_) | Self::RateLimited { .. } | Self::Timeout { .. }
)
}
/// Returns true if this error indicates a rate limiting condition
#[must_use]
pub const fn is_rate_limited(&self) -> bool {
matches!(self, Self::RateLimited { .. })
}
/// Returns the retry delay in seconds if this is a rate limited error
#[must_use]
pub const fn retry_after_seconds(&self) -> Option<u64> {
match self {
Self::RateLimited {
retry_after_seconds,
} => Some(*retry_after_seconds),
_ => None,
}
}
}
// Conversion from serde_json::Error for serialization errors
impl From<serde_json::Error> for TokenError {
fn from(err: serde_json::Error) -> Self {
Self::Serialization(err.to_string())
}
}
/// Configuration for retry behavior in API requests
#[derive(Debug, Clone)]
pub struct RetryConfig {
/// Maximum number of retry attempts
pub max_attempts: u32,
/// Base delay in milliseconds for exponential backoff
pub base_delay_ms: u64,
/// Maximum delay in milliseconds to cap exponential backoff
pub max_delay_ms: u64,
/// Request timeout in seconds
pub timeout_seconds: u64,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
max_attempts: 3,
base_delay_ms: 1000,
max_delay_ms: 30_000,
timeout_seconds: 10,
}
}
}
impl RetryConfig {
/// Creates a `RetryConfig` from environment variables with default fallbacks
///
/// Environment variables:
/// - `API_RETRY_MAX_ATTEMPTS`: Maximum retry attempts (default: 3)
/// - `API_RETRY_BASE_DELAY_MS`: Base delay in milliseconds (default: 1000)
/// - `API_RETRY_MAX_DELAY_MS`: Maximum delay in milliseconds (default: 30000)
/// - `API_REQUEST_TIMEOUT_SECONDS`: Request timeout in seconds (default: 10)
///
/// # Errors
///
/// Returns an error if any environment variable contains an invalid value
pub fn from_env() -> Result<Self, Error> {
let max_attempts = match env::var("API_RETRY_MAX_ATTEMPTS") {
Ok(val) => val.parse::<u32>().map_err(|e| {
Error::InvalidRetryConfig(format!("Invalid API_RETRY_MAX_ATTEMPTS: {e}"))
})?,
Err(_) => 3,
};
let base_delay_ms = match env::var("API_RETRY_BASE_DELAY_MS") {
Ok(val) => val.parse::<u64>().map_err(|e| {
Error::InvalidRetryConfig(format!("Invalid API_RETRY_BASE_DELAY_MS: {e}"))
})?,
Err(_) => 1000,
};
let max_delay_ms = match env::var("API_RETRY_MAX_DELAY_MS") {
Ok(val) => val.parse::<u64>().map_err(|e| {
Error::InvalidRetryConfig(format!("Invalid API_RETRY_MAX_DELAY_MS: {e}"))
})?,
Err(_) => 30_000,
};
let timeout_seconds = match env::var("API_REQUEST_TIMEOUT_SECONDS") {
Ok(val) => val.parse::<u64>().map_err(|e| {
Error::InvalidRetryConfig(format!("Invalid API_REQUEST_TIMEOUT_SECONDS: {e}"))
})?,
Err(_) => 10,
};
// Validate configuration
if max_attempts == 0 {
return Err(Error::InvalidRetryConfig(
"max_attempts must be greater than 0".to_string(),
));
}
if base_delay_ms == 0 {
return Err(Error::InvalidRetryConfig(
"base_delay_ms must be greater than 0".to_string(),
));
}
if max_delay_ms < base_delay_ms {
return Err(Error::InvalidRetryConfig(
"max_delay_ms must be greater than or equal to base_delay_ms".to_string(),
));
}
if timeout_seconds == 0 {
return Err(Error::InvalidRetryConfig(
"timeout_seconds must be greater than 0".to_string(),
));
}
Ok(Self {
max_attempts,
base_delay_ms,
max_delay_ms,
timeout_seconds,
})
}
/// Creates a `RetryConfig` optimized for test environments
///
/// Uses reduced values for faster test execution:
/// - 2 retry attempts
/// - 500ms base delay
/// - 5000ms max delay
/// - 5 second timeout
#[must_use]
pub const fn for_tests() -> Self {
Self {
max_attempts: 2,
base_delay_ms: 500,
max_delay_ms: 5000,
timeout_seconds: 5,
}
}
/// Sets a custom timeout value
#[must_use]
pub const fn with_timeout(mut self, timeout_seconds: u64) -> Self {
self.timeout_seconds = timeout_seconds;
self
}
/// Sets custom max attempts
#[must_use]
pub const fn with_max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = max_attempts;
self
}
/// Sets custom base delay
#[must_use]
pub const fn with_base_delay_ms(mut self, base_delay_ms: u64) -> Self {
self.base_delay_ms = base_delay_ms;
self
}
/// Sets custom max delay
#[must_use]
pub const fn with_max_delay_ms(mut self, max_delay_ms: u64) -> Self {
self.max_delay_ms = max_delay_ms;
self
}
}
/// HTTP client with sophisticated retry logic and exponential backoff
#[derive(Debug, Clone)]
pub struct RetryClient {
client: Client,
config: RetryConfig,
}
impl RetryClient {
/// Creates a new `RetryClient` with the given configuration
#[must_use]
pub fn new(config: RetryConfig) -> Self {
Self {
client: Client::new(),
config,
}
}
/// Creates a new `RetryClient` with default configuration
#[must_use]
pub fn with_default_config() -> Self {
Self::new(RetryConfig::default())
}
/// Creates a new `RetryClient` with test-optimized configuration
#[must_use]
pub fn for_tests() -> Self {
Self::new(RetryConfig::for_tests())
}
/// Executes an HTTP request with retry logic and exponential backoff
///
/// # Arguments
/// * `request_builder` - A function that creates the request builder
///
/// # Returns
/// The response if successful, or an error after all retries are exhausted
///
/// # Errors
/// Returns `TokenError::Timeout` if the request times out
/// Returns `TokenError::RateLimited` if rate limited and retries are exhausted
/// Returns `TokenError::ObtainFailed` if all retry attempts fail
#[allow(clippy::cognitive_complexity)]
pub async fn execute_with_retry<F>(
&self,
request_builder: F,
) -> Result<reqwest::Response, TokenError>
where
F: Fn() -> reqwest::RequestBuilder + Send + Sync,
{
let mut last_error = String::new();
let mut attempt = 0;
while attempt < self.config.max_attempts {
attempt += 1;
// Create the request with timeout
let request =
request_builder().timeout(StdDuration::from_secs(self.config.timeout_seconds));
// Execute the request
match request.send().await {
Ok(response) => {
let status = response.status();
// Handle rate limiting (429 Too Many Requests)
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
let retry_after = Self::extract_retry_after(&response).unwrap_or(60);
tracing::warn!(
"Rate limited (429) on attempt {}/{}. Retry after {} seconds",
attempt,
self.config.max_attempts,
retry_after
);
// If this is our last attempt, return the rate limit error
if attempt >= self.config.max_attempts {
return Err(TokenError::rate_limited(retry_after));
}
// Wait for the rate limit period (or our max delay, whichever is smaller)
let delay_ms = std::cmp::min(retry_after * 1000, self.config.max_delay_ms);
sleep(StdDuration::from_millis(delay_ms)).await;
continue;
}
// Handle other client errors (4xx) - these are generally not retryable
if status.is_client_error() && status != reqwest::StatusCode::TOO_MANY_REQUESTS
{
last_error = format!("Client error: {status}");
tracing::error!("Non-retryable client error: {}", status);
break;
}
// Handle server errors (5xx) - these are retryable
if status.is_server_error() {
last_error = format!("Server error: {status}");
tracing::warn!(
"Server error {} on attempt {}/{}",
status,
attempt,
self.config.max_attempts
);
if attempt < self.config.max_attempts {
let delay = self.calculate_backoff_delay(attempt);
sleep(delay).await;
continue;
}
break;
}
// Success case
return Ok(response);
}
Err(e) => {
last_error = e.to_string();
// Check if this is a timeout error
if e.is_timeout() {
tracing::warn!(
"Request timeout on attempt {}/{}",
attempt,
self.config.max_attempts
);
if attempt >= self.config.max_attempts {
return Err(TokenError::timeout(self.config.timeout_seconds));
}
} else {
tracing::warn!(
"Request failed on attempt {}/{}: {}",
attempt,
self.config.max_attempts,
e
);
}
// If we have more attempts, wait and retry
if attempt < self.config.max_attempts {
let delay = self.calculate_backoff_delay(attempt);
sleep(delay).await;
}
}
}
}
// All retries exhausted
Err(TokenError::obtain_failed(attempt, last_error))
}
/// Calculates the delay for exponential backoff with jitter
///
/// Uses the formula: `min(base_delay * 2^(attempt-1) + jitter, max_delay)`
/// where jitter is a random value between 0 and `base_delay/2`
pub fn calculate_backoff_delay(&self, attempt: u32) -> StdDuration {
use rand::Rng;
let base_delay = self.config.base_delay_ms;
let max_delay = self.config.max_delay_ms;
// Calculate exponential backoff: base_delay * 2^(attempt-1)
let exponential_delay = base_delay * 2_u64.pow(attempt.saturating_sub(1));
// Add jitter (random value between 0 and base_delay/2)
let jitter = rand::thread_rng().gen_range(0..=base_delay / 2);
let total_delay = exponential_delay + jitter;
// Cap at max_delay
let final_delay = std::cmp::min(total_delay, max_delay);
tracing::debug!(
"Calculated backoff delay for attempt {}: {}ms (exponential: {}ms, jitter: {}ms, capped at: {}ms)",
attempt,
final_delay,
exponential_delay,
jitter,
max_delay
);
StdDuration::from_millis(final_delay)
}
/// Extracts the Retry-After header value from a 429 response
///
/// Returns the number of seconds to wait, or None if the header is not present
/// or cannot be parsed
fn extract_retry_after(response: &reqwest::Response) -> Option<u64> {
response
.headers()
.get("retry-after")
.and_then(|value| value.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
}
/// Gets the underlying reqwest client
#[must_use]
pub const fn client(&self) -> &Client {
&self.client
}
/// Gets the retry configuration
#[must_use]
pub const fn config(&self) -> &RetryConfig {
&self.config
}
}
/// Singleton instance of the `TokenManager` for shared token storage across all `ApiClient` instances
static GLOBAL_TOKEN_MANAGER: OnceCell<Arc<TokenManager>> = OnceCell::const_new();
/// Core token manager with proactive refresh and secure storage
#[derive(Debug)]
pub struct TokenManager {
pub token_data: Arc<Mutex<Option<TokenData>>>,
pub retry_client: RetryClient,
base_url: Url,
/// Semaphore to ensure only one token operation (obtain/refresh) happens at a time
/// This prevents race conditions where multiple threads try to refresh/obtain simultaneously
token_operation_semaphore: Arc<Semaphore>,
}
impl TokenManager {
/// Gets the global singleton instance of `TokenManager`
///
/// This ensures all `ApiClient` instances share the same token storage,
/// preventing multiple token acquisition attempts in concurrent tests.
///
/// # Errors
/// Returns an error if the `TokenManager` cannot be initialized
pub async fn get_global_instance() -> Result<Arc<Self>, Error> {
let manager = GLOBAL_TOKEN_MANAGER
.get_or_try_init(|| async {
let config = RetryConfig::from_env()?;
let base_url = get_amp_api_base_url()?;
let manager = Self::with_config_and_base_url(config, base_url).await?;
Ok::<Arc<Self>, Error>(Arc::new(manager))
})
.await?;
Ok(manager.clone())
}
/// Creates a new `TokenManager` with default configuration
///
/// # Errors
/// Returns an error if the base URL cannot be obtained from environment variables
pub async fn new() -> Result<Self, Error> {
let config = RetryConfig::from_env()?;
Self::with_config(config).await
}
/// Creates a new `TokenManager` with the specified retry configuration
///
/// # Errors
/// Returns an error if the base URL cannot be obtained from environment variables
pub async fn with_config(config: RetryConfig) -> Result<Self, Error> {
let base_url = get_amp_api_base_url()?;
Self::with_config_and_base_url(config, base_url).await
}
/// Creates a new `TokenManager` with the specified configuration and base URL (for testing)
///
/// # Errors
/// This method is infallible but returns Result for API consistency
pub async fn with_config_and_base_url(
config: RetryConfig,
base_url: Url,
) -> Result<Self, Error> {
let manager = Self {
token_data: Arc::new(Mutex::new(None)),
retry_client: RetryClient::new(config),
base_url,
token_operation_semaphore: Arc::new(Semaphore::new(1)),
};
// Load token from disk if persistence is enabled
if Self::should_persist_tokens() {
if let Ok(Some(token_data)) = manager.load_token_from_disk().await {
*manager.token_data.lock().await = Some(token_data);
tracing::info!("Token loaded from disk during initialization");
}
}
Ok(manager)
}
/// Creates a new `TokenManager` with a pre-set mock token (for testing)
///
/// # Errors
/// This method is infallible but returns Result for API consistency
pub fn with_mock_token(
config: RetryConfig,
base_url: Url,
mock_token: String,
) -> Result<Self, Error> {
let expires_at = Utc::now() + Duration::hours(24); // Mock token valid for 24 hours
let token_data = TokenData::new(mock_token, expires_at);
let manager = Self {
token_data: Arc::new(Mutex::new(Some(token_data))),
retry_client: RetryClient::new(config),
base_url,
token_operation_semaphore: Arc::new(Semaphore::new(1)),
};
Ok(manager)
}
/// Gets a valid authentication token with proactive refresh logic
///
/// This method implements thread-safe token management logic:
/// 1. Check if a valid token exists and is not expiring soon (within 5 minutes)
/// 2. If token needs refresh/obtain, acquire semaphore to prevent concurrent operations
/// 3. Double-check token state after acquiring semaphore (another thread may have updated it)
/// 4. Perform atomic token update operations
/// 5. Return the valid token
///
/// # Thread Safety
/// This method is fully thread-safe and prevents race conditions by:
/// - Using a semaphore to ensure only one token operation at a time
/// - Double-checking token state after acquiring the semaphore
/// - Performing atomic token updates within the critical section
///
/// # Errors
/// Returns a `TokenError` if token acquisition or refresh fails after all retries
pub async fn get_token(&self) -> Result<String, Error> {
// Fast path: check if we have a valid token without acquiring semaphore
if let Some(token) = self.check_existing_token().await? {
return Ok(token);
}
// Slow path: token needs refresh/obtain, acquire semaphore for thread safety
let _permit = self.acquire_token_semaphore().await?;
// Double-check token state after acquiring semaphore - another thread may have updated it
if let Some(token) = self.check_existing_token().await? {
tracing::debug!("Token was updated by another thread, using existing valid token");
return Ok(token);
}
// At this point, we need to refresh or obtain a new token
self.handle_token_refresh_or_obtain().await
}
/// Checks if we have a valid existing token that doesn't expire soon
async fn check_existing_token(&self) -> Result<Option<String>, Error> {
let token_guard = self.token_data.lock().await;
if let Some(ref token_data) = *token_guard {
if !token_data.expires_soon(Duration::minutes(5)) {
tracing::debug!("Using existing valid token");
let token = token_data.token.expose_secret().clone();
drop(token_guard);
return Ok(Some(token));
}
}
drop(token_guard);
Ok(None)
}
/// Acquires the token operation semaphore for thread-safe operations
async fn acquire_token_semaphore(&self) -> Result<tokio::sync::SemaphorePermit<'_>, Error> {
let permit = self
.token_operation_semaphore
.acquire()
.await
.map_err(|e| {
Error::Token(TokenError::storage(format!(
"Failed to acquire token operation semaphore: {e}"
)))
})?;
tracing::debug!("Acquired token operation semaphore for thread-safe token management");
Ok(permit)
}
/// Handles the token refresh or obtain logic
async fn handle_token_refresh_or_obtain(&self) -> Result<String, Error> {
let needs_refresh = self.determine_token_operation().await;
if needs_refresh {
match self.refresh_token_internal().await {
Ok(token) => {
tracing::info!("Token refreshed successfully");
return Ok(token);
}
Err(e) => {
tracing::warn!("Token refresh failed, falling back to obtain: {e}");
// Fall through to obtain new token
}
}
}
// Either we needed to obtain from the start, or refresh failed
self.obtain_token_internal().await
}
/// Determines whether we need to refresh or obtain a new token
async fn determine_token_operation(&self) -> bool {
let token_guard = self.token_data.lock().await;
token_guard.as_ref().map_or_else(
|| {
tracing::info!("No token exists, will obtain new token");
false
},
|token_data| {
if token_data.is_expired() {
tracing::info!("Token is expired, will obtain new token");
false
} else {
tracing::info!("Token expires soon, will attempt refresh");
true
}
},
)
}
/// Obtains a new authentication token using environment credentials with retry logic
///
/// This method:
/// 1. Reads credentials from environment variables
/// 2. Makes a token request with retry logic
/// 3. Stores the new token with 24-hour expiry
/// 4. Returns the token string
///
/// # Thread Safety
/// This method acquires the token operation semaphore to ensure thread-safe operation.
/// For internal use within already-synchronized contexts, use `obtain_token_internal()`.
///
/// # Errors
/// Returns an error if:
/// - Environment variables are missing
/// - All retry attempts fail
/// - Response parsing fails
pub async fn obtain_token(&self) -> Result<String, Error> {
let _permit = self
.token_operation_semaphore
.acquire()
.await
.map_err(|e| {
Error::Token(TokenError::storage(format!(
"Failed to acquire token operation semaphore: {e}"
)))
})?;
self.obtain_token_internal().await
}
/// Internal method to obtain a new authentication token without acquiring semaphore
///
/// This method should only be called from contexts where the token operation semaphore
/// has already been acquired (e.g., from within `get_token()`).
///
/// # Errors
/// Returns an error if:
/// - Environment variables are missing
/// - All retry attempts fail
/// - Response parsing fails
async fn obtain_token_internal(&self) -> Result<String, Error> {
tracing::debug!("Obtaining new authentication token");
let request_payload = Self::get_credentials_from_env()?;
let url = self.build_obtain_token_url();
let response = self.execute_token_request(&url, &request_payload).await?;
let token_response = self.parse_token_response(response).await?;
self.store_token_data(&token_response.token).await;
tracing::info!("New authentication token obtained successfully");
Ok(token_response.token)
}
/// Gets credentials from environment variables
fn get_credentials_from_env() -> Result<TokenRequest, Error> {
let username = env::var("AMP_USERNAME")
.map_err(|_| Error::MissingEnvVar("AMP_USERNAME".to_string()))?;
let password = env::var("AMP_PASSWORD")
.map_err(|_| Error::MissingEnvVar("AMP_PASSWORD".to_string()))?;
Ok(TokenRequest { username, password })
}
/// Builds the URL for token obtain endpoint
fn build_obtain_token_url(&self) -> Url {
let mut url = self.base_url.clone();
url.path_segments_mut()
.unwrap()
.push("user")
.push("obtain_token");
url
}
/// Executes the token request with retry logic
async fn execute_token_request(
&self,
url: &Url,
request_payload: &TokenRequest,
) -> Result<reqwest::Response, Error> {
let response = self
.retry_client
.execute_with_retry(|| {
self.retry_client
.client()
.post(url.clone())
.json(request_payload)
})
.await
.map_err(Error::Token)?;
if !response.status().is_success() {
let status = response.status();
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(Error::TokenRequestFailed { status, error_text });
}
Ok(response)
}
/// Parses the token response from the API
async fn parse_token_response(
&self,
response: reqwest::Response,
) -> Result<TokenResponse, Error> {
response
.json()
.await
.map_err(|e| Error::ResponseParsingFailed(e.to_string()))
}
/// Stores the token data with 24-hour expiry and optional disk persistence
async fn store_token_data(&self, token: &str) {
let expires_at = Utc::now() + Duration::days(1);
let token_data = TokenData::new(token.to_string(), expires_at);
// Atomic token update - hold the lock for the minimal time needed
*self.token_data.lock().await = Some(token_data.clone());
tracing::debug!("Token data updated atomically in storage");
// Save to disk if persistence is enabled
if Self::should_persist_tokens() {
if let Err(e) = self.save_token_to_disk(&token_data).await {
tracing::warn!("Failed to save token to disk: {e}");
}
}
}
/// Refreshes the current authentication token with fallback to obtain on failure
///
/// This method:
/// 1. Uses the existing token to request a refresh
/// 2. Updates the stored token data on success
/// 3. Falls back to obtaining a new token if refresh fails
///
/// # Thread Safety
/// This method acquires the token operation semaphore to ensure thread-safe operation.
/// For internal use within already-synchronized contexts, use `refresh_token_internal()`.
///
/// # Errors
/// Returns an error if both refresh and obtain operations fail
pub async fn refresh_token(&self) -> Result<String, Error> {
let _permit = self
.token_operation_semaphore
.acquire()
.await
.map_err(|e| {
Error::Token(TokenError::storage(format!(
"Failed to acquire token operation semaphore: {e}"
)))
})?;
self.refresh_token_internal().await
}
/// Internal method to refresh the current authentication token without acquiring semaphore
///
/// This method should only be called from contexts where the token operation semaphore
/// has already been acquired (e.g., from within `get_token()`).
///
/// # Errors
/// Returns an error if both refresh and obtain operations fail
#[allow(clippy::cognitive_complexity)]
async fn refresh_token_internal(&self) -> Result<String, Error> {
tracing::debug!("Refreshing authentication token");
let Some(current_token) = self.get_current_token_for_refresh().await else {
tracing::warn!("No token available for refresh, obtaining new token");
return self.obtain_token_internal().await;
};
let url = self.build_refresh_token_url();
let response = self.execute_refresh_request(&url, ¤t_token).await;
match response {
Ok(resp) => self.handle_refresh_response(resp).await,
Err(e) => {
tracing::warn!("Token refresh request failed: {e}, falling back to obtain");
self.obtain_token_internal().await
}
}
}
/// Gets the current token for refresh operations
async fn get_current_token_for_refresh(&self) -> Option<String> {
let token_guard = self.token_data.lock().await;
token_guard
.as_ref()
.map(|token_data| token_data.token.expose_secret().clone())
}
/// Builds the URL for token refresh endpoint
fn build_refresh_token_url(&self) -> Url {
let mut url = self.base_url.clone();
url.path_segments_mut()
.unwrap()
.push("user")
.push("refresh_token");
url
}
/// Executes the refresh request with retry logic
async fn execute_refresh_request(
&self,
url: &Url,
current_token: &str,
) -> Result<reqwest::Response, TokenError> {
self.retry_client
.execute_with_retry(|| {
self.retry_client
.client()
.post(url.clone())
.header(AUTHORIZATION, format!("token {current_token}"))
})
.await
}
/// Handles the refresh response, either storing the new token or falling back to obtain
async fn handle_refresh_response(&self, resp: reqwest::Response) -> Result<String, Error> {
if !resp.status().is_success() {
let status = resp.status();
let error_text = resp
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
tracing::warn!("Token refresh failed with status {status}: {error_text}");
return self.obtain_token_internal().await;
}
let token_response: TokenResponse = resp
.json()
.await
.map_err(|e| Error::ResponseParsingFailed(e.to_string()))?;
self.store_token_data(&token_response.token).await;
tracing::info!("Authentication token refreshed successfully");
Ok(token_response.token)
}
/// Gets current token information for debugging and monitoring
///
/// Returns detailed information about the current token including:
/// - Expiry time and remaining duration
/// - Token age since acquisition
/// - Expiry status flags
///
/// # Returns
/// `Some(TokenInfo)` if a token exists, `None` if no token is stored
///
/// # Errors
/// Returns an error if token information retrieval fails
pub async fn get_token_info(&self) -> Result<Option<TokenInfo>, Error> {
tracing::debug!("Retrieving token information for debugging");
let token_info = self.token_data.lock().await.as_ref().map(TokenInfo::from);
match &token_info {
Some(info) => {
tracing::debug!(
"Token info retrieved - expires_at: {}, age: {:?}, expires_in: {:?}, is_expired: {}, expires_soon: {}",
info.expires_at,
info.age,
info.expires_in,
info.is_expired,
info.expires_soon
);
}
None => {
tracing::debug!("No token information available - no token stored");
}
}
Ok(token_info)
}
/// Clears the stored token (useful for testing scenarios)
///
/// This method removes the current token from storage, forcing the next
/// `get_token()` call to obtain a fresh token.
///
/// # Errors
/// Returns an error if token clearing fails
pub async fn clear_token(&self) -> Result<(), Error> {
tracing::debug!("Clearing stored token from memory and disk");
let had_token = self.clear_token_from_memory().await;
self.clear_token_from_disk_if_enabled().await;
Self::log_token_clear_result(had_token);
Ok(())
}
/// Clears the token from memory and returns whether a token was present
async fn clear_token_from_memory(&self) -> bool {
let mut token_guard = self.token_data.lock().await;
let had_token = token_guard.is_some();
*token_guard = None;
drop(token_guard);
had_token
}
/// Clears the token from disk if persistence is enabled
async fn clear_token_from_disk_if_enabled(&self) {
if Self::should_persist_tokens() {
if let Err(e) = self.remove_token_from_disk().await {
tracing::warn!("Failed to remove token from disk: {e}");
}
}
}
/// Logs the result of the token clearing operation
fn log_token_clear_result(had_token: bool) {
if had_token {
tracing::info!("Token successfully cleared from memory and disk - next get_token() will obtain fresh token");
} else {
tracing::debug!("No token was stored to clear");
}
}
/// Forces a token refresh regardless of current token status
///
/// This method bypasses the normal proactive refresh logic and immediately
/// attempts to refresh the current token. If no token exists or refresh fails,
/// it falls back to obtaining a new token.
///
/// # Thread Safety
/// This method is fully thread-safe and uses the same semaphore-based synchronization
/// as other token operations to prevent race conditions.
///
/// # Errors
/// Returns an error if both refresh and obtain operations fail
pub async fn force_refresh(&self) -> Result<String, Error> {
tracing::info!("Forcing token refresh - bypassing normal proactive refresh logic");
let _permit = self.acquire_token_semaphore().await?;
self.log_token_status_for_refresh().await;
self.execute_forced_refresh().await
}
/// Logs the current token status for forced refresh operation
async fn log_token_status_for_refresh(&self) {
let has_token = {
let token_guard = self.token_data.lock().await;
token_guard.is_some()
};
if has_token {
tracing::debug!("Existing token found, attempting forced refresh");
} else {
tracing::debug!("No existing token found, will obtain new token");
}
}
/// Executes the forced refresh operation
async fn execute_forced_refresh(&self) -> Result<String, Error> {
match self.refresh_token_internal().await {
Ok(token) => {
tracing::info!("Forced token refresh completed successfully");
Ok(token)
}
Err(e) => {
tracing::error!("Forced token refresh failed: {e}");
Err(e)
}
}
}
/// Determines if token persistence is enabled based on environment variables
///
/// Token persistence is enabled when:
/// - `AMP_TESTS=live` (for live API testing)
/// - `AMP_TOKEN_PERSISTENCE=true` is set
/// - NOT in mock test environments (to prevent test pollution)
fn should_persist_tokens() -> bool {
// Use the new environment detection logic
let environment = TokenEnvironment::detect();
// Never persist tokens in mock environments to prevent test pollution
if environment.is_mock() {
tracing::debug!("Token persistence disabled - mock environment detected");
return false;
}
// Check if explicitly enabled
if env::var("AMP_TOKEN_PERSISTENCE").unwrap_or_default() == "true" {
tracing::debug!("Token persistence enabled - AMP_TOKEN_PERSISTENCE=true");
return true;
}
// Use environment-based persistence setting
let should_persist = environment.should_persist_tokens();
tracing::debug!(
"Token persistence setting from environment: {}",
should_persist
);
should_persist
}
/// Loads token data from disk if it exists and is valid
async fn load_token_from_disk(&self) -> Result<Option<TokenData>, Error> {
let token_file = "token.json";
if !self.token_file_exists(token_file).await {
return Ok(None);
}
let content = self.read_token_file(token_file).await?;
self.parse_and_validate_token(token_file, &content).await
}
/// Checks if the token file exists on disk
async fn token_file_exists(&self, token_file: &str) -> bool {
tokio::fs::try_exists(token_file).await.map_or_else(
|_| {
tracing::debug!("Error checking token file existence: {}", token_file);
false
},
|exists| {
if !exists {
tracing::debug!("Token file does not exist: {}", token_file);
}
exists
},
)
}
/// Reads the token file content from disk
async fn read_token_file(&self, token_file: &str) -> Result<String, Error> {
use tokio::fs;
match fs::read_to_string(token_file).await {
Ok(content) => Ok(content),
Err(e) => {
tracing::warn!("Failed to read token file: {e}");
Err(Error::Token(TokenError::storage(format!(
"Failed to read token file: {e}"
))))
}
}
}
/// Parses token content and validates expiration
async fn parse_and_validate_token(
&self,
token_file: &str,
content: &str,
) -> Result<Option<TokenData>, Error> {
match serde_json::from_str::<TokenData>(content) {
Ok(token_data) => self.handle_parsed_token(token_file, token_data).await,
Err(e) => self.handle_parse_error(token_file, e).await,
}
}
/// Handles successfully parsed token data, checking expiration
async fn handle_parsed_token(
&self,
token_file: &str,
token_data: TokenData,
) -> Result<Option<TokenData>, Error> {
if token_data.is_expired() {
tracing::info!("Token loaded from disk is expired, removing file");
let _ = tokio::fs::remove_file(token_file).await;
Ok(None)
} else {
tracing::info!("Valid token loaded from disk");
Ok(Some(token_data))
}
}
/// Handles token parsing errors by cleaning up the invalid file
async fn handle_parse_error(
&self,
token_file: &str,
e: serde_json::Error,
) -> Result<Option<TokenData>, Error> {
tracing::warn!("Failed to parse token file, removing: {e}");
let _ = tokio::fs::remove_file(token_file).await;
Err(Error::Token(TokenError::serialization(format!(
"Failed to parse token file: {e}"
))))
}
/// Saves token data to disk
async fn save_token_to_disk(&self, token_data: &TokenData) -> Result<(), Error> {
use tokio::fs;
let token_file = "token.json";
match serde_json::to_string_pretty(token_data) {
Ok(json) => match fs::write(token_file, json).await {
Ok(()) => {
tracing::debug!("Token saved to disk: {}", token_file);
Ok(())
}
Err(e) => {
tracing::error!("Failed to write token file: {e}");
Err(Error::Token(TokenError::storage(format!(
"Failed to write token file: {e}"
))))
}
},
Err(e) => {
tracing::error!("Failed to serialize token data: {e}");
Err(Error::Token(TokenError::serialization(format!(
"Failed to serialize token data: {e}"
))))
}
}
}
/// Removes the token file from disk
async fn remove_token_from_disk(&self) -> Result<(), Error> {
use tokio::fs;
let token_file = "token.json";
match fs::remove_file(token_file).await {
Ok(()) => {
tracing::debug!("Token file removed from disk: {}", token_file);
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("Token file does not exist, nothing to remove");
Ok(())
}
Err(e) => {
tracing::warn!("Failed to remove token file: {e}");
Err(Error::Token(TokenError::storage(format!(
"Failed to remove token file: {e}"
))))
}
}
}
/// Forces cleanup of token persistence files (useful for testing)
/// This method removes token files regardless of persistence settings
///
/// # Errors
/// Returns an error if:
/// - File system permissions prevent deletion of the token file
/// - I/O errors occur during file deletion operations
/// - The token file is locked by another process
pub async fn force_cleanup_token_files() -> Result<(), Error> {
use tokio::fs;
let token_file = "token.json";
match fs::remove_file(token_file).await {
Ok(()) => {
tracing::debug!("Token file forcefully removed: {}", token_file);
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("No token file to clean up");
Ok(())
}
Err(e) => {
tracing::warn!("Failed to force cleanup token file: {e}");
Err(Error::Token(TokenError::storage(format!(
"Failed to force cleanup token file: {e}"
))))
}
}
}
/// Resets the global `TokenManager` singleton (useful for testing)
///
/// This method clears the global singleton instance, forcing the next
/// call to `get_global_instance()` to create a fresh `TokenManager`.
/// Primarily intended for test scenarios where a clean state is needed.
///
/// # Errors
/// Returns an error if:
/// - Token clearing operations fail during the reset process
/// - File system errors occur when clearing persistent token data
/// - The global instance is in an invalid state that prevents cleanup
pub async fn reset_global_instance() -> Result<(), Error> {
// Clear any existing token from the current global instance
if let Some(manager) = GLOBAL_TOKEN_MANAGER.get() {
let _ = manager.clear_token().await;
}
// Reset the OnceCell to allow a new instance to be created
// Note: OnceCell doesn't have a reset method, so we can't actually reset it
// The best we can do is clear the token from the existing instance
tracing::debug!("Global TokenManager instance token cleared for testing");
Ok(())
}
}
#[derive(Debug)]
pub struct ApiClient {
client: Client,
base_url: Url,
token_strategy: Box<dyn TokenStrategy>,
}
#[allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
impl ApiClient {
/// Creates a new API client with the base URL from environment variables.
///
/// Automatically selects the appropriate token strategy based on environment detection:
/// - Mock strategy for mock environments (no persistence, isolated tokens)
/// - Live strategy for live environments (full token management with persistence)
///
/// # Errors
///
/// Returns an error if:
/// - The `AMP_API_BASE_URL` environment variable contains an invalid URL
/// - Token strategy initialization fails
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a new client - automatically detects environment
/// let client = ApiClient::new().await?;
///
/// // Client is ready to use
/// let assets = client.get_assets().await?;
/// println!("Found {} assets", assets.len());
/// # Ok(())
/// # }
/// ```
pub async fn new() -> Result<Self, Error> {
let base_url = get_amp_api_base_url()?;
let client = Client::new();
// Automatic strategy selection based on environment
let token_strategy = TokenEnvironment::create_auto_strategy(None).await?;
tracing::info!(
"Created ApiClient with {} strategy for base URL: {}",
token_strategy.strategy_type(),
base_url
);
Ok(Self {
client,
base_url,
token_strategy,
})
}
/// Creates a new API client with the specified base URL.
///
/// Automatically selects the appropriate token strategy based on environment detection.
///
/// # Errors
///
/// Returns an error if token strategy initialization fails.
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # use reqwest::Url;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let base_url = Url::parse("https://amp-test.blockstream.com/api")?;
/// let client = ApiClient::with_base_url(base_url).await?;
///
/// // Client is ready to use with the specified URL
/// let assets = client.get_assets().await?;
/// # Ok(())
/// # }
/// ```
pub async fn with_base_url(base_url: Url) -> Result<Self, Error> {
let client = Client::new();
// Automatic strategy selection based on environment
let token_strategy = TokenEnvironment::create_auto_strategy(None).await?;
tracing::info!(
"Created ApiClient with {} strategy for base URL: {}",
token_strategy.strategy_type(),
base_url
);
Ok(Self {
client,
base_url,
token_strategy,
})
}
/// Creates a new API client with a custom token strategy (useful for testing).
///
/// # Errors
///
/// Returns an error if the base URL cannot be obtained from environment variables.
pub fn with_token_strategy(token_strategy: Box<dyn TokenStrategy>) -> Result<Self, Error> {
let base_url = get_amp_api_base_url()?;
tracing::info!(
"Created ApiClient with explicit {} strategy for base URL: {}",
token_strategy.strategy_type(),
base_url
);
Ok(Self {
client: Client::new(),
base_url,
token_strategy,
})
}
/// Creates a new API client with a custom token manager (useful for testing).
///
/// # Errors
///
/// Returns an error if the base URL cannot be obtained from environment variables.
pub fn with_token_manager(token_manager: Arc<TokenManager>) -> Result<Self, Error> {
let base_url = get_amp_api_base_url()?;
let token_strategy: Box<dyn TokenStrategy> =
Box::new(LiveTokenStrategy::with_token_manager(token_manager));
tracing::info!(
"Created ApiClient with custom token manager for base URL: {}",
base_url
);
Ok(Self {
client: Client::new(),
base_url,
token_strategy,
})
}
/// Creates a new API client for testing with a mock token strategy that always returns a fixed token.
/// This bypasses all token acquisition and management logic and uses complete isolation.
///
/// # Errors
///
/// This method is infallible but returns Result for API consistency.
///
/// # Examples
/// ```
/// # use amp_rs::ApiClient;
/// # use reqwest::Url;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let base_url = Url::parse("http://localhost:8080/api")?;
/// let client = ApiClient::with_mock_token(base_url, "test_token".to_string())?;
///
/// // Client will always use "test_token" for authentication
/// let token = client.get_token().await?;
/// assert_eq!(token, "test_token");
/// # Ok(())
/// # }
/// ```
pub fn with_mock_token(base_url: Url, mock_token: String) -> Result<Self, Error> {
let client = Client::new();
let token_strategy: Box<dyn TokenStrategy> = Box::new(MockTokenStrategy::new(mock_token));
tracing::info!(
"Created ApiClient with explicit mock token strategy for base URL: {}",
base_url
);
Ok(Self {
client,
base_url,
token_strategy,
})
}
/// Obtains a new authentication token from the AMP API.
///
/// **Note**: This method is deprecated in favor of the automatic token management
/// provided by `get_token()`. The `TokenManager` handles token acquisition internally
/// with enhanced retry logic and error handling.
///
/// # Errors
///
/// Returns an error if:
/// - The `AMP_USERNAME` or `AMP_PASSWORD` environment variables are not set
/// - The HTTP request fails
/// - The token request is rejected by the server
/// - The response cannot be parsed
#[deprecated(note = "Use get_token() instead - it provides automatic token management")]
pub async fn obtain_amp_token(&self) -> Result<String, Error> {
// Delegate to get_token for backward compatibility
self.get_token().await
}
/// Gets current token information for debugging and monitoring.
///
/// Returns detailed information about the current token including:
/// - Expiry time and remaining duration
/// - Token age since acquisition
/// - Expiry status flags
///
/// Note: Mock strategies may return limited or no token information.
///
/// # Returns
/// `Some(TokenInfo)` if a token exists, `None` if no token is stored or strategy doesn't support info
///
/// # Errors
/// Returns an error if token information retrieval fails
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// if let Some(token_info) = client.get_token_info().await? {
/// println!("Token expires at: {}", token_info.expires_at);
/// println!("Token is expired: {}", token_info.is_expired);
/// } else {
/// println!("No token stored or mock strategy in use");
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_token_info(&self) -> Result<Option<TokenInfo>, Error> {
// Only live strategies support detailed token information
if let Some(live_strategy) = self
.token_strategy
.as_any()
.downcast_ref::<LiveTokenStrategy>()
{
live_strategy.get_token_info().await
} else {
// Mock strategies don't provide detailed token information
tracing::debug!(
"Token info not available for {} strategy",
self.token_strategy.strategy_type()
);
Ok(None)
}
}
/// Clears the stored token (useful for testing scenarios).
///
/// This method removes the current token from storage, forcing the next
/// `get_token()` call to obtain a fresh token.
///
/// # Errors
/// Returns an error if token clearing fails
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// // Clear any existing token
/// client.clear_token().await?;
///
/// // Next get_token() call will obtain a fresh token
/// let token = client.get_token().await?;
/// # Ok(())
/// # }
/// ```
pub async fn clear_token(&self) -> Result<(), Error> {
self.token_strategy.clear_token().await
}
/// Forces a token refresh regardless of current token status.
///
/// This method bypasses the normal proactive refresh logic and immediately
/// attempts to refresh the current token. If no token exists or refresh fails,
/// it falls back to obtaining a new token.
///
/// # Errors
/// Returns an error if both refresh and obtain operations fail
pub async fn force_refresh(&self) -> Result<String, Error> {
// Clear current token and get a fresh one
self.token_strategy.clear_token().await?;
self.token_strategy.get_token().await
}
/// Resets the global `TokenManager` singleton (useful for testing).
///
/// This method clears the token from the global `TokenManager` instance.
/// Primarily intended for test scenarios where a clean token state is needed.
///
/// # Errors
/// Returns an error if the reset operation fails
pub async fn reset_global_token_manager() -> Result<(), Error> {
TokenManager::reset_global_instance().await
}
/// Gets a valid authentication token with automatic token management.
///
/// This method uses the integrated `TokenManager` to handle:
/// - Proactive token refresh (5 minutes before expiry)
/// - Automatic fallback from refresh to obtain on failure
/// - Retry logic with exponential backoff
/// - Thread-safe token storage
///
/// # Errors
///
/// Returns an error if token acquisition or refresh fails after all retries.
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// // Get a valid token - automatically handles refresh if needed
/// let token = client.get_token().await?;
/// println!("Got token: {}", &token[..10]); // Print first 10 chars
/// # Ok(())
/// # }
/// ```
pub async fn get_token(&self) -> Result<String, Error> {
self.token_strategy.get_token().await
}
/// Returns the type of token strategy currently in use
///
/// This is useful for debugging and testing to verify the correct strategy is selected.
///
/// # Returns
/// A string indicating the strategy type: "mock" or "live"
#[must_use]
pub fn get_strategy_type(&self) -> &'static str {
self.token_strategy.strategy_type()
}
/// Returns whether the current strategy persists tokens
///
/// This is useful for understanding the token management behavior.
///
/// # Returns
/// `true` if tokens are persisted to disk, `false` for in-memory only
#[must_use]
pub fn should_persist_tokens(&self) -> bool {
self.token_strategy.should_persist()
}
/// Force cleanup of token files (for test cleanup)
///
/// This is a static method that can be used to cleanup token files
/// without needing an `ApiClient` instance. Useful for test teardown.
///
/// # Errors
/// Returns an error if token file cleanup fails
pub async fn force_cleanup_token_files() -> Result<(), Error> {
// Only cleanup if we're not in a live test environment
let environment = TokenEnvironment::detect();
if !environment.is_live() || environment.is_mock() {
TokenManager::force_cleanup_token_files().await?;
tracing::debug!("Token files cleaned up for non-live environment");
} else {
tracing::debug!("Skipping token file cleanup in live environment");
}
Ok(())
}
async fn request_raw(
&self,
method: Method,
path: &[&str],
body: Option<impl serde::Serialize>,
) -> Result<reqwest::Response, Error> {
let token = self.get_token().await?;
let mut url = self.base_url.clone();
url.path_segments_mut().unwrap().extend(path);
let mut request_builder = self
.client
.request(method, url)
.header(AUTHORIZATION, format!("token {token}"));
if let Some(body) = body {
request_builder = request_builder.json(&body);
}
let response = request_builder.send().await?;
if !response.status().is_success() {
let status = response.status();
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(Error::RequestFailed(format!(
"Request to {path:?} failed with status {status}: {error_text}"
)));
}
Ok(response)
}
async fn request_json<T: DeserializeOwned>(
&self,
method: Method,
path: &[&str],
body: Option<impl serde::Serialize>,
) -> Result<T, Error> {
let response = self.request_raw(method, path, body).await?;
response
.json()
.await
.map_err(|e| Error::ResponseParsingFailed(e.to_string()))
}
async fn request_empty(
&self,
method: Method,
path: &[&str],
body: Option<impl serde::Serialize>,
) -> Result<(), Error> {
self.request_raw(method, path, body).await?;
Ok(())
}
/// Gets the API changelog.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed as JSON
pub async fn get_changelog(&self) -> Result<serde_json::Value, Error> {
self.request_json(Method::GET, &["changelog"], None::<&()>)
.await
}
/// Changes the user's password.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server rejects the password change
/// - The response cannot be parsed
pub async fn user_change_password(
&self,
password: Secret<String>,
) -> Result<ChangePasswordResponse, Error> {
let request = ChangePasswordRequest {
password: Secret::new(Password(password.expose_secret().clone())),
};
self.request_json(Method::POST, &["user", "change_password"], Some(request))
.await
}
/// Gets a list of all assets.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let assets = client.get_assets().await?;
/// for asset in assets {
/// println!("Asset: {} ({})", asset.name, asset.ticker.unwrap_or_default());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_assets(&self) -> Result<Vec<Asset>, Error> {
self.request_json(Method::GET, &["assets"], None::<&()>)
.await
}
/// Gets a specific asset by UUID.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The asset does not exist
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let asset = client.get_asset(asset_uuid).await?;
///
/// println!("Asset: {} ({})", asset.name, asset.ticker.unwrap_or_default());
/// println!("Registered: {}, Locked: {}", asset.is_registered, asset.is_locked);
/// # Ok(())
/// # }
/// ```
pub async fn get_asset(&self, asset_uuid: &str) -> Result<Asset, Error> {
self.request_json(Method::GET, &["assets", asset_uuid], None::<&()>)
.await
}
/// Issues a new asset.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The issuance request is invalid
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::IssuanceRequest};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let issuance_request = IssuanceRequest {
/// name: "My Token".to_string(),
/// amount: 1000000,
/// destination_address: "vjU2i2EM2viGEzSywpStMPkTX9U9QSDsLSN63kJJYVpxKJZuxaph8v5r5Jf11aqnfBVdjSbrvcJ2pw26".to_string(),
/// domain: "example.com".to_string(),
/// ticker: "MYTKN".to_string(),
/// pubkey: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".to_string(),
/// precision: Some(8),
/// is_confidential: Some(true),
/// is_reissuable: Some(false),
/// reissuance_amount: None,
/// reissuance_address: None,
/// transfer_restricted: Some(false),
/// };
///
/// let response = client.issue_asset(&issuance_request).await?;
/// println!("Issued asset with UUID: {}", response.asset_uuid);
/// # Ok(())
/// # }
/// ```
pub async fn issue_asset(
&self,
issuance_request: &IssuanceRequest,
) -> Result<IssuanceResponse, Error> {
self.request_json(Method::POST, &["assets", "issue"], Some(issuance_request))
.await
}
/// Edits an existing asset.
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The asset does not exist
/// - The edit request is invalid
/// - The response cannot be parsed
pub async fn edit_asset(
&self,
asset_uuid: &str,
edit_asset_request: &EditAssetRequest,
) -> Result<Asset, Error> {
self.request_json(
Method::PUT,
&["assets", asset_uuid, "edit"],
Some(edit_asset_request),
)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset does not exist or cannot be found
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
pub async fn delete_asset(&self, asset_uuid: &str) -> Result<(), Error> {
self.request_empty(
Method::DELETE,
&["assets", asset_uuid, "delete"],
None::<&()>,
)
.await
}
/// # Errors
/// Returns an error if:
/// - The transaction ID is invalid or not found
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_broadcast_status(&self, txid: &str) -> Result<BroadcastResponse, Error> {
self.request_json(Method::GET, &["tx", "broadcast", txid], None::<&()>)
.await
}
/// # Errors
/// Returns an error if:
/// - The transaction hex is invalid or malformed
/// - The transaction is rejected by the network
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn broadcast_transaction(&self, tx_hex: &str) -> Result<BroadcastResponse, Error> {
self.request_json(Method::POST, &["tx", "broadcast"], Some(tx_hex))
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The asset is already registered
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn register_asset(&self, asset_uuid: &str) -> Result<Asset, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "register"],
None::<&()>,
)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The user lacks authorization to register the asset
/// - The asset is already registered
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn register_asset_authorized(&self, asset_uuid: &str) -> Result<Asset, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "register-authorized"],
None::<&()>,
)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The asset is already locked
/// - The user lacks permission to lock the asset
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn lock_asset(&self, asset_uuid: &str) -> Result<Asset, Error> {
self.request_json(Method::PUT, &["assets", asset_uuid, "lock"], None::<&()>)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The asset is not currently locked
/// - The user lacks permission to unlock the asset
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn unlock_asset(&self, asset_uuid: &str) -> Result<Asset, Error> {
self.request_json(Method::PUT, &["assets", asset_uuid, "unlock"], None::<&()>)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The activity parameters are invalid
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_asset_activities(
&self,
asset_uuid: &str,
params: &AssetActivityParams,
) -> Result<Vec<Activity>, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "activities"],
Some(params),
)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - The specified height is invalid or out of range
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_asset_ownerships(
&self,
asset_uuid: &str,
height: Option<i64>,
) -> Result<Vec<Ownership>, Error> {
let mut path = vec!["assets", asset_uuid, "ownerships"];
let height_str;
if let Some(h) = height {
height_str = h.to_string();
path.push(&height_str);
}
self.request_json(Method::GET, &path, None::<&()>).await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_asset_balance(&self, asset_uuid: &str) -> Result<Balance, Error> {
self.request_json(Method::GET, &["assets", asset_uuid, "balance"], None::<&()>)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_asset_summary(&self, asset_uuid: &str) -> Result<AssetSummary, Error> {
self.request_json(Method::GET, &["assets", asset_uuid, "summary"], None::<&()>)
.await
}
/// # Errors
/// Returns an error if:
/// - The asset UUID is invalid or not found
/// - Authentication fails or token is invalid
/// - Network connectivity issues occur
/// - The server returns an error status
/// - The response cannot be parsed
pub async fn get_asset_utxos(&self, asset_uuid: &str) -> Result<Vec<Utxo>, Error> {
self.request_json(Method::GET, &["assets", asset_uuid, "utxos"], None::<&()>)
.await
}
/// Gets the memo for a specific asset.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to retrieve the memo for
///
/// # Returns
/// The memo string associated with the asset
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The asset does not exist
/// - The response cannot be parsed
pub async fn get_asset_memo(&self, asset_uuid: &str) -> Result<String, Error> {
self.request_json(Method::GET, &["assets", asset_uuid, "memo"], None::<&()>)
.await
}
/// Sets a memo for the specified asset.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to set the memo for
/// * `memo` - The memo string to associate with the asset
///
/// # Returns
/// Returns `Ok(())` on success.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The asset does not exist
/// - The memo cannot be set due to validation errors
///
/// # Example
/// ```rust
/// # use amp_rs::ApiClient;
/// # async fn example(client: &ApiClient) -> Result<(), Box<dyn std::error::Error>> {
/// client.set_asset_memo("asset-uuid-123", "This is a memo for the asset").await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_asset_memo(&self, asset_uuid: &str, memo: &str) -> Result<(), Error> {
let token = self.get_token().await?;
let mut url = self.base_url.clone();
url.path_segments_mut()
.unwrap()
.extend(&["assets", asset_uuid, "memo", "set"]);
let response = self
.client
.request(Method::POST, url)
.header(AUTHORIZATION, format!("token {token}"))
.header("content-type", "application/json")
.body(format!("\"{}\"", memo.replace('"', "\\\"")))
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(Error::RequestFailed(format!(
"Request to [\"assets\", \"{asset_uuid}\", \"memo\", \"set\"] failed with status {status}: {error_text}"
)));
}
Ok(())
}
/// Blacklists specific UTXOs for an asset to prevent them from being used in transactions.
///
/// This method adds the specified UTXOs to the asset's blacklist, preventing them from being
/// used in future transactions. This is typically used for security purposes when UTXOs are
/// suspected to be compromised or need to be temporarily disabled.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to blacklist UTXOs for
/// * `utxos` - A slice of `Outpoint` structs representing the UTXOs to blacklist
///
/// # Returns
/// Returns a vector of `Utxo` structs representing the blacklisted UTXOs with their updated status.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The asset UUID is invalid or does not exist
/// - One or more UTXOs are invalid or already blacklisted
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::Outpoint};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let utxos = vec![
/// Outpoint {
/// txid: "abc123...".to_string(),
/// vout: 0,
/// },
/// Outpoint {
/// txid: "def456...".to_string(),
/// vout: 1,
/// },
/// ];
///
/// let blacklisted_utxos = client.blacklist_asset_utxos(asset_uuid, &utxos).await?;
/// println!("Blacklisted {} UTXOs", blacklisted_utxos.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`whitelist_asset_utxos`](Self::whitelist_asset_utxos) - Remove UTXOs from blacklist
/// - [`get_asset`](Self::get_asset) - Get asset information including UTXO status
pub async fn blacklist_asset_utxos(
&self,
asset_uuid: &str,
utxos: &[Outpoint],
) -> Result<Vec<Utxo>, Error> {
self.request_json(
Method::POST,
&["assets", asset_uuid, "utxos", "blacklist"],
Some(utxos),
)
.await
}
/// Removes UTXOs from the asset's blacklist, allowing them to be used in transactions again.
///
/// This method removes the specified UTXOs from the asset's blacklist, restoring their ability
/// to be used in transactions. This is the reverse operation of blacklisting UTXOs.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to whitelist UTXOs for
/// * `utxos` - A slice of `Outpoint` structs representing the UTXOs to remove from blacklist
///
/// # Returns
/// Returns a vector of `Utxo` structs representing the whitelisted UTXOs with their updated status.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The asset UUID is invalid or does not exist
/// - One or more UTXOs are invalid or not currently blacklisted
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::Outpoint};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let utxos = vec![
/// Outpoint {
/// txid: "abc123...".to_string(),
/// vout: 0,
/// },
/// ];
///
/// let whitelisted_utxos = client.whitelist_asset_utxos(asset_uuid, &utxos).await?;
/// println!("Whitelisted {} UTXOs", whitelisted_utxos.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`blacklist_asset_utxos`](Self::blacklist_asset_utxos) - Add UTXOs to blacklist
/// - [`get_asset`](Self::get_asset) - Get asset information including UTXO status
pub async fn whitelist_asset_utxos(
&self,
asset_uuid: &str,
utxos: &[Outpoint],
) -> Result<Vec<Utxo>, Error> {
self.request_json(
Method::POST,
&["assets", asset_uuid, "utxos", "whitelist"],
Some(utxos),
)
.await
}
/// Gets the treasury addresses for a specific asset
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to get treasury addresses for
///
/// # Returns
/// A vector of treasury addresses as strings
///
/// # Errors
/// Returns an error if:
/// - The asset does not exist
/// - The request fails
/// - The response cannot be parsed
pub async fn get_asset_treasury_addresses(
&self,
asset_uuid: &str,
) -> Result<Vec<String>, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "treasury-addresses"],
None::<&()>,
)
.await
}
/// Adds treasury addresses to a specific asset
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to add treasury addresses to
/// * `addresses` - A slice of address strings to add as treasury addresses
///
/// # Returns
/// Returns `Ok(())` on success
///
/// # Errors
/// Returns an error if:
/// - The asset does not exist
/// - The addresses are invalid
/// - The request fails
/// - Insufficient permissions
pub async fn add_asset_treasury_addresses(
&self,
asset_uuid: &str,
addresses: &[String],
) -> Result<(), Error> {
self.request_empty(
Method::POST,
&["assets", asset_uuid, "treasury-addresses", "add"],
Some(addresses),
)
.await
}
/// Removes treasury addresses from a specific asset.
///
/// This method removes the specified addresses from the asset's treasury address list.
/// Treasury addresses are special addresses that can be used for asset management operations
/// such as reissuance and burning.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to remove treasury addresses from
/// * `addresses` - A slice of address strings to remove from the treasury addresses
///
/// # Returns
/// Returns `Ok(())` on successful removal.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The asset UUID is invalid or does not exist
/// - One or more addresses are invalid or not currently treasury addresses
/// - The HTTP request fails
/// - The server returns an error status
/// - Attempting to remove the last treasury address (if not allowed)
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let addresses = vec![
/// "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
/// "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string(),
/// ];
///
/// client.delete_asset_treasury_addresses(asset_uuid, &addresses).await?;
/// println!("Removed {} treasury addresses", addresses.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`add_asset_treasury_addresses`](Self::add_asset_treasury_addresses) - Add treasury addresses
/// - [`get_asset_treasury_addresses`](Self::get_asset_treasury_addresses) - Get current treasury addresses
/// - [`reissue_asset`](Self::reissue_asset) - Reissue assets using treasury addresses
pub async fn delete_asset_treasury_addresses(
&self,
asset_uuid: &str,
addresses: &[String],
) -> Result<(), Error> {
self.request_empty(
Method::DELETE,
&["assets", asset_uuid, "treasury-addresses", "delete"],
Some(addresses),
)
.await
}
/// Gets a list of all registered users.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let users = client.get_registered_users().await?;
/// for user in users {
/// println!("User: {} (ID: {})", user.name, user.id);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_registered_users(
&self,
) -> Result<Vec<crate::model::RegisteredUserResponse>, Error> {
self.request_json(Method::GET, &["registered_users"], None::<&()>)
.await
}
/// Gets a specific registered user by ID.
///
/// # Arguments
/// * `user_id` - The ID of the registered user to retrieve
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The user ID does not exist
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let user = client.get_registered_user(1).await?;
/// println!("User: {} (ID: {})", user.name, user.id);
/// # Ok(())
/// # }
/// ```
pub async fn get_registered_user(
&self,
user_id: i64,
) -> Result<crate::model::RegisteredUserResponse, Error> {
self.request_json(
Method::GET,
&["registered_users", &user_id.to_string()],
None::<&()>,
)
.await
}
/// Creates a new registered user in the AMP system.
///
/// This method creates a new registered user with the provided information. Registered users
/// can be associated with GAIDs, assigned to categories, and receive asset assignments.
///
/// # Arguments
/// * `new_user` - A `RegisteredUserAdd` struct containing the user information to create
///
/// # Returns
/// Returns a `RegisteredUserResponse` containing the created user's information including
/// the assigned user ID.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The user data is invalid (e.g., missing required fields, invalid email format)
/// - A user with the same identifier already exists
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::RegisteredUserAdd};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let new_user = RegisteredUserAdd {
/// name: "John Doe".to_string(),
/// gaid: Some("GAbYScu6jkWUND2jo3L4KJxyvo55d".to_string()),
/// is_company: false,
/// };
///
/// let created_user = client.add_registered_user(&new_user).await?;
/// println!("Created user: {} with ID {}", created_user.name, created_user.id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_registered_users`](Self::get_registered_users) - List all registered users
/// - [`edit_registered_user`](Self::edit_registered_user) - Update user information
/// - [`delete_registered_user`](Self::delete_registered_user) - Remove a user
pub async fn add_registered_user(
&self,
new_user: &crate::model::RegisteredUserAdd,
) -> Result<crate::model::RegisteredUserResponse, Error> {
self.request_json(Method::POST, &["registered_users", "add"], Some(new_user))
.await
}
/// Removes a registered user from the AMP system.
///
/// This method permanently deletes a registered user and all associated data. This operation
/// cannot be undone. Any GAIDs associated with the user will be disassociated, and any
/// pending assignments may be affected.
///
/// # Arguments
/// * `user_id` - The ID of the registered user to delete
///
/// # Returns
/// Returns `Ok(())` on successful deletion.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The user ID is invalid or does not exist
/// - The user has active assignments that prevent deletion
/// - The HTTP request fails
/// - The server returns an error status
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let user_id = 123;
/// client.delete_registered_user(user_id).await?;
/// println!("Successfully deleted user with ID {}", user_id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_registered_user`](Self::get_registered_user) - Get user information before deletion
/// - [`add_registered_user`](Self::add_registered_user) - Create a new user
/// - [`get_registered_user_summary`](Self::get_registered_user_summary) - Check user's assignments
pub async fn delete_registered_user(&self, user_id: i64) -> Result<(), Error> {
self.request_empty(
Method::DELETE,
&["registered_users", &user_id.to_string(), "delete"],
None::<&()>,
)
.await
}
/// Updates registered user information.
///
/// This method allows you to modify the information of an existing registered user.
/// Only the fields provided in the edit data will be updated; other fields remain unchanged.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user to update
/// * `edit_data` - A `RegisteredUserEdit` struct containing the fields to update
///
/// # Returns
/// Returns a `RegisteredUserResponse` containing the updated user information.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The user ID is invalid or does not exist
/// - The edit data contains invalid values (e.g., invalid email format)
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::RegisteredUserEdit};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let user_id = 123;
/// let edit_data = RegisteredUserEdit {
/// name: Some("Jane Doe".to_string()),
/// };
///
/// let updated_user = client.edit_registered_user(user_id, &edit_data).await?;
/// println!("Updated user: {}", updated_user.name);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_registered_user`](Self::get_registered_user) - Get current user information
/// - [`add_registered_user`](Self::add_registered_user) - Create a new user
/// - [`delete_registered_user`](Self::delete_registered_user) - Remove a user
pub async fn edit_registered_user(
&self,
registered_user_id: i64,
edit_data: &crate::model::RegisteredUserEdit,
) -> Result<crate::model::RegisteredUserResponse, Error> {
self.request_json(
Method::PUT,
&["registered_users", ®istered_user_id.to_string(), "edit"],
Some(edit_data),
)
.await
}
/// Gets comprehensive summary information for a registered user including assets and distributions.
///
/// This method retrieves detailed summary information about a registered user, including
/// their basic information, associated assets, assignment history, and distribution records.
/// This provides a complete overview of the user's activity and holdings in the system.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user to get summary for
///
/// # Returns
/// Returns a `RegisteredUserSummary` containing:
/// - Basic user information (name, email, etc.)
/// - List of associated GAIDs
/// - Asset assignments and their status
/// - Distribution history
/// - Balance information
/// - Activity timestamps
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The user ID is invalid or does not exist
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let user_id = 123;
/// let summary = client.get_registered_user_summary(user_id).await?;
///
/// println!("Asset UUID: {}", summary.asset_uuid);
/// println!("Asset ID: {}", summary.asset_id);
/// println!("Asset assignments: {}", summary.assignments.len());
/// println!("Distributions received: {}", summary.distributions.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_registered_user`](Self::get_registered_user) - Get basic user information
/// - [`get_registered_user_gaids`](Self::get_registered_user_gaids) - Get only GAIDs
/// - [`get_asset_assignments`](Self::get_asset_assignments) - Get assignments for specific asset
pub async fn get_registered_user_summary(
&self,
registered_user_id: i64,
) -> Result<crate::model::RegisteredUserSummary, Error> {
self.request_json(
Method::GET,
&[
"registered_users",
®istered_user_id.to_string(),
"summary",
],
None::<&()>,
)
.await
}
/// Gets all GAIDs (Green Address IDs) associated with a registered user.
///
/// This method retrieves a list of all GAIDs that are currently associated with the specified
/// registered user. GAIDs are unique identifiers that can be used to receive assets and
/// track ownership.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user to get GAIDs for
///
/// # Returns
/// Returns a vector of GAID strings associated with the user.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The user ID is invalid or does not exist
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let user_id = 123;
/// let gaids = client.get_registered_user_gaids(user_id).await?;
///
/// println!("User {} has {} associated GAIDs:", user_id, gaids.len());
/// for gaid in gaids {
/// println!(" - {}", gaid);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`add_gaid_to_registered_user`](Self::add_gaid_to_registered_user) - Associate a GAID with user
/// - [`set_default_gaid_for_registered_user`](Self::set_default_gaid_for_registered_user) - Set default GAID
/// - [`get_gaid_registered_user`](Self::get_gaid_registered_user) - Find user by GAID
/// - [`validate_gaid`](Self::validate_gaid) - Validate GAID format
pub async fn get_registered_user_gaids(
&self,
registered_user_id: i64,
) -> Result<Vec<String>, Error> {
self.request_json(
Method::GET,
&["registered_users", ®istered_user_id.to_string(), "gaids"],
None::<&()>,
)
.await
}
/// Associates a GAID with a registered user.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user
/// * `gaid` - The GAID to associate with the user
///
/// # Errors
///
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The registered user ID is invalid
/// - The GAID is invalid or already associated
pub async fn add_gaid_to_registered_user(
&self,
registered_user_id: i64,
gaid: &str,
) -> Result<(), Error> {
let request = GaidRequest {
gaid: gaid.to_string(),
};
self.request_empty(
Method::POST,
&[
"registered_users",
®istered_user_id.to_string(),
"gaids",
"add",
],
Some(request),
)
.await
}
/// Sets an existing GAID as the default for a registered user.
///
/// This method allows you to designate a specific GAID as the primary/default
/// GAID for a registered user. The GAID must already be associated with the user.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user
/// * `gaid` - The GAID to set as default
///
/// # Returns
/// Returns `Ok(())` if the operation is successful.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The registered user ID is invalid
/// - The GAID is not associated with the user
pub async fn set_default_gaid_for_registered_user(
&self,
registered_user_id: i64,
gaid: &str,
) -> Result<(), Error> {
let request = GaidRequest {
gaid: gaid.to_string(),
};
self.request_empty(
Method::POST,
&[
"registered_users",
®istered_user_id.to_string(),
"gaids",
"set-default",
],
Some(request),
)
.await
}
/// Retrieves the registered user associated with a GAID
///
/// # Arguments
/// * `gaid` - The GAID to look up
///
/// # Returns
/// Returns the registered user data if the GAID is associated with a user
///
/// # Errors
/// This function will return an error if:
/// - The GAID has no associated user
/// - The GAID is invalid
/// - Network or authentication errors occur
pub async fn get_gaid_registered_user(
&self,
gaid: &str,
) -> Result<crate::model::RegisteredUserResponse, Error> {
self.request_json(
Method::GET,
&["gaids", gaid, "registered_user"],
None::<&()>,
)
.await
}
/// Gets the balance information for a specific GAID.
///
/// This method retrieves all asset balances associated with the given GAID,
/// including confirmed balances and any lost outputs.
///
/// # Arguments
/// * `gaid` - The GAID to query balance for
///
/// # Returns
/// Returns a `Balance` struct containing confirmed balances and lost outputs
///
/// # Errors
/// Returns an error if:
/// - The GAID is invalid
/// - Network or authentication errors occur
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
/// let balance = client.get_gaid_balance(gaid).await?;
///
/// println!("GAID {} has {} balance entries", gaid, balance.len());
/// for entry in balance {
/// println!("Asset {}: {} units", entry.asset_id, entry.balance);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_gaid_balance(&self, gaid: &str) -> Result<Balance, Error> {
self.request_json(Method::GET, &["gaids", gaid, "balance"], None::<&()>)
.await
}
/// Retrieves the specific asset balance for a GAID
///
/// # Arguments
/// * `gaid` - The GAID to query
/// * `asset_uuid` - The UUID of the asset to query
///
/// # Returns
/// Returns the specific asset balance information
///
/// # Errors
/// Returns an error if:
/// - The GAID is invalid
/// - The asset UUID is invalid
/// - Network or authentication errors occur
/// - The response cannot be parsed
pub async fn get_gaid_asset_balance(
&self,
gaid: &str,
asset_uuid: &str,
) -> Result<Ownership, Error> {
// Try to get the response as a GaidBalanceEntry first, then convert to Ownership
let balance_entry: GaidBalanceEntry = self
.request_json(
Method::GET,
&["gaids", gaid, "balance", asset_uuid],
None::<&()>,
)
.await?;
// Convert GaidBalanceEntry to Ownership format
Ok(Ownership {
owner: gaid.to_string(),
amount: balance_entry.balance,
gaid: Some(gaid.to_string()),
})
}
/// Gets a list of all categories.
///
/// # Returns
/// Returns a vector of `CategoryResponse` objects
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let categories = client.get_categories().await?;
/// for category in categories {
/// println!("Category: {} (ID: {})", category.name, category.id);
/// if let Some(desc) = category.description {
/// println!(" Description: {}", desc);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_categories(&self) -> Result<Vec<CategoryResponse>, Error> {
self.request_json(Method::GET, &["categories"], None::<&()>)
.await
}
/// Creates a new category for organizing users and assets.
///
/// This method creates a new category that can be used to group registered users and assets
/// for organizational purposes. Categories help manage permissions and provide logical
/// groupings for assets and users.
///
/// # Arguments
/// * `new_category` - A `CategoryAdd` struct containing the category information to create
///
/// # Returns
/// Returns a `CategoryResponse` containing the created category information including
/// the assigned category ID.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category data is invalid (e.g., missing name, invalid characters)
/// - A category with the same name already exists
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::CategoryAdd};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let new_category = CategoryAdd {
/// name: "Premium Users".to_string(),
/// description: Some("High-value users with special privileges".to_string()),
/// };
///
/// let created_category = client.add_category(&new_category).await?;
/// println!("Created category: {} with ID {}", created_category.name, created_category.id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_categories`](Self::get_categories) - List all categories
/// - [`edit_category`](Self::edit_category) - Update category information
/// - [`delete_category`](Self::delete_category) - Remove a category
/// - [`add_registered_user_to_category`](Self::add_registered_user_to_category) - Add users to category
pub async fn add_category(
&self,
new_category: &CategoryAdd,
) -> Result<CategoryResponse, Error> {
self.request_json(Method::POST, &["categories", "add"], Some(new_category))
.await
}
/// Gets a specific category by ID.
///
/// This method retrieves detailed information about a specific category, including
/// its name, description, and associated users and assets.
///
/// # Arguments
/// * `category_id` - The ID of the category to retrieve
///
/// # Returns
/// Returns a `CategoryResponse` containing the category information including:
/// - Category ID, name, and description
/// - List of associated registered users
/// - List of associated assets
/// - Creation and modification timestamps
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let category = client.get_category(category_id).await?;
///
/// println!("Category: {} (ID: {})", category.name, category.id);
/// if let Some(desc) = category.description {
/// println!("Description: {}", desc);
/// }
/// println!("Users: {}, Assets: {}", category.registered_users.len(), category.assets.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_categories`](Self::get_categories) - List all categories
/// - [`add_category`](Self::add_category) - Create a new category
/// - [`edit_category`](Self::edit_category) - Update category information
/// - [`delete_category`](Self::delete_category) - Remove a category
pub async fn get_category(&self, category_id: i64) -> Result<CategoryResponse, Error> {
self.request_json(
Method::GET,
&["categories", &category_id.to_string()],
None::<&()>,
)
.await
}
/// Updates category information.
///
/// This method allows you to modify the information of an existing category.
/// Only the fields provided in the edit data will be updated; other fields remain unchanged.
///
/// # Arguments
/// * `category_id` - The ID of the category to update
/// * `edit_category` - A `CategoryEdit` struct containing the fields to update
///
/// # Returns
/// Returns a `CategoryResponse` containing the updated category information.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The edit data contains invalid values (e.g., empty name, invalid characters)
/// - A category with the new name already exists (if name is being changed)
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::CategoryEdit};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let edit_data = CategoryEdit {
/// name: Some("VIP Users".to_string()),
/// description: Some("Very important users with premium access".to_string()),
/// };
///
/// let updated_category = client.edit_category(category_id, &edit_data).await?;
/// println!("Updated category: {}", updated_category.name);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_category`](Self::get_category) - Get current category information
/// - [`add_category`](Self::add_category) - Create a new category
/// - [`delete_category`](Self::delete_category) - Remove a category
pub async fn edit_category(
&self,
category_id: i64,
edit_category: &CategoryEdit,
) -> Result<CategoryResponse, Error> {
self.request_json(
Method::PUT,
&["categories", &category_id.to_string(), "edit"],
Some(edit_category),
)
.await
}
/// Removes a category from the system.
///
/// This method permanently deletes a category. All users and assets associated with the
/// category will be disassociated, but the users and assets themselves are not deleted.
/// This operation cannot be undone.
///
/// # Arguments
/// * `category_id` - The ID of the category to delete
///
/// # Returns
/// Returns `Ok(())` on successful deletion.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The category is still in use and cannot be deleted (depending on system configuration)
/// - The HTTP request fails
/// - The server returns an error status
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// client.delete_category(category_id).await?;
/// println!("Successfully deleted category with ID {}", category_id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_category`](Self::get_category) - Get category information before deletion
/// - [`add_category`](Self::add_category) - Create a new category
/// - [`remove_registered_user_from_category`](Self::remove_registered_user_from_category) - Remove users first
/// - [`remove_asset_from_category`](Self::remove_asset_from_category) - Remove assets first
pub async fn delete_category(&self, category_id: i64) -> Result<(), Error> {
self.request_empty(
Method::DELETE,
&["categories", &category_id.to_string(), "delete"],
None::<&()>,
)
.await
}
/// Associates a registered user with a category.
///
/// This method adds a registered user to a category, allowing for organized grouping
/// of users. Users can belong to multiple categories, and categories can contain
/// multiple users.
///
/// # Arguments
/// * `category_id` - The ID of the category to add the user to
/// * `user_id` - The ID of the registered user to add to the category
///
/// # Returns
/// Returns a `CategoryResponse` containing the updated category information including
/// the newly added user.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The user ID is invalid or does not exist
/// - The user is already associated with the category
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let user_id = 123;
///
/// let updated_category = client.add_registered_user_to_category(category_id, user_id).await?;
/// println!("Added user {} to category '{}'", user_id, updated_category.name);
/// println!("Category now has {} users", updated_category.registered_users.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`remove_registered_user_from_category`](Self::remove_registered_user_from_category) - Remove user from category
/// - [`get_category`](Self::get_category) - Get category information including users
/// - [`get_registered_user`](Self::get_registered_user) - Get user information
pub async fn add_registered_user_to_category(
&self,
category_id: i64,
user_id: i64,
) -> Result<CategoryResponse, Error> {
self.request_json(
Method::PUT,
&[
"categories",
&category_id.to_string(),
"registered_users",
&user_id.to_string(),
"add",
],
None::<&()>,
)
.await
}
/// Removes a registered user from a category.
///
/// This method disassociates a registered user from a category. The user remains in the
/// system but is no longer part of the specified category. This does not affect the user's
/// association with other categories.
///
/// # Arguments
/// * `category_id` - The ID of the category to remove the user from
/// * `user_id` - The ID of the registered user to remove from the category
///
/// # Returns
/// Returns a `CategoryResponse` containing the updated category information without
/// the removed user.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The user ID is invalid or does not exist
/// - The user is not currently associated with the category
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let user_id = 123;
///
/// let updated_category = client.remove_registered_user_from_category(category_id, user_id).await?;
/// println!("Removed user {} from category '{}'", user_id, updated_category.name);
/// println!("Category now has {} users", updated_category.registered_users.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`add_registered_user_to_category`](Self::add_registered_user_to_category) - Add user to category
/// - [`get_category`](Self::get_category) - Get category information including users
/// - [`get_registered_user`](Self::get_registered_user) - Get user information
pub async fn remove_registered_user_from_category(
&self,
category_id: i64,
user_id: i64,
) -> Result<CategoryResponse, Error> {
self.request_json(
Method::PUT,
&[
"categories",
&category_id.to_string(),
"registered_users",
&user_id.to_string(),
"remove",
],
None::<&()>,
)
.await
}
/// Associates an asset with a category.
///
/// This method adds an asset to a category, allowing for organized grouping of assets.
/// Assets can belong to multiple categories, and categories can contain multiple assets.
/// This helps with asset management and permission organization.
///
/// # Arguments
/// * `category_id` - The ID of the category to add the asset to
/// * `asset_uuid` - The UUID of the asset to add to the category
///
/// # Returns
/// Returns a `CategoryResponse` containing the updated category information including
/// the newly added asset.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The asset UUID is invalid or does not exist
/// - The asset is already associated with the category
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
///
/// let updated_category = client.add_asset_to_category(category_id, asset_uuid).await?;
/// println!("Added asset {} to category '{}'", asset_uuid, updated_category.name);
/// println!("Category now has {} assets", updated_category.assets.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`remove_asset_from_category`](Self::remove_asset_from_category) - Remove asset from category
/// - [`get_category`](Self::get_category) - Get category information including assets
/// - [`get_asset`](Self::get_asset) - Get asset information
pub async fn add_asset_to_category(
&self,
category_id: i64,
asset_uuid: &str,
) -> Result<CategoryResponse, Error> {
self.request_json(
Method::PUT,
&[
"categories",
&category_id.to_string(),
"assets",
asset_uuid,
"add",
],
None::<&()>,
)
.await
}
/// Removes an asset from a category.
///
/// This method disassociates an asset from a category. The asset remains in the system
/// but is no longer part of the specified category. This does not affect the asset's
/// association with other categories.
///
/// # Arguments
/// * `category_id` - The ID of the category to remove the asset from
/// * `asset_uuid` - The UUID of the asset to remove from the category
///
/// # Returns
/// Returns a `CategoryResponse` containing the updated category information without
/// the removed asset.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The category ID is invalid or does not exist
/// - The asset UUID is invalid or does not exist
/// - The asset is not currently associated with the category
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let category_id = 1;
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
///
/// let updated_category = client.remove_asset_from_category(category_id, asset_uuid).await?;
/// println!("Removed asset {} from category '{}'", asset_uuid, updated_category.name);
/// println!("Category now has {} assets", updated_category.assets.len());
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`add_asset_to_category`](Self::add_asset_to_category) - Add asset to category
/// - [`get_category`](Self::get_category) - Get category information including assets
/// - [`get_asset`](Self::get_asset) - Get asset information
pub async fn remove_asset_from_category(
&self,
category_id: i64,
asset_uuid: &str,
) -> Result<CategoryResponse, Error> {
self.request_json(
Method::PUT,
&[
"categories",
&category_id.to_string(),
"assets",
asset_uuid,
"remove",
],
None::<&()>,
)
.await
}
/// Validates a GAID (Green Address ID).
///
/// # Arguments
/// * `gaid` - The GAID string to validate
///
/// # Returns
/// Returns a `ValidateGaidResponse` indicating whether the GAID is valid
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
/// let validation = client.validate_gaid(gaid).await?;
///
/// if validation.is_valid {
/// println!("GAID {} is valid", gaid);
/// } else {
/// println!("GAID {} is invalid: {:?}", gaid, validation.error);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn validate_gaid(
&self,
gaid: &str,
) -> Result<crate::model::ValidateGaidResponse, Error> {
self.request_json(Method::GET, &["gaids", gaid, "validate"], None::<&()>)
.await
}
/// Gets the address associated with a GAID.
///
/// # Arguments
/// * `gaid` - The GAID to get the address for
///
/// # Returns
/// Returns an `AddressGaidResponse` containing the address
///
/// # Errors
/// Returns an error if:
/// - The GAID is invalid
/// - Authentication fails
/// - The HTTP request fails
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
/// let address_response = client.get_gaid_address(gaid).await?;
///
/// println!("Address for GAID {}: {}", gaid, address_response.address);
/// # Ok(())
/// # }
/// ```
pub async fn get_gaid_address(
&self,
gaid: &str,
) -> Result<crate::model::AddressGaidResponse, Error> {
self.request_json(Method::GET, &["gaids", gaid, "address"], None::<&()>)
.await
}
/// Gets a list of all managers.
///
/// # Returns
/// Returns a vector of `Manager` objects
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let managers = client.get_managers().await?;
/// for manager in managers {
/// println!("Manager: {} (ID: {})", manager.username, manager.id);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_managers(&self) -> Result<Vec<crate::model::Manager>, Error> {
self.request_json(Method::GET, &["managers"], None::<&()>)
.await
}
/// Creates a new manager.
///
/// # Arguments
/// * `new_manager` - The manager creation request containing username and password
///
/// # Returns
/// Returns the created `Manager` object
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The manager creation request is invalid
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::ManagerCreate};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let new_manager = ManagerCreate {
/// username: "new_manager".to_string(),
/// password: "secure_password".to_string(),
/// };
///
/// let manager = client.create_manager(&new_manager).await?;
/// println!("Created manager: {} (ID: {})", manager.username, manager.id);
/// # Ok(())
/// # }
/// ```
pub async fn create_manager(
&self,
new_manager: &crate::model::ManagerCreate,
) -> Result<crate::model::Manager, Error> {
self.request_json(Method::POST, &["managers", "create"], Some(new_manager))
.await
}
/// Gets all assignments for a specific asset.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to get assignments for
///
/// # Returns
/// Returns a vector of `Assignment` objects
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The asset UUID is invalid
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let assignments = client.get_asset_assignments(asset_uuid).await?;
///
/// for assignment in assignments {
/// println!("Assignment ID: {}, Amount: {}", assignment.id, assignment.amount);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_asset_assignments(&self, asset_uuid: &str) -> Result<Vec<Assignment>, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "assignments"],
None::<&()>,
)
.await
}
/// Creates multiple asset assignments in batch.
///
/// This method creates multiple asset assignments for the specified asset. Each assignment
/// allocates a specific amount of the asset to a registered user. The assignments are
/// created individually due to API limitations, but this method handles the batch processing
/// automatically.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset to create assignments for
/// * `requests` - A slice of `CreateAssetAssignmentRequest` structs containing assignment details
///
/// # Returns
/// Returns a vector of `Assignment` structs representing the created assignments with their
/// assigned IDs and status information.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The asset UUID is invalid or does not exist
/// - Any assignment request contains invalid data (e.g., invalid user ID, negative amount)
/// - Insufficient asset balance for the total requested assignments
/// - Any individual assignment creation fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed
///
/// # Examples
/// ```no_run
/// # use amp_rs::{ApiClient, model::CreateAssetAssignmentRequest};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let requests = vec![
/// CreateAssetAssignmentRequest {
/// registered_user: 123,
/// amount: 1000,
/// vesting_timestamp: None,
/// ready_for_distribution: false,
/// },
/// CreateAssetAssignmentRequest {
/// registered_user: 456,
/// amount: 500,
/// vesting_timestamp: None,
/// ready_for_distribution: true,
/// },
/// ];
///
/// let assignments = client.create_asset_assignments(asset_uuid, &requests).await?;
/// println!("Created {} assignments", assignments.len());
/// for assignment in assignments {
/// println!("Assignment {}: {} units to user {}",
/// assignment.id, assignment.amount, assignment.registered_user);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_asset_assignments`](Self::get_asset_assignments) - List all assignments for an asset
/// - [`delete_asset_assignment`](Self::delete_asset_assignment) - Remove an assignment
/// - [`edit_asset_assignment`](Self::edit_asset_assignment) - Update assignment details
/// - [`set_assignment_ready_for_distribution`](Self::set_assignment_ready_for_distribution) - Mark for distribution
pub async fn create_asset_assignments(
&self,
asset_uuid: &str,
requests: &[CreateAssetAssignmentRequest],
) -> Result<Vec<Assignment>, Error> {
use crate::model::CreateAssetAssignmentRequestWrapper;
// The API only supports maximum length 1 per request, so we need to break
// multiple assignments into separate CreateAssetAssignmentRequestWrapper instances
let mut all_assignments = Vec::new();
for request in requests {
let wrapper = CreateAssetAssignmentRequestWrapper {
assignments: vec![request.clone()],
};
let assignments: Vec<Assignment> = self
.request_json(
Method::POST,
&["assets", asset_uuid, "assignments", "create"],
Some(&wrapper),
)
.await?;
all_assignments.extend(assignments);
}
Ok(all_assignments)
}
/// Gets a specific asset assignment by asset UUID and assignment ID.
///
/// This method sends a GET request to retrieve detailed information about a specific asset
/// assignment. Asset assignments represent the allocation of assets to users or entities,
/// including information such as the assigned amount, recipient details, and assignment status.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset for which to retrieve the assignment
/// * `assignment_id` - The ID of the specific assignment to retrieve
///
/// # Returns
/// Returns an `Assignment` struct containing the assignment details including:
/// - Assignment ID and amount
/// - Recipient information
/// - Assignment status and metadata
/// - Creation and modification timestamps
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The asset UUID is invalid or does not exist
/// - The assignment ID is invalid or does not exist
/// - The assignment is not accessible to the current user
/// - The response cannot be parsed as a valid Assignment
///
/// # Example
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// // Retrieve assignment with ID "123" for asset "550e8400-e29b-41d4-a716-446655440000"
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let assignment_id = "123";
///
/// let assignment = client.get_asset_assignment(asset_uuid, assignment_id).await?;
///
/// println!("Assignment ID: {}", assignment.id);
/// println!("Assigned amount: {}", assignment.amount);
/// println!("Registered user: {}", assignment.registered_user);
/// # Ok(())
/// # }
/// ```
pub async fn get_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error> {
self.request_json(
Method::GET,
&["assets", asset_uuid, "assignments", assignment_id],
None::<&()>,
)
.await
}
/// Gets a specific manager by ID.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to retrieve
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed as JSON
pub async fn get_manager(&self, manager_id: i64) -> Result<crate::model::Manager, Error> {
self.request_json(
Method::GET,
&["managers", &manager_id.to_string()],
None::<&()>,
)
.await
}
/// Removes a manager's permissions to modify a specific asset.
///
/// This method revokes a manager's access to a specific asset, preventing them from
/// performing asset management operations such as creating assignments, managing ownership,
/// or modifying asset properties. The manager will no longer be able to access this asset
/// through their management interface.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to remove permissions from
/// * `asset_uuid` - The UUID of the asset to remove permissions for
///
/// # Returns
/// Returns `Ok(())` on successful permission removal.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The manager ID is invalid or does not exist
/// - The asset UUID is invalid or does not exist
/// - The manager does not currently have permissions for this asset
/// - The HTTP request fails
/// - The server returns an error status
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let manager_id = 123;
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
///
/// client.manager_remove_asset(manager_id, asset_uuid).await?;
/// println!("Removed asset {} from manager {}", asset_uuid, manager_id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`add_asset_to_manager`](Self::add_asset_to_manager) - Grant manager permissions for an asset
/// - [`get_manager`](Self::get_manager) - Get manager information including current assets
/// - [`revoke_manager`](Self::revoke_manager) - Remove all asset permissions from manager
/// - [`lock_manager`](Self::lock_manager) - Lock manager account
pub async fn manager_remove_asset(
&self,
manager_id: i64,
asset_uuid: &str,
) -> Result<(), Error> {
self.request_empty(
Method::POST,
&[
"managers",
&manager_id.to_string(),
"assets",
asset_uuid,
"remove",
],
None::<&()>,
)
.await
}
/// Revokes all asset permissions for a manager.
///
/// This method first retrieves the manager's current asset permissions,
/// then removes the manager's access to each asset they currently have access to.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to revoke permissions for
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - Any individual asset removal fails
pub async fn revoke_manager(&self, manager_id: i64) -> Result<(), Error> {
// First, get the manager to see which assets they have access to
let manager = self.get_manager(manager_id).await?;
// Remove the manager's access to each asset
for asset_uuid in &manager.assets {
self.manager_remove_asset(manager_id, asset_uuid).await?;
}
Ok(())
}
/// Gets the current manager information as raw JSON.
///
/// This method calls the `/managers/me` endpoint to retrieve information
/// about the currently authenticated manager.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The response cannot be parsed as JSON
pub async fn get_current_manager_raw(&self) -> Result<serde_json::Value, Error> {
self.request_json(Method::GET, &["managers", "me"], None::<&()>)
.await
}
/// Locks a manager account to prevent further operations.
///
/// This method sends a PUT request to lock the specified manager, preventing any further
/// operations on that manager account. This is typically used for security purposes or
/// when a manager needs to be temporarily disabled.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to lock
///
/// # Returns
/// Returns `Ok(())` if the manager was successfully locked.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The manager ID is invalid or does not exist
/// - The manager is already locked
///
/// # Example
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// // Lock manager with ID 123
/// client.lock_manager(123).await?;
/// println!("Manager 123 has been locked successfully");
/// # Ok(())
/// # }
/// ```
pub async fn lock_manager(&self, manager_id: i64) -> Result<(), Error> {
self.request_empty(
Method::PUT,
&["managers", &manager_id.to_string(), "lock"],
None::<&()>,
)
.await
}
/// Unlocks a manager account.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to unlock
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
pub async fn unlock_manager(&self, manager_id: i64) -> Result<(), Error> {
self.request_empty(
Method::PUT,
&["managers", &manager_id.to_string(), "unlock"],
None::<&()>,
)
.await
}
/// Authorizes a manager to manage a specific asset.
///
/// This method sends a PUT request to authorize the specified manager to manage the given asset.
/// Once authorized, the manager will have permissions to perform operations on the asset such as
/// creating assignments, managing ownership, and other asset-related operations.
///
/// # Arguments
/// * `manager_id` - The ID of the manager to authorize
/// * `asset_uuid` - The UUID of the asset to add to the manager's authorized assets
///
/// # Returns
/// Returns `Ok(())` if the manager was successfully authorized for the asset.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The HTTP request fails
/// - The server returns an error status
/// - The manager ID is invalid or does not exist
/// - The asset UUID is invalid or does not exist
/// - The manager is already authorized for this asset
/// - The manager is locked and cannot be modified
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// // Authorize manager 123 to manage asset with UUID "550e8400-e29b-41d4-a716-446655440000"
/// let manager_id = 123;
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
///
/// client.add_asset_to_manager(manager_id, asset_uuid).await?;
/// println!("Manager {} is now authorized to manage asset {}", manager_id, asset_uuid);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`manager_remove_asset`](Self::manager_remove_asset) - Remove manager permissions for an asset
/// - [`get_manager`](Self::get_manager) - Get manager information including current assets
/// - [`get_manager_permissions`](Self::get_manager_permissions) - Get manager's current permissions
/// - [`lock_manager`](Self::lock_manager) - Lock manager account
pub async fn add_asset_to_manager(
&self,
manager_id: i64,
asset_uuid: &str,
) -> Result<(), Error> {
self.request_empty(
Method::PUT,
&[
"managers",
&manager_id.to_string(),
"assets",
asset_uuid,
"add",
],
None::<&()>,
)
.await
}
/// Deletes a specific asset assignment.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset
/// * `assignment_id` - The ID of the assignment to delete
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// Removes an asset assignment.
///
/// This method permanently deletes an asset assignment, returning the allocated assets
/// back to the available pool. This operation cannot be undone. If the assignment has
/// already been distributed, this operation may fail.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset containing the assignment
/// * `assignment_id` - The ID of the assignment to delete
///
/// # Returns
/// Returns `Ok(())` on successful deletion.
///
/// # Errors
/// Returns an error if:
/// - Authentication fails or insufficient permissions
/// - The asset UUID is invalid or does not exist
/// - The assignment ID is invalid or does not exist
/// - The assignment has already been distributed and cannot be deleted
/// - The assignment is locked and cannot be modified
/// - The HTTP request fails
/// - The server returns an error status
///
/// # Examples
/// ```no_run
/// # use amp_rs::ApiClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ApiClient::new().await?;
///
/// let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
/// let assignment_id = "123";
///
/// client.delete_asset_assignment(asset_uuid, assignment_id).await?;
/// println!("Successfully deleted assignment {}", assignment_id);
/// # Ok(())
/// # }
/// ```
///
/// # Related Methods
/// - [`get_asset_assignment`](Self::get_asset_assignment) - Get assignment details before deletion
/// - [`create_asset_assignments`](Self::create_asset_assignments) - Create new assignments
/// - [`edit_asset_assignment`](Self::edit_asset_assignment) - Update assignment instead of deleting
/// - [`lock_asset_assignment`](Self::lock_asset_assignment) - Lock assignment to prevent changes
pub async fn delete_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<(), Error> {
self.request_empty(
Method::DELETE,
&["assets", asset_uuid, "assignments", assignment_id, "delete"],
None::<&()>,
)
.await
}
/// Locks a specific asset assignment.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset
/// * `assignment_id` - The ID of the assignment to lock
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
pub async fn lock_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error> {
self.request_json(
Method::PUT,
&["assets", asset_uuid, "assignments", assignment_id, "lock"],
None::<&()>,
)
.await
}
/// Unlocks a specific asset assignment.
///
/// # Arguments
/// * `asset_uuid` - The UUID of the asset
/// * `assignment_id` - The ID of the assignment to unlock
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
pub async fn unlock_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error> {
self.request_json(
Method::PUT,
&["assets", asset_uuid, "assignments", assignment_id, "unlock"],
None::<&()>,
)
.await
}
/// Adds categories to a registered user.
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user
/// * `categories` - A slice of category IDs to add to the user
///
/// # Errors
/// Returns an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The registered user ID is invalid
/// - Any category ID is invalid
pub async fn add_categories_to_registered_user(
&self,
registered_user_id: i64,
categories: &[i64],
) -> Result<(), Error> {
let request_body = CategoriesRequest {
categories: categories.to_vec(),
};
self.request_empty(
Method::PUT,
&[
"registered_users",
®istered_user_id.to_string(),
"categories",
"add",
],
Some(request_body),
)
.await
}
/// Removes categories from a registered user
///
/// # Arguments
/// * `registered_user_id` - The ID of the registered user
/// * `categories` - A slice of category IDs to remove from the user
///
/// # Returns
/// Returns `Ok(())` if the categories are successfully removed, or an error if:
/// - Authentication fails
/// - The HTTP request fails
/// - The server returns an error status
/// - The registered user ID is invalid
/// - Any category ID is not associated with the user
pub async fn remove_categories_from_registered_user(
&self,
registered_user_id: i64,
categories: &[i64],
) -> Result<(), Error> {
let request_body = CategoriesRequest {
categories: categories.to_vec(),
};
self.request_empty(
Method::PUT,
&[
"registered_users",
®istered_user_id.to_string(),
"categories",
"delete",
],
Some(request_body),
)
.await
}
}
fn get_amp_api_base_url() -> Result<Url, Error> {
let url_str = env::var("AMP_API_BASE_URL")
.unwrap_or_else(|_| "https://amp-test.blockstream.com/api".to_string());
Url::parse(&url_str).map_err(Error::from)
}
/// Creates a token strategy based on automatic environment detection
///
/// This function detects the current environment and creates the appropriate strategy:
/// - Mock strategy for mock environments (isolated, no persistence)
/// - Live strategy for live environments (full token management)
///
/// # Arguments
/// * `mock_token` - Optional token to use for mock environments
///
/// # Errors
/// Returns an error if strategy creation fails
pub async fn create_auto_token_strategy(
mock_token: Option<String>,
) -> Result<Box<dyn TokenStrategy>, Error> {
TokenEnvironment::create_auto_strategy(mock_token).await
}
/// Creates a mock token strategy with the specified token
///
/// # Arguments
/// * `token` - The mock token to use
#[must_use]
pub fn create_mock_token_strategy(token: String) -> Box<dyn TokenStrategy> {
Box::new(MockTokenStrategy::new(token))
}
/// Creates a live token strategy with default configuration
///
/// # Errors
/// Returns an error if the `TokenManager` cannot be initialized
pub async fn create_live_token_strategy() -> Result<Box<dyn TokenStrategy>, Error> {
let strategy = LiveTokenStrategy::new().await?;
Ok(Box::new(strategy))
}
/// Creates a token strategy for the specified environment
///
/// # Arguments
/// * `environment` - The target environment
/// * `mock_token` - Optional token to use for mock environments
///
/// # Errors
/// Returns an error if strategy creation fails
pub async fn create_token_strategy_for_environment(
environment: TokenEnvironment,
mock_token: Option<String>,
) -> Result<Box<dyn TokenStrategy>, Error> {
environment.create_strategy(mock_token).await
}
#[cfg(test)]
mod tests {
use super::*;
use tokio;
#[tokio::test]
async fn test_mock_token_strategy_basic_functionality() {
let mock_token = "mock_token_12_345".to_string();
let strategy = MockTokenStrategy::new(mock_token.clone());
// Test get_token returns the mock token
let result = strategy.get_token().await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), mock_token);
// Test strategy type identification
assert_eq!(strategy.strategy_type(), "mock");
// Test persistence is disabled
assert!(!strategy.should_persist());
// Test clear_token is a no-op (should not fail)
let clear_result = strategy.clear_token().await;
assert!(clear_result.is_ok());
// Verify token is still available after clear (since it's a no-op for mock)
let token_after_clear = strategy.get_token().await;
assert!(token_after_clear.is_ok());
assert_eq!(token_after_clear.unwrap(), mock_token);
}
#[tokio::test]
async fn test_mock_token_strategy_isolation() {
let token1 = "token_instance_1".to_string();
let token2 = "token_instance_2".to_string();
let strategy1 = MockTokenStrategy::new(token1.clone());
let strategy2 = MockTokenStrategy::new(token2.clone());
// Test that different instances are isolated
let result1 = strategy1.get_token().await.unwrap();
let result2 = strategy2.get_token().await.unwrap();
assert_eq!(result1, token1);
assert_eq!(result2, token2);
assert_ne!(result1, result2);
// Test that operations on one don't affect the other
let _ = strategy1.clear_token().await;
let result2_after_clear = strategy2.get_token().await.unwrap();
assert_eq!(result2_after_clear, token2);
}
#[tokio::test]
async fn test_live_token_strategy_creation() {
// Test creating a live strategy with global instance
let strategy_result = LiveTokenStrategy::new().await;
assert!(strategy_result.is_ok());
let strategy = strategy_result.unwrap();
assert_eq!(strategy.strategy_type(), "live");
assert!(strategy.should_persist());
}
#[tokio::test]
async fn test_live_token_strategy_with_custom_manager() {
// Create a custom token manager for testing
let config = RetryConfig::for_tests();
let base_url = Url::parse("http://localhost:8080").unwrap();
let mock_token = "test_live_token".to_string();
let token_manager =
Arc::new(TokenManager::with_mock_token(config, base_url, mock_token.clone()).unwrap());
let strategy = LiveTokenStrategy::with_token_manager(token_manager);
// Test strategy properties
assert_eq!(strategy.strategy_type(), "live");
assert!(strategy.should_persist());
// Test token retrieval
let token_result = strategy.get_token().await;
assert!(token_result.is_ok());
assert_eq!(token_result.unwrap(), mock_token);
}
#[tokio::test]
async fn test_live_token_strategy_clear_token() {
// Create a live strategy with a mock token manager
let config = RetryConfig::for_tests();
let base_url = Url::parse("http://localhost:8080").unwrap();
let mock_token = "test_clear_token".to_string();
let token_manager =
Arc::new(TokenManager::with_mock_token(config, base_url, mock_token.clone()).unwrap());
let strategy = LiveTokenStrategy::with_token_manager(token_manager);
// Verify token is available initially
let initial_token = strategy.get_token().await;
assert!(initial_token.is_ok());
assert_eq!(initial_token.unwrap(), mock_token);
// Clear the token
let clear_result = strategy.clear_token().await;
assert!(clear_result.is_ok());
// Note: After clearing, the TokenManager would try to obtain a new token
// In a real scenario, this would fail without proper credentials
// But our mock token manager will still return the same token
}
#[tokio::test]
async fn test_strategy_type_identification() {
let mock_strategy = MockTokenStrategy::new("test_token".to_string());
let live_strategy = LiveTokenStrategy::new().await.unwrap();
// Test that we can identify strategy types for debugging
assert_eq!(mock_strategy.strategy_type(), "mock");
assert_eq!(live_strategy.strategy_type(), "live");
// Test persistence settings
assert!(!mock_strategy.should_persist());
assert!(live_strategy.should_persist());
}
#[tokio::test]
async fn test_strategy_debug_formatting() {
let mock_strategy = MockTokenStrategy::new("debug_test_token".to_string());
let debug_output = format!("{mock_strategy:?}");
// Verify debug output contains expected information
assert!(debug_output.contains("MockTokenStrategy"));
assert!(debug_output.contains("debug_test_token"));
}
// Environment Detection Tests
#[test]
fn test_token_environment_detect_live_via_amp_tests() {
// Set up environment for live test detection
env::set_var("AMP_TESTS", "live");
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "real_pass");
env::remove_var("AMP_API_BASE_URL");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Live);
// Clean up
env::remove_var("AMP_TESTS");
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
}
#[test]
fn test_token_environment_detect_mock_via_credentials() {
// Set up environment for mock detection via username
env::remove_var("AMP_TESTS");
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "real_pass");
env::remove_var("AMP_API_BASE_URL");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
// Test mock detection via password
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "mock_pass");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
}
#[test]
fn test_token_environment_detect_mock_via_base_url() {
// Set up environment for mock detection via localhost URL
env::remove_var("AMP_TESTS");
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "real_pass");
env::set_var("AMP_API_BASE_URL", "http://localhost:8080/api");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
// Test with 127.0.0.1
env::set_var("AMP_API_BASE_URL", "http://127.0.0.1:3000/api");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
// Test with mock in URL
env::set_var("AMP_API_BASE_URL", "http://mock-server.example.com/api");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_API_BASE_URL");
}
#[test]
fn test_token_environment_detect_live_via_real_credentials() {
// Set up environment for live detection via real credentials
env::remove_var("AMP_TESTS");
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "real_pass");
env::set_var("AMP_API_BASE_URL", "https://amp-test.blockstream.com/api");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Live);
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_API_BASE_URL");
}
#[test]
fn test_token_environment_detect_mock_fallback() {
// Set up environment with no credentials (fallback to mock)
env::remove_var("AMP_TESTS");
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_API_BASE_URL");
let environment = TokenEnvironment::detect();
assert_eq!(environment, TokenEnvironment::Mock);
}
#[test]
fn test_has_mock_credentials() {
// Test mock username detection
assert!(TokenEnvironment::has_mock_credentials(
"mock_user",
"real_pass",
""
));
assert!(TokenEnvironment::has_mock_credentials(
"Mock_User",
"real_pass",
""
));
assert!(TokenEnvironment::has_mock_credentials(
"user_mock",
"real_pass",
""
));
// Test mock password detection
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"mock_pass",
""
));
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"Mock_Pass",
""
));
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"pass_mock",
""
));
// Test mock URL detection
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"real_pass",
"http://localhost:8080"
));
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"real_pass",
"http://127.0.0.1:3000"
));
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"real_pass",
"http://mock-server.com"
));
assert!(TokenEnvironment::has_mock_credentials(
"real_user",
"real_pass",
"http://Mock-Server.com"
));
// Test non-mock credentials
assert!(!TokenEnvironment::has_mock_credentials(
"real_user",
"real_pass",
"https://amp-test.blockstream.com"
));
assert!(!TokenEnvironment::has_mock_credentials("", "", ""));
}
#[test]
fn test_token_environment_should_persist_tokens() {
assert!(!TokenEnvironment::Mock.should_persist_tokens());
assert!(TokenEnvironment::Live.should_persist_tokens());
// Auto should delegate to detect()
env::set_var("AMP_TESTS", "live");
assert!(TokenEnvironment::Auto.should_persist_tokens());
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "some_password");
env::remove_var("AMP_TESTS");
env::remove_var("AMP_API_BASE_URL");
assert!(!TokenEnvironment::Auto.should_persist_tokens());
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
}
#[test]
fn test_token_environment_is_mock_and_is_live() {
assert!(TokenEnvironment::Mock.is_mock());
assert!(!TokenEnvironment::Mock.is_live());
assert!(!TokenEnvironment::Live.is_mock());
assert!(TokenEnvironment::Live.is_live());
// Auto should delegate to detect()
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "some_password");
env::remove_var("AMP_TESTS");
env::remove_var("AMP_API_BASE_URL");
assert!(TokenEnvironment::Auto.is_mock());
assert!(!TokenEnvironment::Auto.is_live());
env::set_var("AMP_TESTS", "live");
assert!(!TokenEnvironment::Auto.is_mock());
assert!(TokenEnvironment::Auto.is_live());
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_TESTS");
}
#[tokio::test]
async fn test_token_environment_create_strategy_mock() {
let mock_token = "test_mock_token".to_string();
let strategy = TokenEnvironment::Mock
.create_strategy(Some(mock_token.clone()))
.await
.unwrap();
assert_eq!(strategy.strategy_type(), "mock");
assert!(!strategy.should_persist());
let token = strategy.get_token().await.unwrap();
assert_eq!(token, mock_token);
}
#[tokio::test]
async fn test_token_environment_create_strategy_live() {
let strategy = TokenEnvironment::Live.create_strategy(None).await.unwrap();
assert_eq!(strategy.strategy_type(), "live");
assert!(strategy.should_persist());
}
#[tokio::test]
async fn test_token_environment_create_auto_strategy() {
// Test with mock environment - need both username and password for proper detection
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "some_password");
env::remove_var("AMP_TESTS");
env::remove_var("AMP_API_BASE_URL");
let mock_token = "auto_mock_token".to_string();
let strategy = TokenEnvironment::create_auto_strategy(Some(mock_token.clone()))
.await
.unwrap();
assert_eq!(strategy.strategy_type(), "mock");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, mock_token);
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
}
#[tokio::test]
async fn test_mock_token_strategy_factory_methods() {
// Test with_default_token
let strategy = MockTokenStrategy::with_default_token();
assert_eq!(strategy.strategy_type(), "mock");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, "mock_token_default");
// Test for_test
let strategy = MockTokenStrategy::for_test("my_test");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, "mock_token_my_test");
}
#[tokio::test]
async fn test_live_token_strategy_factory_methods() {
// Test for_testing
let strategy = LiveTokenStrategy::for_testing().await.unwrap();
assert_eq!(strategy.strategy_type(), "live");
assert!(strategy.should_persist());
}
#[tokio::test]
async fn test_standalone_factory_functions() {
// Test create_mock_token_strategy
let mock_token = "standalone_mock".to_string();
let strategy = create_mock_token_strategy(mock_token.clone());
assert_eq!(strategy.strategy_type(), "mock");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, mock_token);
// Test create_live_token_strategy
let strategy = create_live_token_strategy().await.unwrap();
assert_eq!(strategy.strategy_type(), "live");
// Test create_auto_token_strategy with mock environment
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "some_password");
env::remove_var("AMP_TESTS");
env::remove_var("AMP_API_BASE_URL");
let auto_mock_token = "auto_standalone_mock".to_string();
let strategy = create_auto_token_strategy(Some(auto_mock_token.clone()))
.await
.unwrap();
assert_eq!(strategy.strategy_type(), "mock");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, auto_mock_token);
// Test create_token_strategy_for_environment
let env_mock_token = "env_mock".to_string();
let strategy = create_token_strategy_for_environment(
TokenEnvironment::Mock,
Some(env_mock_token.clone()),
)
.await
.unwrap();
assert_eq!(strategy.strategy_type(), "mock");
let token = strategy.get_token().await.unwrap();
assert_eq!(token, env_mock_token);
// Clean up
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
}
#[test]
fn test_environment_detection_with_various_credential_combinations() {
// Test case 1: AMP_TESTS=live overrides everything
env::set_var("AMP_TESTS", "live");
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "mock_pass");
env::set_var("AMP_API_BASE_URL", "http://localhost:8080");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Live);
// Test case 2: Mock username with real password and URL
env::remove_var("AMP_TESTS");
env::set_var("AMP_USERNAME", "mock_user");
env::set_var("AMP_PASSWORD", "real_password");
env::set_var("AMP_API_BASE_URL", "https://amp-test.blockstream.com/api");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Test case 3: Real username with mock password
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "mock_password");
env::set_var("AMP_API_BASE_URL", "https://amp-test.blockstream.com/api");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Test case 4: Real credentials with localhost URL
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "real_password");
env::set_var("AMP_API_BASE_URL", "http://localhost:3000/api");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Test case 5: All real credentials
env::set_var("AMP_USERNAME", "real_user");
env::set_var("AMP_PASSWORD", "real_password");
env::set_var("AMP_API_BASE_URL", "https://amp-test.blockstream.com/api");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Live);
// Test case 6: Empty credentials
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_API_BASE_URL");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Test case 7: Only username set
env::set_var("AMP_USERNAME", "real_user");
env::remove_var("AMP_PASSWORD");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Test case 8: Only password set
env::remove_var("AMP_USERNAME");
env::set_var("AMP_PASSWORD", "real_password");
assert_eq!(TokenEnvironment::detect(), TokenEnvironment::Mock);
// Clean up all environment variables
env::remove_var("AMP_TESTS");
env::remove_var("AMP_USERNAME");
env::remove_var("AMP_PASSWORD");
env::remove_var("AMP_API_BASE_URL");
}
}