snip-sync 0.2.0

gRPC sync server for snp snippet manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
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
// The `format!("{}", var)` patterns below are inherited from the
// pre-existing main.rs implementation. They were not flagged by clippy
// when the code lived in a binary crate's `#[cfg(test)] mod tests`
// (binary test targets are not always checked by `cargo clippy
// --all-targets`), but moving the code into the library makes them
// visible to lib test compilation. The lint suppression keeps the
// refactor minimal; a follow-up should inline the args.
//
// Similarly, `RateLimiter::new()` and a few other constructors predate
// the refactor and never carried a `Default` impl. Suppressing
// `new_without_default` here keeps the diff focused.
#![allow(clippy::uninlined_format_args, clippy::new_without_default)]

pub mod bootstrap;
pub mod cert;
pub mod cli;
pub mod db;
pub mod editor;
pub mod http;
pub mod metrics;
pub mod orchestration;
pub mod paths;
pub mod premade;
pub mod process;
pub mod rate_limiter;
pub mod server_lock;
pub mod startup;
#[cfg(any(test, feature = "test-helpers"))]
pub mod test_helpers;
#[cfg(any(test, feature = "test-helpers"))]
pub mod test_observer;
pub mod toml_escapes;

pub use db::Database;
pub use metrics::Metrics;
pub use premade::PremadeManager;
pub use rate_limiter::RateLimiter;

use prost::Message;
use serde::Deserialize;
use snip_proto::{
    CreateLibraryRequest, CreateLibraryResponse, DeleteLibraryRequest, DeleteLibraryResponse,
    GetPremadeLibraryRequest, GetPremadeLibraryResponse, GetSnippetsRequest, HealthRequest,
    HealthResponse, Library, ListLibrariesRequest, ListLibrariesResponse,
    ListPremadeLibrariesRequest, ListPremadeLibrariesResponse,
    PremadeLibrary as ProtoPremadeLibrary, PushSnippetsRequest, PushSnippetsResponse,
    RegisterRequest, RegisterResponse, SearchPremadeLibrariesRequest,
    SearchPremadeLibrariesResponse, Snippet as ProtoSnippet, SnippetList, SyncRequest,
    SyncResponse, snippet_sync_server::SnippetSync,
};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tonic::{Request, Response, Status};

/// Extract the API key from a gRPC request's `authorization` metadata.
/// Falls back to the body `api_key` field for backward compatibility.
///
/// The auth-scheme token is case-insensitive (RFC 9110 §11.1), so `Bearer`,
/// `bearer`, and `BEARER` are all accepted. Only the scheme is matched
/// leniently; the credential itself is used verbatim (minus surrounding
/// whitespace) and compared exactly by the authentication path.
pub fn extract_api_key<T>(request: &Request<T>, body_api_key: &str) -> String {
    request
        .metadata()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| {
            let (scheme, credential) = v.split_once(' ')?;
            scheme
                .eq_ignore_ascii_case("bearer")
                .then(|| credential.trim().to_owned())
        })
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| body_api_key.to_string())
}

/// Strip a trailing `:port` suffix from a peer address.
///
/// The value can be attacker-influenced (it comes from the `x-forwarded-for`
/// header behind a trusted proxy), so malformed input is returned unchanged
/// rather than panicking — the result is only ever used as a rate-limit
/// bucket key.
fn strip_port(addr: &str) -> String {
    if let Some(close_bracket) = addr.find("]:") {
        // Only a bracketed IPv6 literal (`[::1]:443`) has a `]:` separator.
        // Anything else is malformed: slicing it would produce a bogus
        // address, and slicing at offset 0 would panic outright.
        if close_bracket > 0 && addr.starts_with('[') {
            return addr[1..close_bracket].to_string();
        }
        return addr.to_string();
    }
    // Bare IPv6 addresses contain multiple colons but no brackets.
    // They have no port to strip, so return as-is.
    if !addr.starts_with('[') && addr.matches(':').count() > 1 {
        return addr.to_string();
    }
    if let Some(colon_pos) = addr.rfind(':')
        && !addr.starts_with('[')
    {
        return addr[..colon_pos].to_string();
    }
    addr.to_string()
}

pub const DEFAULT_MAX_COMMAND_LENGTH: usize = 1024;
// Encrypted records carry description + command + tags as one AES-256-GCM
// payload in `command`, base64-expanded (~1.37x the plaintext JSON). The cap
// is deliberately far above `max_command_length` so ordinary snippets are
// unaffected; its job is to make storage bounded and to guarantee a single
// record can always be transported, since anything larger than the gRPC
// message ceiling could be stored but never downloaded again.
pub const DEFAULT_MAX_ENCRYPTED_PAYLOAD_LENGTH: usize = 1024 * 1024; // 1 MiB
pub const DEFAULT_MAX_DESCRIPTION_LENGTH: usize = 1024;
pub const DEFAULT_MAX_TAGS: usize = 50;
pub const DEFAULT_MAX_TAG_LENGTH: usize = 100;
pub const DEFAULT_MAX_ID_LENGTH: usize = 128;
pub const DEFAULT_MAX_DEVICE_ID_LENGTH: usize = 128;
pub const DEFAULT_MAX_API_KEY_LENGTH: usize = 512;
pub const DEFAULT_MAX_SYNC_SNIPPETS: usize = 10000;
pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;
pub const DEFAULT_RATE_LIMIT_PER_MINUTE: u32 = 120;
/// Global ceiling on successful account creations per minute, independent of
/// the caller's address. The per-peer `register:<peer>` budget alone lets an
/// attacker with many addresses grow the user table without bound.
pub const DEFAULT_REGISTER_PER_MINUTE: u32 = 10;
/// Global ceiling on **failed** `/metrics` authentications per minute. Correct
/// credentials never consume it, so an attacker cannot deny the operator their
/// own scrape by burning the budget.
pub const DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE: u32 = 10;
/// Multiplier applied to the per-peer budget for requests that have **not**
/// yet authenticated. The pre-authentication budget only has to bound the cost
/// of an API-key lookup, so it is generous by design: an unauthenticated
/// caller must not be able to exhaust the budget that legitimate callers
/// spend on the authenticated surface.
pub const PRE_AUTH_RATE_LIMIT_MULTIPLIER: u32 = 10;
pub const DEFAULT_DB_MAX_CONNECTIONS: u32 = 5;
pub const DEFAULT_GRPC_MAX_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; // 4 MiB
/// Hard upper bound for any single request's page size. Endpoints choose
/// their own default page size when the client omits one (`sync` → 1000,
/// `get_snippets` → 100, `list_libraries` → 50); all are clamped here.
pub const MAX_REQUEST_LIMIT: i32 = 1000;

/// Bytes held back from the gRPC encode ceiling for the response envelope
/// (status message, `skipped_ids`, scalar fields, and protobuf framing).
const RESPONSE_ENVELOPE_RESERVE_BYTES: usize = 64 * 1024;

/// Encoded-byte budget available to the `snippets` array of one response,
/// given the configured gRPC ceiling and any other variable-length payload the
/// envelope already carries.
fn page_byte_ceiling(grpc_ceiling: usize, envelope_bytes: usize) -> usize {
    grpc_ceiling
        .saturating_sub(RESPONSE_ENVELOPE_RESERVE_BYTES)
        .saturating_sub(envelope_bytes)
}

/// Drop trailing rows from a response page until its encoded size fits
/// `ceiling`; returns whether anything was dropped.
///
/// Downloads are paged by *row count*, but tonic hard-fails an over-size
/// encoding with `OUT_OF_RANGE` instead of truncating. Without this bound a
/// library whose rows happen to be large can be pushed successfully and then
/// never downloaded again, by any client, for any page size. The caller sets
/// `has_more` from the return value so the remainder is still fetched.
fn fit_page_to_byte_ceiling(snippets: &mut Vec<ProtoSnippet>, ceiling: usize) -> bool {
    let mut used = 0usize;
    let mut kept = 0usize;
    for snippet in snippets.iter() {
        let len = snippet.encoded_len();
        // Always keep at least one row. A single record larger than the whole
        // ceiling cannot be made to fit, and returning an empty page would
        // stall the client's pagination loop rather than make progress.
        if kept > 0 && used.saturating_add(len) > ceiling {
            break;
        }
        used = used.saturating_add(len);
        kept += 1;
    }
    let truncated = kept < snippets.len();
    if truncated {
        tracing::info!(
            dropped = snippets.len() - kept,
            kept_bytes = used,
            ceiling_bytes = ceiling,
            "Response page trimmed to fit the gRPC encode ceiling"
        );
        snippets.truncate(kept);
    }
    truncated
}

#[derive(Deserialize, Default)]
pub struct ConfigFile {
    pub server: Option<ServerConfig>,
}

#[derive(Deserialize, Default)]
pub struct ServerConfig {
    pub grpc_host: Option<String>,
    pub grpc_port: Option<u16>,
    pub http_host: Option<String>,
    pub http_port: Option<u16>,
    pub database: Option<DatabaseConfig>,
    pub premade: Option<PremadeConfig>,
    pub limits: Option<LimitsConfig>,
    pub rate_limit: Option<RateLimitConfig>,
    pub metrics: Option<MetricsConfig>,
    pub cors: Option<CorsConfig>,
}

#[derive(Deserialize, Default)]
pub struct DatabaseConfig {
    pub path: Option<String>,
    pub max_connections: Option<u32>,
}

#[derive(Deserialize, Default)]
pub struct PremadeConfig {
    pub directory: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct LimitsConfig {
    pub max_command_length: Option<usize>,
    pub max_encrypted_payload_length: Option<usize>,
    pub max_description_length: Option<usize>,
    pub max_tags: Option<usize>,
    pub max_tag_length: Option<usize>,
    pub max_id_length: Option<usize>,
    pub max_device_id_length: Option<usize>,
    pub max_api_key_length: Option<usize>,
    pub request_timeout_secs: Option<u64>,
    pub grpc_max_message_size: Option<u32>,
}

#[derive(Deserialize, Default)]
pub struct RateLimitConfig {
    pub requests_per_minute: Option<u32>,
    /// Global per-minute ceiling on account creation (all peers combined).
    pub register_per_minute: Option<u32>,
    /// Global per-minute ceiling on failed `/metrics` authentications.
    pub metrics_auth_failures_per_minute: Option<u32>,
    pub trusted_proxies: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
pub struct MetricsConfig {
    pub username: Option<String>,
    pub password: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct CorsConfig {
    pub allowed_origins: Option<String>,
}

#[derive(Clone, Debug)]
pub struct Config {
    pub grpc_host: String,
    pub grpc_port: u16,
    pub http_host: String,
    pub http_port: u16,
    pub db_path: String,
    pub db_max_connections: u32,
    pub premade_dir: PathBuf,
    pub max_command_length: usize,
    pub max_encrypted_payload_length: usize,
    pub max_description_length: usize,
    pub max_tags: usize,
    pub max_tag_length: usize,
    pub max_id_length: usize,
    pub max_device_id_length: usize,
    pub max_api_key_length: usize,
    pub request_timeout_secs: u64,
    pub grpc_max_message_size: u32,
    pub rate_limit_per_minute: u32,
    /// Global per-minute ceiling on account creation, across all peers.
    pub register_per_minute: u32,
    /// Global per-minute ceiling on failed `/metrics` authentications.
    pub metrics_auth_failures_per_minute: u32,
    pub trusted_proxies: Vec<String>,
    pub metrics_username: Option<String>,
    pub metrics_password: Option<String>,
    pub cors_allowed_origins: Vec<String>,
}

#[derive(Debug, thiserror::Error)]
pub enum ConfigLoadError {
    #[error("failed to read configuration file {path}: {source}")]
    Read {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("failed to parse configuration file {path}: {source}")]
    Parse {
        path: PathBuf,
        source: toml::de::Error,
    },
    #[error("invalid environment variable {name}={value:?}: {reason}")]
    InvalidEnvironment {
        name: &'static str,
        value: String,
        reason: String,
    },
    #[error("invalid configuration value {name}={value:?}: {reason}")]
    InvalidRange {
        name: &'static str,
        value: String,
        reason: String,
    },
}

/// Parse an optional environment variable, returning the typed value if present and valid.
///
/// Missing variable → `Ok(None)`. Present and valid → `Ok(Some(value))`.
/// Present and invalid → `Err(ConfigLoadError::InvalidEnvironment)`.
pub fn parse_env<T>(
    env: &impl Fn(&str) -> Option<String>,
    name: &'static str,
) -> Result<Option<T>, ConfigLoadError>
where
    T: std::str::FromStr,
    T::Err: std::fmt::Display,
{
    match env(name) {
        Some(val) => match val.parse::<T>() {
            Ok(parsed) => Ok(Some(parsed)),
            Err(e) => Err(ConfigLoadError::InvalidEnvironment {
                name,
                value: val,
                reason: e.to_string(),
            }),
        },
        None => Ok(None),
    }
}

/// Parse an optional boolean environment variable.
///
/// Accepted true values (case-insensitive): `true`, `1`, `yes`, `on`
/// Accepted false values (case-insensitive): `false`, `0`, `no`, `off`
///
/// Missing variable → `Ok(None)`. Present and valid → `Ok(Some(bool))`.
/// Present and invalid → `Err(ConfigLoadError::InvalidEnvironment)`.
pub fn parse_bool_env(
    env: &impl Fn(&str) -> Option<String>,
    name: &'static str,
) -> Result<Option<bool>, ConfigLoadError> {
    match env(name) {
        Some(val) => match val.to_lowercase().as_str() {
            "true" | "1" | "yes" | "on" => Ok(Some(true)),
            "false" | "0" | "no" | "off" => Ok(Some(false)),
            _ => Err(ConfigLoadError::InvalidEnvironment {
                name,
                value: val,
                reason: "expected one of: true, 1, yes, on, false, 0, no, off".to_string(),
            }),
        },
        None => Ok(None),
    }
}

/// Warn if a config file containing credentials is world-readable.
///
/// On Unix, a world-readable config file (mode bits `0o004` set) allows
/// any local user to read plaintext metrics credentials.  This helper
/// logs a warning so the operator can `chmod 600` the file.
#[cfg(unix)]
fn check_config_permissions(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    match std::fs::metadata(path) {
        Ok(meta) => {
            let mode = meta.permissions().mode() & 0o777;
            if mode & 0o004 != 0 {
                tracing::warn!(
                    "Config file {} is world-readable (mode {:#05o}); \
                     other local users can read metrics credentials. \
                     Run: chmod 600 {}",
                    path.display(),
                    mode,
                    path.display()
                );
            }
        }
        Err(e) => {
            tracing::debug!("Unable to check permissions on {}: {}", path.display(), e);
        }
    }
}

impl Config {
    pub fn load() -> Result<Self, ConfigLoadError> {
        let config_path = paths::config_path();
        Self::load_from(&config_path, &|name| std::env::var(name).ok())
    }

    fn load_from(
        config_path: &std::path::Path,
        env: &impl Fn(&str) -> Option<String>,
    ) -> Result<Self, ConfigLoadError> {
        let config_file = match std::fs::read_to_string(config_path) {
            Ok(content) => {
                let parsed: ConfigFile =
                    toml::from_str(&content).map_err(|source| ConfigLoadError::Parse {
                        path: config_path.to_path_buf(),
                        source,
                    })?;

                #[cfg(unix)]
                if let Some(server) = &parsed.server
                    && server
                        .metrics
                        .as_ref()
                        .is_some_and(|m| m.username.is_some() || m.password.is_some())
                {
                    check_config_permissions(config_path);
                }

                parsed
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => ConfigFile::default(),
            Err(source) => {
                return Err(ConfigLoadError::Read {
                    path: config_path.to_path_buf(),
                    source,
                });
            }
        };

        let server = config_file.server.unwrap_or_default();

        let config = Self {
            grpc_host: env("GRPC_HOST")
                .or_else(|| server.grpc_host.clone())
                .unwrap_or_else(|| "127.0.0.1".to_string()),
            grpc_port: parse_env(env, "GRPC_PORT")?
                .or(server.grpc_port)
                .unwrap_or(50051),
            http_host: env("HTTP_HOST")
                .or_else(|| server.http_host.clone())
                .unwrap_or_else(|| "127.0.0.1".to_string()),
            http_port: parse_env(env, "HTTP_PORT")?
                .or(server.http_port)
                .unwrap_or(50050),
            db_path: env("DATABASE_URL")
                .or_else(|| server.database.as_ref().and_then(|d| d.path.clone()))
                .unwrap_or_else(|| paths::default_db_path().to_string_lossy().into_owned()),
            db_max_connections: parse_env(env, "DB_MAX_CONNECTIONS")?
                .or(server.database.as_ref().and_then(|d| d.max_connections))
                .unwrap_or(DEFAULT_DB_MAX_CONNECTIONS),
            premade_dir: env("PREMADE_DIR")
                .map(PathBuf::from)
                .or_else(|| {
                    server
                        .premade
                        .as_ref()
                        .and_then(|p| p.directory.clone())
                        .map(PathBuf::from)
                })
                .unwrap_or_else(paths::default_premade_dir),
            max_command_length: parse_env(env, "MAX_COMMAND_LENGTH")?
                .or(server.limits.as_ref().and_then(|l| l.max_command_length))
                .unwrap_or(DEFAULT_MAX_COMMAND_LENGTH),
            max_encrypted_payload_length: parse_env(env, "MAX_ENCRYPTED_PAYLOAD_LENGTH")?
                .or(server
                    .limits
                    .as_ref()
                    .and_then(|l| l.max_encrypted_payload_length))
                .unwrap_or(DEFAULT_MAX_ENCRYPTED_PAYLOAD_LENGTH),
            max_description_length: parse_env(env, "MAX_DESCRIPTION_LENGTH")?
                .or(server
                    .limits
                    .as_ref()
                    .and_then(|l| l.max_description_length))
                .unwrap_or(DEFAULT_MAX_DESCRIPTION_LENGTH),
            max_tags: parse_env(env, "MAX_TAGS")?
                .or(server.limits.as_ref().and_then(|l| l.max_tags))
                .unwrap_or(DEFAULT_MAX_TAGS),
            max_tag_length: parse_env(env, "MAX_TAG_LENGTH")?
                .or(server.limits.as_ref().and_then(|l| l.max_tag_length))
                .unwrap_or(DEFAULT_MAX_TAG_LENGTH),
            max_id_length: parse_env(env, "MAX_ID_LENGTH")?
                .or(server.limits.as_ref().and_then(|l| l.max_id_length))
                .unwrap_or(DEFAULT_MAX_ID_LENGTH),
            max_device_id_length: parse_env(env, "MAX_DEVICE_ID_LENGTH")?
                .or(server.limits.as_ref().and_then(|l| l.max_device_id_length))
                .unwrap_or(DEFAULT_MAX_DEVICE_ID_LENGTH),
            max_api_key_length: parse_env(env, "MAX_API_KEY_LENGTH")?
                .or(server.limits.as_ref().and_then(|l| l.max_api_key_length))
                .unwrap_or(DEFAULT_MAX_API_KEY_LENGTH),
            request_timeout_secs: parse_env(env, "REQUEST_TIMEOUT_SECS")?
                .or(server.limits.as_ref().and_then(|l| l.request_timeout_secs))
                .unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECS),
            grpc_max_message_size: parse_env(env, "GRPC_MAX_MESSAGE_SIZE")?
                .or(server.limits.as_ref().and_then(|l| l.grpc_max_message_size))
                .unwrap_or(DEFAULT_GRPC_MAX_MESSAGE_SIZE),
            rate_limit_per_minute: parse_env(env, "RATE_LIMIT_PER_MINUTE")?
                .or(server
                    .rate_limit
                    .as_ref()
                    .and_then(|r| r.requests_per_minute))
                .unwrap_or(DEFAULT_RATE_LIMIT_PER_MINUTE),
            register_per_minute: parse_env(env, "REGISTER_PER_MINUTE")?
                .or(server
                    .rate_limit
                    .as_ref()
                    .and_then(|r| r.register_per_minute))
                .unwrap_or(DEFAULT_REGISTER_PER_MINUTE),
            metrics_auth_failures_per_minute: parse_env(env, "METRICS_AUTH_FAILURES_PER_MINUTE")?
                .or(server
                    .rate_limit
                    .as_ref()
                    .and_then(|r| r.metrics_auth_failures_per_minute))
                .unwrap_or(DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE),
            trusted_proxies: env("TRUSTED_PROXIES")
                .map(|v| {
                    v.split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty() && s.parse::<std::net::IpAddr>().is_ok())
                        .collect()
                })
                .or_else(|| server.rate_limit.as_ref()?.trusted_proxies.clone())
                .unwrap_or_default(),
            metrics_username: env("METRICS_USERNAME")
                .or_else(|| server.metrics.as_ref().and_then(|m| m.username.clone())),
            metrics_password: env("METRICS_PASSWORD")
                .or_else(|| server.metrics.as_ref().and_then(|m| m.password.clone())),
            cors_allowed_origins: env("CORS_ALLOWED_ORIGINS")
                .or_else(|| server.cors.as_ref().and_then(|c| c.allowed_origins.clone()))
                .map(|v| {
                    v.split(',')
                        .map(str::trim)
                        .filter(|origin| !origin.is_empty())
                        .map(ToOwned::to_owned)
                        .collect()
                })
                .unwrap_or_default(),
        };

        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<(), ConfigLoadError> {
        if self.grpc_port == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "GRPC_PORT",
                value: self.grpc_port.to_string(),
                reason: "port must be nonzero".into(),
            });
        }
        if self.http_port == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "HTTP_PORT",
                value: self.http_port.to_string(),
                reason: "port must be nonzero".into(),
            });
        }
        if self.db_max_connections == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "DB_MAX_CONNECTIONS",
                value: self.db_max_connections.to_string(),
                reason: "must be at least 1".into(),
            });
        }
        if self.request_timeout_secs == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "REQUEST_TIMEOUT_SECS",
                value: self.request_timeout_secs.to_string(),
                reason: "must be at least 1".into(),
            });
        }
        if self.grpc_max_message_size == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "GRPC_MAX_MESSAGE_SIZE",
                value: self.grpc_max_message_size.to_string(),
                reason: "must be greater than 0".into(),
            });
        }
        if self.max_command_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_COMMAND_LENGTH",
                value: self.max_command_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_encrypted_payload_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_ENCRYPTED_PAYLOAD_LENGTH",
                value: self.max_encrypted_payload_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_description_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_DESCRIPTION_LENGTH",
                value: self.max_description_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_tags == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_TAGS",
                value: self.max_tags.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_tag_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_TAG_LENGTH",
                value: self.max_tag_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_id_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_ID_LENGTH",
                value: self.max_id_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_device_id_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_DEVICE_ID_LENGTH",
                value: self.max_device_id_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.max_api_key_length == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "MAX_API_KEY_LENGTH",
                value: self.max_api_key_length.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.rate_limit_per_minute == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "RATE_LIMIT_PER_MINUTE",
                value: self.rate_limit_per_minute.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        // Zero is a hard error, not "unlimited": a zero registration budget
        // makes account creation impossible, and a zero metrics-failure budget
        // makes the second failed scrape return 429 forever. Both are almost
        // certainly operator mistakes.
        if self.register_per_minute == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "REGISTER_PER_MINUTE",
                value: self.register_per_minute.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        if self.metrics_auth_failures_per_minute == 0 {
            return Err(ConfigLoadError::InvalidRange {
                name: "METRICS_AUTH_FAILURES_PER_MINUTE",
                value: self.metrics_auth_failures_per_minute.to_string(),
                reason: "must be nonzero".into(),
            });
        }
        Ok(())
    }

    pub fn ensure_config_file() {
        if let Err(e) = bootstrap::ensure_config_file() {
            tracing::warn!("{}", e);
        }
    }
}

#[derive(Clone)]
pub struct AppState {
    pub config: Config,
    pub metrics: Metrics,
    pub db: Arc<Database>,
    /// The same process-local limiter the gRPC service uses. Sharing it keeps
    /// one bounded structure (and one `MAX_ENTRIES` budget) for both listeners
    /// instead of inventing a second one for the HTTP leaf.
    pub rate_limiter: Arc<RateLimiter>,
}

pub struct SnipSyncService {
    pub db: Arc<Database>,
    pub rate_limiter: Arc<RateLimiter>,
    pub config: Config,
    pub metrics: Metrics,
    pub premade_manager: PremadeManager,
    /// Test-only: most recent `authorization` header value observed by
    /// the gRPC handlers. Used by integration tests to assert that the
    /// sync client actually sends a non-empty bearer token in metadata
    /// (catching the auth-header regression where `request.api_key` was
    /// read instead of the caller's API key).
    #[cfg(any(test, feature = "test-helpers"))]
    pub captured_auth_header: Arc<std::sync::Mutex<Option<String>>>,
    /// Test-only: optional request observer for telemetry tests.
    /// When set, `record_request` and `record_request_finished` emit
    /// sanitized events to the observer.
    #[cfg(any(test, feature = "test-helpers"))]
    pub test_observer: Option<Arc<dyn crate::test_observer::TestRequestObserver>>,
    /// Test-only: failure-injection threshold for `PushSnippets`.
    ///
    /// The value is the 1-indexed push call that must fail: once
    /// `push_fail_counter` reaches it, the push is rejected with an
    /// internal error. `u32::MAX` (the default) disables injection. This
    /// field is only read — the call counter is tracked separately in
    /// `push_fail_counter`.
    #[cfg(any(test, feature = "test-helpers"))]
    pub push_fail_after: Arc<std::sync::atomic::AtomicU32>,
    /// Test-only: internal counter for push failure injection.
    /// Starts at 0 and increments on each PushSnippets call.
    #[cfg(any(test, feature = "test-helpers"))]
    pub push_fail_counter: Arc<std::sync::atomic::AtomicU32>,
}

impl SnipSyncService {
    pub fn record_request(&self, method: &str) {
        self.metrics
            .requests_total
            .with_label_values(&[method])
            .inc();
        tracing::trace!("Request: {}", method);
        #[cfg(feature = "test-helpers")]
        if let Some(ref obs) = self.test_observer {
            use crate::test_observer::{RequestStarted, now_millis, operation_name_for_method};
            let sequence = obs.allocate_sequence();
            let concurrent = obs.current_concurrent();
            obs.request_started(RequestStarted {
                sequence,
                started_at_unix_ms: now_millis(),
                method: method.to_string(),
                operation: operation_name_for_method(method).to_string(),
                authenticated_user_id: None,
                authenticated_device_id: None,
                target_library_id: None,
                request_revision: None,
                payload_len: 0,
                payload_sha256: String::new(),
                payload_contains_plaintext_sentinel: false,
                concurrent_at_start: concurrent,
            });
        }
    }

    #[cfg_attr(not(feature = "test-helpers"), allow(unused_variables))]
    pub fn record_request_finished(&self, method: &str, success: bool) {
        #[cfg(feature = "test-helpers")]
        if let Some(ref obs) = self.test_observer {
            use crate::test_observer::RequestFinished;
            let sequence = obs.last_started_sequence_for_method(method);
            obs.request_finished(RequestFinished {
                sequence,
                finished_at_unix_ms: crate::test_observer::now_millis(),
                success,
                response_revision: None,
            });
        }
    }

    /// Update the last started request's authenticated IDs.
    ///
    /// Called after authentication resolves the user and device IDs.
    /// Only active with `test-helpers` feature.
    #[cfg_attr(not(feature = "test-helpers"), allow(unused_variables))]
    pub fn update_request_ids(
        &self,
        method: &str,
        user_id: Option<String>,
        device_id: Option<String>,
        library_id: Option<String>,
    ) {
        #[cfg(feature = "test-helpers")]
        if let Some(ref obs) = self.test_observer {
            obs.update_ids_for_last_method(method, user_id, device_id, library_id);
        }
    }

    pub fn record_request_duration(&self, method: &str, start: std::time::Instant) {
        let duration = start.elapsed().as_secs_f64();
        self.metrics
            .request_duration_seconds
            .with_label_values(&[method])
            .observe(duration);
        tracing::debug!("Request {} completed in {:.3}s", method, duration);
    }

    pub fn record_rate_limit(&self) {
        self.metrics.rate_limit_hits.inc();
    }

    pub fn record_auth_failure(&self) {
        self.metrics.auth_failures.inc();
    }

    /// Record a database failure (for example an upsert that failed inside a
    /// write transaction). Database failures are infrastructure errors, not
    /// content-level skips, so they are counted separately from the
    /// `skipped_count` a client sees.
    pub fn record_db_error(&self) {
        self.metrics.db_errors_total.inc();
    }

    pub fn record_sync(&self, direction: &str) {
        self.metrics
            .sync_operations_total
            .with_label_values(&[direction])
            .inc();
    }

    pub fn record_library_op(&self, operation: &str) {
        self.metrics
            .library_operations_total
            .with_label_values(&[operation])
            .inc();
    }

    fn request_api_key<T>(&self, request: &Request<T>, body_api_key: &str) -> String {
        let api_key = extract_api_key(request, body_api_key);
        #[cfg(any(test, feature = "test-helpers"))]
        self.capture_test_auth_header(&api_key);
        api_key
    }

    #[cfg(any(test, feature = "test-helpers"))]
    fn capture_test_auth_header(&self, api_key: &str) {
        if !api_key.is_empty() {
            let mut slot = self
                .captured_auth_header
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            if slot.is_none() {
                *slot = Some(format!("Bearer {api_key}"));
            }
        }
    }

    /// Derive the rate-limit bucket identity for an inbound request.
    ///
    /// Deliberately **not** the API key. The key is request-supplied and is
    /// not validated until `db.get_user_by_api_key` runs, so keying the limiter
    /// on it meant every distinct attacker-chosen key got its own budget of
    /// `rate_limit_per_minute` and the limiter imposed no aggregate request
    /// ceiling on the authenticated gRPC surface. The peer address is bounded
    /// by the number of real callers, and `x-forwarded-for` is honoured only
    /// from a configured trusted proxy.
    ///
    /// Tonic inserts a [`tonic::transport::server::TcpConnectInfo`] into the
    /// request extensions for every TCP connection; the peer address is read
    /// from there. A bare [`std::net::SocketAddr`] is never inserted, so
    /// looking for one yields `None` for every request and collapses every
    /// caller onto a single global bucket.
    fn peer_rate_limit_key<T>(&self, request: &Request<T>) -> String {
        let peer_ip = request
            .extensions()
            .get::<tonic::transport::server::TcpConnectInfo>()
            .and_then(|info| info.remote_addr())
            .map(|addr| addr.ip().to_string());

        match peer_ip {
            Some(ref ip) if self.config.trusted_proxies.contains(ip) => request
                .metadata()
                .get("x-forwarded-for")
                .and_then(|v| v.to_str().ok())
                .and_then(|header| header.split(',').next())
                .map(|s| strip_port(s.trim()))
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| ip.clone()),
            Some(ip) => ip,
            None => "unknown".to_string(),
        }
    }

    pub async fn authenticate_and_rate_limit(
        &self,
        api_key: &str,
        rate_limit_key: &str,
    ) -> Result<String, Status> {
        self.authenticate_and_rate_limit_with_duration(api_key, rate_limit_key, None)
            .await
    }

    /// Like `authenticate_and_rate_limit`, but records request duration on
    /// failure so the histogram captures latency for error responses.
    ///
    /// `rate_limit_key` must come from [`Self::peer_rate_limit_key`].
    pub async fn authenticate_and_rate_limit_with_duration(
        &self,
        api_key: &str,
        rate_limit_key: &str,
        start: Option<std::time::Instant>,
    ) -> Result<String, Status> {
        if api_key.is_empty() {
            if let Some(s) = start {
                self.record_request_duration("auth", s);
            }
            return Err(Status::unauthenticated("API key is required"));
        }
        if api_key.len() > self.config.max_api_key_length {
            if let Some(s) = start {
                self.record_request_duration("auth", s);
            }
            return Err(Status::invalid_argument(format!(
                "API key exceeds maximum length of {} bytes",
                self.config.max_api_key_length
            )));
        }

        // Pre-authentication budget. Its only job is to bound the cost of the
        // API-key lookup below, so it is deliberately far larger than the
        // per-caller budget: an unauthenticated caller must never be able to
        // exhaust the budget that legitimate callers spend.
        let pre_auth_key = format!("pre-auth:{rate_limit_key}");
        let pre_auth_limit = self
            .config
            .rate_limit_per_minute
            .saturating_mul(PRE_AUTH_RATE_LIMIT_MULTIPLIER) as usize;
        if !self
            .rate_limiter
            .allow(&pre_auth_key, pre_auth_limit, Duration::from_secs(60))
            .await
        {
            self.record_rate_limit();
            if let Some(s) = start {
                self.record_request_duration("auth", s);
            }
            return Err(Status::resource_exhausted("Rate limit exceeded"));
        }

        let user_id = self
            .db
            .get_user_by_api_key(api_key)
            .await
            .map_err(|_| {
                if let Some(s) = start {
                    self.record_request_duration("auth", s);
                }
                Status::internal("Internal error")
            })?
            .ok_or_else(|| {
                self.record_auth_failure();
                if let Some(s) = start {
                    self.record_request_duration("auth", s);
                }
                Status::unauthenticated("Invalid API key")
            })?;

        // Authenticated budget. Only a request that presented a valid API key
        // can spend it, so an invalid key cannot lock out a legitimate caller
        // that shares the same peer address.
        if !self
            .rate_limiter
            .allow(
                rate_limit_key,
                self.config.rate_limit_per_minute as usize,
                Duration::from_secs(60),
            )
            .await
        {
            self.record_rate_limit();
            if let Some(s) = start {
                self.record_request_duration("auth", s);
            }
            return Err(Status::resource_exhausted("Rate limit exceeded"));
        }

        Ok(user_id)
    }

    pub fn validate_snippet(&self, snippet: &ProtoSnippet) -> Result<(), Status> {
        if snippet.id.is_empty() {
            return Err(Status::invalid_argument("Snippet ID is required"));
        }
        if snippet.id.len() > self.config.max_id_length {
            return Err(Status::invalid_argument(format!(
                "Snippet ID exceeds maximum length of {} bytes",
                self.config.max_id_length
            )));
        }

        if snippet.device_id.is_empty() {
            return Err(Status::invalid_argument("Device ID is required"));
        }
        if snippet.device_id.len() > self.config.max_device_id_length {
            return Err(Status::invalid_argument(format!(
                "Device ID exceeds maximum length of {} bytes",
                self.config.max_device_id_length
            )));
        }

        if !snippet.encrypted && snippet.command.len() > self.config.max_command_length {
            return Err(Status::invalid_argument(format!(
                "Command exceeds maximum length of {} bytes",
                self.config.max_command_length
            )));
        }

        if !snippet.encrypted && snippet.command.trim().is_empty() {
            return Err(Status::invalid_argument("Snippet command is required"));
        }

        if snippet.encrypted && snippet.command.len() > self.config.max_encrypted_payload_length {
            return Err(Status::invalid_argument(format!(
                "Encrypted payload exceeds maximum length of {} bytes",
                self.config.max_encrypted_payload_length
            )));
        }

        if snippet.encrypted && (snippet.command.is_empty() || snippet.command.trim().is_empty()) {
            return Err(Status::invalid_argument(
                "Encrypted snippet payload is required",
            ));
        }

        if snippet.description.len() > self.config.max_description_length {
            return Err(Status::invalid_argument(format!(
                "Description exceeds maximum length of {} bytes",
                self.config.max_description_length
            )));
        }

        if snippet.tags.len() > self.config.max_tags {
            return Err(Status::invalid_argument(format!(
                "Too many tags (max {})",
                self.config.max_tags
            )));
        }

        for tag in &snippet.tags {
            if tag.len() > self.config.max_tag_length {
                return Err(Status::invalid_argument(format!(
                    "Tag '{}' exceeds maximum length of {} bytes",
                    tag, self.config.max_tag_length
                )));
            }
        }

        // Sample server time once to avoid micro-boundary disagreement
        // between consecutive timestamp checks.
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let tolerance = 300; // 5 minutes

        if snippet.updated_at > now + tolerance {
            let skew = snippet.updated_at - now;
            return Err(Status::invalid_argument(format!(
                "CLOCK_SKEW: updated_at is {} seconds ahead of server time; \
                 synchronize the client clock and retry",
                skew
            )));
        }
        if snippet.created_at > now + tolerance {
            let skew = snippet.created_at - now;
            return Err(Status::invalid_argument(format!(
                "CLOCK_SKEW: created_at is {} seconds ahead of server time; \
                 synchronize the client clock and retry",
                skew
            )));
        }
        if snippet.created_at < 0 || snippet.updated_at < 0 {
            return Err(Status::invalid_argument("Timestamps must be non-negative"));
        }
        // Lower clock-skew bound: a zero timestamp means the client clock was
        // unset (epoch). Such rows would be invisible to every delta query
        // (the cursor filter is inclusive, so a zero timestamp never reaches
        // a client whose cursor is positive), so reject them instead of
        // storing them.
        if snippet.created_at == 0 || snippet.updated_at == 0 {
            return Err(Status::invalid_argument(
                "Timestamps must be positive; zero indicates an unset client clock",
            ));
        }
        if snippet.created_at > snippet.updated_at {
            return Err(Status::invalid_argument(
                "created_at must not be greater than updated_at",
            ));
        }

        Ok(())
    }
}

#[tonic::async_trait]
impl SnippetSync for SnipSyncService {
    async fn health(
        &self,
        _request: Request<HealthRequest>,
    ) -> Result<Response<HealthResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("health");
        tracing::debug!(request_id = %request_id, "Health check");
        let healthy = self.db.ping().await.is_ok();
        self.record_request_duration("health", start);
        self.record_request_finished("health", healthy);
        Ok(Response::new(HealthResponse {
            healthy,
            version: env!("CARGO_PKG_VERSION").to_string(),
        }))
    }

    async fn register(
        &self,
        request: Request<RegisterRequest>,
    ) -> Result<Response<RegisterResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("register");
        tracing::info!(request_id = %request_id, "Register request");

        // Use peer IP address for rate limiting (device_id is client-controlled).
        // Tonic populates request.extensions() with a `TcpConnectInfo` holding
        // the peer socket address.
        let rate_limit_key = self.peer_rate_limit_key(&request);

        // Registration is unauthenticated, so it gets its own bucket: it must
        // not be able to spend the budget that authenticated callers use.
        let register_limit_key = format!("register:{rate_limit_key}");
        if !self
            .rate_limiter
            .allow(
                &register_limit_key,
                self.config.rate_limit_per_minute as usize,
                Duration::from_secs(60),
            )
            .await
        {
            self.record_rate_limit();
            self.record_request_duration("register", start);
            self.record_request_finished("register", false);
            return Err(Status::resource_exhausted(
                "Rate limit exceeded for registration",
            ));
        }

        // Per-peer budgets do not bound a caller that rotates addresses, and
        // every registration inserts a user plus a default library. The global
        // budget is deliberately a separate key so a legitimate caller is not
        // charged for an attacker's traffic on another address: it caps total
        // account creation, not per-caller fairness.
        if !self
            .rate_limiter
            .allow(
                "register-global",
                self.config.register_per_minute as usize,
                Duration::from_secs(60),
            )
            .await
        {
            self.record_rate_limit();
            self.record_request_duration("register", start);
            self.record_request_finished("register", false);
            tracing::warn!(
                request_id = %request_id,
                "Rejected registration: global per-minute ceiling reached"
            );
            return Err(Status::resource_exhausted(
                "Registration is temporarily unavailable: global account-creation limit reached",
            ));
        }

        let _req = request.into_inner();

        let api_key = uuid::Uuid::new_v4().to_string();

        match self.db.create_user(&api_key).await {
            Ok(device_id) => {
                if uuid::Uuid::parse_str(&device_id).is_err() {
                    tracing::error!(
                        request_id = %request_id,
                        "Generated device_id is not a valid UUID: {}",
                        device_id
                    );
                    self.record_request_duration("register", start);
                    self.record_request_finished("register", false);
                    return Err(Status::internal(
                        "Internal error: invalid device ID generated",
                    ));
                }
                tracing::info!(
                    request_id = %request_id,
                    device_id = %device_id,
                    "Created new user"
                );
                self.record_request_duration("register", start);
                self.record_request_finished("register", true);
                Ok(Response::new(RegisterResponse {
                    success: true,
                    api_key,
                    message: "Account created successfully".to_string(),
                    device_id,
                }))
            }
            Err(e) => {
                tracing::error!(request_id = %request_id, "Failed to create user: {}", e);
                self.record_request_duration("register", start);
                self.record_request_finished("register", false);
                Err(Status::internal("Internal error"))
            }
        }
    }

    async fn get_snippets(
        &self,
        request: Request<GetSnippetsRequest>,
    ) -> Result<Response<SnippetList>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("get_snippets");
        tracing::info!(request_id = %request_id, "GetSnippets request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("get_snippets", false);
            })?;

        let library_id = if req.library_id.is_empty() {
            self.db.get_default_library(&user_id).await.map_err(|e| {
                self.record_request_duration("get_snippets", start);
                self.record_request_finished("get_snippets", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?
        } else {
            if !self
                .db
                .verify_library_ownership(&user_id, &req.library_id)
                .await
                .map_err(|e| {
                    self.record_request_duration("get_snippets", start);
                    self.record_request_finished("get_snippets", false);
                    tracing::error!("Internal error: {}", e);
                    Status::internal("Internal error")
                })?
            {
                tracing::warn!(
                    "User {} attempted to access library {} without ownership",
                    user_id,
                    req.library_id
                );
                self.record_request_duration("get_snippets", start);
                self.record_request_finished("get_snippets", false);
                return Err(Status::not_found("Library not found"));
            }
            req.library_id
        };

        // Update observer with authenticated identity after resolution.
        self.update_request_ids(
            "get_snippets",
            Some(user_id.clone()),
            None,
            Some(library_id.clone()),
        );

        let limit = if req.limit > 0 {
            req.limit.clamp(1, MAX_REQUEST_LIMIT)
        } else {
            100
        };
        let offset = if req.offset > 0 { req.offset } else { 0 };

        let (snippets, total) = self
            .db
            .get_snippets(&user_id, &library_id, req.since, limit, offset, false)
            .await
            .map_err(|e| {
                self.record_request_duration("get_snippets", start);
                self.record_request_finished("get_snippets", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?;

        let page_len = snippets.len() as i32;
        let has_more_by_rows = offset.saturating_add(page_len) < total;

        let mut proto_snippets: Vec<ProtoSnippet> = snippets
            .into_iter()
            .map(|s| ProtoSnippet {
                id: s.id,
                description: s.description,
                command: s.command,
                tags: s.tags,
                created_at: s.created_at,
                updated_at: s.updated_at,
                device_id: s.device_id,
                deleted: s.deleted,
                encrypted: s.encrypted,
            })
            .collect();

        let truncated = fit_page_to_byte_ceiling(
            &mut proto_snippets,
            page_byte_ceiling(self.config.grpc_max_message_size as usize, 0),
        );
        let has_more = has_more_by_rows || truncated;

        self.record_request_duration("get_snippets", start);

        let result = Ok(Response::new(SnippetList {
            snippets: proto_snippets,
            total_count: total,
            has_more,
        }));
        self.record_request_finished("get_snippets", result.is_ok());
        result
    }

    async fn push_snippets(
        &self,
        request: Request<PushSnippetsRequest>,
    ) -> Result<Response<PushSnippetsResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("push_snippets");
        tracing::info!(request_id = %request_id, "PushSnippets request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("push_snippets", false);
            })?;

        let library_id = if req.library_id.is_empty() {
            self.db.get_default_library(&user_id).await.map_err(|e| {
                self.record_request_duration("push_snippets", start);
                self.record_request_finished("push_snippets", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?
        } else {
            if !self
                .db
                .verify_library_ownership(&user_id, &req.library_id)
                .await
                .map_err(|e| {
                    self.record_request_duration("push_snippets", start);
                    self.record_request_finished("push_snippets", false);
                    tracing::error!("Internal error: {}", e);
                    Status::internal("Internal error")
                })?
            {
                tracing::warn!(
                    "User {} attempted to push to library {} without ownership",
                    user_id,
                    req.library_id
                );
                self.record_request_duration("push_snippets", start);
                self.record_request_finished("push_snippets", false);
                return Err(Status::not_found("Library not found"));
            }
            req.library_id
        };

        // Update observer with authenticated identity after resolution.
        self.update_request_ids(
            "push_snippets",
            Some(user_id.clone()),
            req.snippets.first().map(|s| s.device_id.clone()),
            Some(library_id.clone()),
        );

        if req.snippets.len() > DEFAULT_MAX_SYNC_SNIPPETS {
            self.record_request_duration("push_snippets", start);
            self.record_request_finished("push_snippets", false);
            return Err(Status::invalid_argument(format!(
                "Too many snippets in push request (max {}), got {}",
                DEFAULT_MAX_SYNC_SNIPPETS,
                req.snippets.len()
            )));
        }

        // Test-only failure injection: fail on the Nth PushSnippets call.
        // push_fail_after stores the 1-indexed failure point. A value of
        // u32::MAX means "disabled" (never fail). The internal counter
        // starts at 0 and increments on each push; when it reaches the
        // threshold the push is rejected.
        #[cfg(feature = "test-helpers")]
        {
            let threshold = self
                .push_fail_after
                .load(std::sync::atomic::Ordering::SeqCst);
            if threshold != u32::MAX {
                let count = self
                    .push_fail_counter
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
                    + 1;
                if count >= threshold {
                    self.record_request_duration("push_snippets", start);
                    self.record_request_finished("push_snippets", false);
                    return Err(Status::internal("test-injected push failure"));
                }
            }
        }

        let mut accepted = 0;
        let mut rejected = 0;

        // The write transaction deliberately spans every upsert of the
        // request: a push is all-or-nothing, and a failed upsert rolls the
        // whole batch back (see the error arm below). Committing in batches
        // would shorten the SQLite write-lock window, but it would also turn
        // a mid-batch failure into a partially applied upload — a contract
        // change that needs its own design decision, not a silent tweak.
        let mut tx = self.db.pool().begin().await.map_err(|e| {
            self.record_request_duration("push_snippets", start);
            self.record_request_finished("push_snippets", false);
            tracing::error!(request_id = %request_id, "Failed to begin transaction: {}", e);
            Status::internal("Internal error")
        })?;

        for snippet in req.snippets {
            if let Err(e) = self.validate_snippet(&snippet) {
                rejected += 1;
                tracing::warn!(request_id = %request_id, snippet_id = %snippet.id, reason = %e, "Snippet validation failed");
                continue;
            }

            let db_snippet = db::Snippet {
                id: snippet.id.clone(),
                description: snippet.description,
                command: snippet.command,
                tags: snippet.tags,
                created_at: snippet.created_at,
                updated_at: snippet.updated_at,
                device_id: snippet.device_id,
                deleted: snippet.deleted,
                encrypted: snippet.encrypted,
            };

            match self
                .db
                .upsert_snippet_in_tx(&mut tx, &db_snippet, &user_id, &library_id)
                .await
            {
                Ok(db::UpsertOutcome::Written | db::UpsertOutcome::Stale) => accepted += 1,
                Ok(db::UpsertOutcome::ForeignScope) => {
                    // `snippets.id` is a global primary key, so this snippet
                    // cannot be stored alongside the identically-identified one
                    // in another user or library. Reporting it as accepted
                    // would tell the client the upload succeeded while the
                    // snippet is silently absent from the server.
                    rejected += 1;
                    tracing::error!(
                        request_id = %request_id,
                        snippet_id = %snippet.id,
                        user_id = %user_id,
                        library_id = %library_id,
                        "Snippet rejected: id already exists under a different user or library"
                    );
                }
                Err(e) => {
                    tracing::warn!(
                        request_id = %request_id,
                        snippet_id = %snippet.id,
                        reason = %e,
                        "Snippet upsert failed"
                    );
                    self.record_db_error();
                    // Rollback failure must not leak a dirty connection back
                    // into the pool. sqlx 0.9 guarantees this on release: a
                    // returned PoolConnection is pinged, which flushes any
                    // queued/failed ROLLBACK work, and a connection that
                    // fails the ping is hard-closed instead of pooled
                    // (sqlx-core `pool/connection.rs::return_to_pool`).
                    if let Err(rollback_error) = tx.rollback().await {
                        tracing::error!(
                            request_id = %request_id,
                            error = %rollback_error,
                            "Failed to roll back push transaction"
                        );
                    }
                    self.record_request_duration("push_snippets", start);
                    self.record_request_finished("push_snippets", false);
                    return Err(Status::internal("Internal error"));
                }
            }
        }

        tx.commit().await.map_err(|e| {
            self.record_request_duration("push_snippets", start);
            self.record_request_finished("push_snippets", false);
            tracing::error!(request_id = %request_id, "Failed to commit transaction: {}", e);
            Status::internal("Internal error")
        })?;

        self.record_request_duration("push_snippets", start);

        let result = Ok(Response::new(PushSnippetsResponse {
            success: rejected == 0,
            message: format!("Accepted {}, rejected {}", accepted, rejected),
            accepted_count: accepted,
            rejected_count: rejected,
        }));
        self.record_request_finished("push_snippets", result.is_ok());
        result
    }

    async fn sync(&self, request: Request<SyncRequest>) -> Result<Response<SyncResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("sync");
        tracing::info!(request_id = %request_id, "Sync request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("sync", false);
            })?;

        if req.local_snippets.len() > DEFAULT_MAX_SYNC_SNIPPETS {
            self.record_request_duration("sync", start);
            self.record_request_finished("sync", false);
            return Err(Status::invalid_argument(format!(
                "Too many snippets in sync request (max {}), got {}",
                DEFAULT_MAX_SYNC_SNIPPETS,
                req.local_snippets.len()
            )));
        }

        self.record_sync("bidirectional");

        let library_id = if req.library_id.is_empty() {
            self.db.get_default_library(&user_id).await.map_err(|e| {
                self.record_request_duration("sync", start);
                self.record_request_finished("sync", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?
        } else {
            if !self
                .db
                .verify_library_ownership(&user_id, &req.library_id)
                .await
                .map_err(|e| {
                    self.record_request_duration("sync", start);
                    self.record_request_finished("sync", false);
                    tracing::error!("Internal error: {}", e);
                    Status::internal("Internal error")
                })?
            {
                tracing::warn!(
                    "User {} attempted to sync with library {} without ownership",
                    user_id,
                    req.library_id
                );
                self.record_request_duration("sync", start);
                self.record_request_finished("sync", false);
                return Err(Status::not_found("Library not found"));
            }
            req.library_id
        };

        // Update observer with authenticated identity after resolution.
        self.update_request_ids(
            "sync",
            Some(user_id.clone()),
            req.local_snippets.first().map(|s| s.device_id.clone()),
            Some(library_id.clone()),
        );

        let mut skipped_ids = Vec::new();

        // The write transaction deliberately spans every upsert of the
        // request, for the same reason as `push_snippets`: a sync is
        // all-or-nothing and a failed upsert rolls the whole batch back.
        // Batching the commits would shorten the SQLite write-lock window
        // but would turn a mid-batch failure into a partially applied
        // upload, which needs its own design decision.
        let mut tx = self.db.pool().begin().await.map_err(|e| {
            self.record_request_duration("sync", start);
            self.record_request_finished("sync", false);
            tracing::error!(request_id = %request_id, "Failed to begin transaction: {}", e);
            Status::internal("Internal error")
        })?;

        for snippet in &req.local_snippets {
            if let Err(e) = self.validate_snippet(snippet) {
                tracing::warn!(
                    request_id = %request_id,
                    snippet_id = %snippet.id,
                    reason = %e,
                    "Snippet skipped: validation failed"
                );
                skipped_ids.push(snippet.id.clone());
                continue;
            }

            let db_snippet = db::Snippet {
                id: snippet.id.clone(),
                description: snippet.description.clone(),
                command: snippet.command.clone(),
                tags: snippet.tags.clone(),
                created_at: snippet.created_at,
                updated_at: snippet.updated_at,
                device_id: snippet.device_id.clone(),
                deleted: snippet.deleted,
                encrypted: snippet.encrypted,
            };

            match self
                .db
                .upsert_snippet_in_tx(&mut tx, &db_snippet, &user_id, &library_id)
                .await
            {
                Ok(db::UpsertOutcome::Written | db::UpsertOutcome::Stale) => {}
                Ok(db::UpsertOutcome::ForeignScope) => {
                    // See `push_snippets`: the global primary key makes this
                    // write impossible. Report it in `skipped_ids` so the
                    // client sees a partial failure instead of a clean sync.
                    tracing::error!(
                        request_id = %request_id,
                        snippet_id = %snippet.id,
                        user_id = %user_id,
                        library_id = %library_id,
                        "Snippet skipped: id already exists under a different user or library"
                    );
                    skipped_ids.push(snippet.id.clone());
                }
                Err(e) => {
                    // A database error is an infrastructure failure, not a
                    // content-level skip. Reporting it as a skip would tell
                    // the client the sync succeeded while the snippet was
                    // never stored. Roll the transaction back and answer
                    // with an internal error so the client retries.
                    tracing::error!(
                        request_id = %request_id,
                        snippet_id = %snippet.id,
                        reason = %e,
                        "Snippet upsert failed: rolling back the sync transaction"
                    );
                    self.record_db_error();
                    // Rollback failure must not leak a dirty connection back
                    // into the pool (sqlx hard-closes a connection whose
                    // rollback cannot be flushed).
                    if let Err(rollback_error) = tx.rollback().await {
                        tracing::error!(
                            request_id = %request_id,
                            error = %rollback_error,
                            "Failed to roll back sync transaction"
                        );
                    }
                    self.record_request_duration("sync", start);
                    self.record_request_finished("sync", false);
                    return Err(Status::internal("Internal error"));
                }
            }
        }

        tx.commit().await.map_err(|e| {
            self.record_request_duration("sync", start);
            self.record_request_finished("sync", false);
            tracing::error!(request_id = %request_id, "Failed to commit transaction: {}", e);
            Status::internal("Internal error")
        })?;

        let limit = if req.limit > 0 {
            req.limit.clamp(1, MAX_REQUEST_LIMIT)
        } else {
            1000
        };

        let offset = if req.offset > 0 { req.offset } else { 0 };

        // The sequence cursor is the exact delta cursor; the timestamp cursor
        // stays the filter for clients that send no sequence cursor. A
        // non-zero sequence in the request is the whole negotiation: there is
        // no separate round trip.
        let sequence_cursor = req.last_sync_sequence;
        let cursor = if sequence_cursor != 0 {
            db::DeltaCursor::Sequence(sequence_cursor)
        } else {
            db::DeltaCursor::Timestamp(req.last_sync_timestamp)
        };

        // One page plus a `LIMIT limit + 1` probe row: `has_more` is derived
        // from the rows themselves, so the common single-page sync no longer
        // pays for a second `COUNT(*)` scan over the same range. `total`
        // keeps its exact meaning (see `Database::get_snippets_page`).
        let page = self
            .db
            .get_snippets_page(&user_id, &library_id, cursor, limit, offset, true)
            .await
            .map_err(|e| {
                self.record_request_duration("sync", start);
                self.record_request_finished("sync", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?;

        let total = page.total;
        let has_more_by_rows = page.has_more;

        let mut proto_snippets: Vec<ProtoSnippet> = page
            .snippets
            .into_iter()
            .map(|s| ProtoSnippet {
                id: s.id,
                description: s.description,
                command: s.command,
                tags: s.tags,
                created_at: s.created_at,
                updated_at: s.updated_at,
                device_id: s.device_id,
                deleted: s.deleted,
                encrypted: s.encrypted,
            })
            .collect();

        // Bound the page by encoded bytes before deciding `has_more`: the
        // timestamp watermark below must be withheld whenever rows remain to
        // be fetched, including rows dropped here for size.
        let skipped_bytes: usize = skipped_ids.iter().map(|id| id.len() + 8).sum();
        let truncated = fit_page_to_byte_ceiling(
            &mut proto_snippets,
            page_byte_ceiling(self.config.grpc_max_message_size as usize, skipped_bytes),
        );
        let has_more = has_more_by_rows || truncated;

        let timestamp = if has_more {
            // Don't advance timestamp when paginating — client needs to fetch remaining pages
            req.last_sync_timestamp
        } else {
            self.db
                .get_latest_timestamp(&user_id, &library_id)
                .await
                .map_err(|e| {
                    self.record_request_duration("sync", start);
                    self.record_request_finished("sync", false);
                    tracing::error!("Internal error: {}", e);
                    Status::internal("Internal error")
                })?
        };

        // The sequence watermark is the server's answer to "which cursor am I
        // serving?". It is answered in exactly two cases:
        //
        // - the request carried a sequence cursor (the exact path), and
        // - the request carried no cursor at all (the bootstrap full sync),
        //   because that request delivers the complete library, so its
        //   watermark is adoptable by the client.
        //
        // A timestamp-only delta is answered with zero: a delta does not
        // deliver the library's whole history, so the client cannot adopt the
        // watermark without skipping rows it never received. Like the
        // timestamp, the sequence does not advance while paginating.
        //
        // A zero watermark is not reported as zero: in the protocol zero
        // means "no sequence", which a client cannot tell apart from a
        // server that does not serve one. The inclusive `sequence >=` filter
        // makes the reported position safe — a library that has issued
        // nothing yet reports the position before its first row, so that row
        // is still delivered when it appears.
        let sequence = if has_more {
            sequence_cursor
        } else if sequence_cursor != 0 || req.last_sync_timestamp == 0 {
            self.db
                .get_latest_sequence(&user_id, &library_id)
                .await
                .map_err(|e| {
                    self.record_request_duration("sync", start);
                    self.record_request_finished("sync", false);
                    tracing::error!("Internal error: {}", e);
                    Status::internal("Internal error")
                })?
                .max(1)
        } else {
            0
        };

        let skipped_count = skipped_ids.len() as i32;

        tracing::info!(
            request_id = %request_id,
            snippets_synced = proto_snippets.len(),
            skipped_count = skipped_count,
            has_more = has_more,
            "Sync completed"
        );

        self.record_request_duration("sync", start);

        let result = Ok(Response::new(SyncResponse {
            success: true,
            message: if skipped_count > 0 {
                format!("Sync completed, {} snippets skipped", skipped_count)
            } else {
                "Sync completed".to_string()
            },
            snippets: proto_snippets,
            server_timestamp: timestamp,
            server_sequence: sequence,
            skipped_count,
            skipped_ids,
            has_more,
            total_count: total,
        }));
        self.record_request_finished("sync", result.is_ok());
        result
    }

    async fn create_library(
        &self,
        request: Request<CreateLibraryRequest>,
    ) -> Result<Response<CreateLibraryResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("create_library");
        self.record_library_op("create");
        tracing::info!(request_id = %request_id, "CreateLibrary request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("create_library", false);
            })?;

        let result = match self.db.create_library(&user_id, &req.name).await {
            Ok(lib_id) => {
                tracing::info!("Created library '{}' for user {}", req.name, user_id);
                self.record_request_duration("create_library", start);
                Ok(Response::new(CreateLibraryResponse {
                    success: true,
                    library_id: lib_id,
                    message: format!("Library '{}' created successfully", req.name),
                }))
            }
            Err(db::DbError::Conflict(msg)) => {
                self.record_request_duration("create_library", start);
                Err(Status::already_exists(msg))
            }
            Err(db::DbError::Validation(msg)) => {
                self.record_request_duration("create_library", start);
                Err(Status::invalid_argument(msg))
            }
            Err(db::DbError::NotFound(msg)) => {
                self.record_request_duration("create_library", start);
                Err(Status::invalid_argument(msg))
            }
            Err(db::DbError::Internal(msg)) => {
                tracing::error!("Internal error creating library: {}", msg);
                self.record_request_duration("create_library", start);
                Err(Status::internal("Internal error"))
            }
            Err(db::DbError::Database(e)) => {
                tracing::error!("Database error creating library: {}", e);
                self.record_request_duration("create_library", start);
                Err(Status::internal("Internal error"))
            }
        };
        self.record_request_finished("create_library", result.is_ok());
        result
    }

    async fn list_libraries(
        &self,
        request: Request<ListLibrariesRequest>,
    ) -> Result<Response<ListLibrariesResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("list_libraries");
        self.record_library_op("list");
        tracing::info!(request_id = %request_id, "ListLibraries request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("list_libraries", false);
            })?;

        let limit = if req.limit > 0 {
            req.limit.clamp(1, MAX_REQUEST_LIMIT)
        } else {
            50
        };
        let offset = if req.offset > 0 { req.offset } else { 0 };

        let (libraries, total) = self
            .db
            .list_libraries(&user_id, limit, offset)
            .await
            .map_err(|e| {
                self.record_request_duration("list_libraries", start);
                self.record_request_finished("list_libraries", false);
                tracing::error!("Internal error: {}", e);
                Status::internal("Internal error")
            })?;

        let has_more = offset.saturating_add(libraries.len() as i32) < total;

        let proto_libraries: Vec<Library> = libraries
            .into_iter()
            .map(|l| Library {
                id: l.id,
                name: l.name,
                created_at: l.created_at,
                snippet_count: l.snippet_count,
            })
            .collect();

        self.record_request_duration("list_libraries", start);

        let result = Ok(Response::new(ListLibrariesResponse {
            libraries: proto_libraries,
            total_count: total,
            has_more,
        }));
        self.record_request_finished("list_libraries", result.is_ok());
        result
    }

    async fn delete_library(
        &self,
        request: Request<DeleteLibraryRequest>,
    ) -> Result<Response<DeleteLibraryResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("delete_library");
        self.record_library_op("delete");
        tracing::info!(request_id = %request_id, "DeleteLibrary request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("delete_library", false);
            })?;

        // Prevent deleting default library — resolve the actual UUID, not
        // the literal string "default" which is just the library name.
        if req.library_id.is_empty() || req.library_id == "default" {
            self.record_request_duration("delete_library", start);
            self.record_request_finished("delete_library", false);
            return Err(Status::invalid_argument("Cannot delete default library"));
        }
        if let Ok(default_id) = self.db.get_default_library(&user_id).await
            && req.library_id == default_id
        {
            self.record_request_duration("delete_library", start);
            self.record_request_finished("delete_library", false);
            return Err(Status::invalid_argument("Cannot delete default library"));
        }

        let result = match self.db.delete_library(&user_id, &req.library_id).await {
            Ok(_) => {
                tracing::info!("Deleted library {} for user {}", req.library_id, user_id);
                Ok(Response::new(DeleteLibraryResponse {
                    success: true,
                    message: "Library deleted successfully".to_string(),
                }))
            }
            Err(db::DbError::NotFound(msg)) => Err(Status::not_found(msg)),
            Err(db::DbError::Conflict(msg)) => Err(Status::failed_precondition(msg)),
            Err(db::DbError::Validation(msg)) => Err(Status::invalid_argument(msg)),
            Err(db::DbError::Internal(msg)) => {
                tracing::error!("Internal error deleting library: {}", msg);
                Err(Status::internal("Internal error"))
            }
            Err(db::DbError::Database(e)) => {
                tracing::error!("Failed to delete library: {}", e);
                Err(Status::internal("Internal error"))
            }
        };
        self.record_request_duration("delete_library", start);
        self.record_request_finished("delete_library", result.is_ok());
        result
    }

    async fn list_premade_libraries(
        &self,
        request: Request<ListPremadeLibrariesRequest>,
    ) -> Result<Response<ListPremadeLibrariesResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("list_premade_libraries");
        tracing::info!(request_id = %request_id, "ListPremadeLibraries request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let _req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("list_premade_libraries", false);
            })?;

        let libraries = self.premade_manager.list();

        let proto_libraries: Vec<ProtoPremadeLibrary> = libraries
            .into_iter()
            .map(|l| ProtoPremadeLibrary {
                name: l.name,
                filename: l.filename,
                description: l.description,
                snippet_count: l.snippet_count,
                tags: l.tags,
            })
            .collect();

        tracing::info!(
            request_id = %request_id,
            user_id = %user_id,
            count = proto_libraries.len(),
            "ListPremadeLibraries completed"
        );

        let count = proto_libraries.len() as i32;

        self.record_request_duration("list_premade_libraries", start);

        let result = Ok(Response::new(ListPremadeLibrariesResponse {
            libraries: proto_libraries,
            has_more: false,
            total_count: count,
        }));
        self.record_request_finished("list_premade_libraries", result.is_ok());
        result
    }

    async fn get_premade_library(
        &self,
        request: Request<GetPremadeLibraryRequest>,
    ) -> Result<Response<GetPremadeLibraryResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("get_premade_library");
        tracing::info!(request_id = %request_id, "GetPremadeLibrary request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("get_premade_library", false);
            })?;

        if req.filename.is_empty() {
            self.record_request_duration("get_premade_library", start);
            self.record_request_finished("get_premade_library", false);
            return Err(Status::invalid_argument("Filename is required"));
        }

        if req.filename.contains("..") || req.filename.contains('/') || req.filename.contains('\\')
        {
            self.record_request_duration("get_premade_library", start);
            self.record_request_finished("get_premade_library", false);
            return Err(Status::invalid_argument("Invalid filename"));
        }

        let sanitized: String = req
            .filename
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
            .collect();

        if sanitized.is_empty() || sanitized.len() > 64 {
            self.record_request_duration("get_premade_library", start);
            self.record_request_finished("get_premade_library", false);
            return Err(Status::invalid_argument("Invalid filename"));
        }
        if sanitized != req.filename {
            self.record_request_duration("get_premade_library", start);
            self.record_request_finished("get_premade_library", false);
            return Err(Status::invalid_argument("Invalid filename"));
        }

        let content = match self.premade_manager.get(&sanitized) {
            Ok(c) => c,
            Err(e) => {
                self.record_request_duration("get_premade_library", start);
                self.record_request_finished("get_premade_library", false);
                return Err(e);
            }
        };

        tracing::info!("User {} fetched premade library '{}'", user_id, sanitized);

        self.record_request_duration("get_premade_library", start);

        let result = Ok(Response::new(GetPremadeLibraryResponse {
            success: true,
            name: sanitized.clone(),
            content,
            message: "Library fetched successfully".to_string(),
        }));
        self.record_request_finished("get_premade_library", result.is_ok());
        result
    }

    async fn search_premade_libraries(
        &self,
        request: Request<SearchPremadeLibrariesRequest>,
    ) -> Result<Response<SearchPremadeLibrariesResponse>, Status> {
        let request_id = uuid::Uuid::new_v4();
        let start = std::time::Instant::now();
        self.record_request("search_premade_libraries");
        tracing::info!(request_id = %request_id, "SearchPremadeLibraries request");
        let rate_limit_key = self.peer_rate_limit_key(&request);
        let api_key = self.request_api_key(&request, &request.get_ref().api_key);
        let req = request.into_inner();

        let _user_id = self
            .authenticate_and_rate_limit_with_duration(&api_key, &rate_limit_key, Some(start))
            .await
            .inspect_err(|_| {
                self.record_request_finished("search_premade_libraries", false);
            })?;

        if req.query.is_empty() {
            self.record_request_duration("search_premade_libraries", start);
            self.record_request_finished("search_premade_libraries", false);
            return Err(Status::invalid_argument("Query is required"));
        }

        let results = self.premade_manager.search(&req.query);

        let proto_libraries: Vec<ProtoPremadeLibrary> = results
            .into_iter()
            .map(|l| ProtoPremadeLibrary {
                name: l.name,
                filename: l.filename,
                description: l.description,
                snippet_count: l.snippet_count,
                tags: l.tags,
            })
            .collect();

        let count = proto_libraries.len() as i32;

        tracing::info!(
            request_id = %request_id,
            query = %req.query,
            count = count,
            "SearchPremadeLibraries completed"
        );

        self.record_request_duration("search_premade_libraries", start);

        let result = Ok(Response::new(SearchPremadeLibrariesResponse {
            libraries: proto_libraries,
            total_count: count,
        }));
        self.record_request_finished("search_premade_libraries", result.is_ok());
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use snip_proto::{
        CreateLibraryRequest, GetPremadeLibraryRequest, GetSnippetsRequest, HealthRequest,
        ListLibrariesRequest, PushSnippetsRequest, RegisterRequest, Snippet as ProtoSnippet,
        SyncRequest,
    };

    pub async fn setup_test_service() -> SnipSyncService {
        setup_test_service_with_rate_limit(DEFAULT_RATE_LIMIT_PER_MINUTE).await
    }

    async fn setup_test_service_with_rate_limit(rate_limit_per_minute: u32) -> SnipSyncService {
        let db = Arc::new(Database::connect("sqlite::memory:", 5).await.unwrap());
        let config = Config {
            grpc_host: "127.0.0.1".to_string(),
            grpc_port: 50051,
            http_host: "127.0.0.1".to_string(),
            http_port: 50050,
            db_path: "sqlite::memory:".to_string(),
            db_max_connections: 5,
            premade_dir: PathBuf::from("premade-libraries"),
            max_command_length: 1024,
            max_encrypted_payload_length: DEFAULT_MAX_ENCRYPTED_PAYLOAD_LENGTH,
            max_description_length: 1024,
            max_tags: 50,
            max_tag_length: 100,
            max_id_length: 128,
            max_device_id_length: 128,
            max_api_key_length: 512,
            request_timeout_secs: 30,
            grpc_max_message_size: 4 * 1024 * 1024,
            rate_limit_per_minute,
            register_per_minute: DEFAULT_REGISTER_PER_MINUTE,
            metrics_auth_failures_per_minute: DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE,
            trusted_proxies: vec![],
            metrics_username: None,
            metrics_password: None,
            cors_allowed_origins: vec![],
        };
        let metrics = Metrics::fallback();
        let rate_limiter = Arc::new(RateLimiter::new());
        let premade_manager = PremadeManager::new(PathBuf::from("premade-libraries"));

        SnipSyncService {
            db,
            rate_limiter,
            config,
            metrics,
            premade_manager,
            #[cfg(any(test, feature = "test-helpers"))]
            captured_auth_header: Arc::new(std::sync::Mutex::new(None)),
            test_observer: None,
            push_fail_after: Arc::new(std::sync::atomic::AtomicU32::new(u32::MAX)),
            push_fail_counter: Arc::new(std::sync::atomic::AtomicU32::new(0)),
        }
    }

    pub async fn register_test_user(service: &SnipSyncService) -> String {
        let req = Request::new(RegisterRequest {
            device_id: "test-device".to_string(),
        });
        let resp = service.register(req).await.unwrap();
        resp.into_inner().api_key
    }

    #[tokio::test]
    async fn test_health_check() {
        let service = setup_test_service().await;
        let req = Request::new(HealthRequest {});
        let resp = service.health(req).await.unwrap();
        let health = resp.into_inner();
        assert!(health.healthy);
        assert_eq!(health.version, env!("CARGO_PKG_VERSION"));
    }

    #[tokio::test]
    async fn test_register_creates_user() {
        let service = setup_test_service().await;
        let req = Request::new(RegisterRequest {
            device_id: "test-device".to_string(),
        });
        let resp = service.register(req).await.unwrap();
        let reg = resp.into_inner();
        assert!(reg.success);
        assert!(!reg.api_key.is_empty());
        assert!(!reg.device_id.is_empty());
        assert!(uuid::Uuid::parse_str(&reg.device_id).is_ok());
    }

    #[tokio::test]
    async fn test_register_rate_limiting() {
        let service = setup_test_service_with_rate_limit(3).await;
        for _ in 0..3 {
            let req = Request::new(RegisterRequest {
                device_id: "test-device".to_string(),
            });
            let _ = service.register(req).await;
        }
        let req = Request::new(RegisterRequest {
            device_id: "test-device".to_string(),
        });
        let resp = service.register(req).await;
        assert!(resp.is_err());
        assert_eq!(resp.unwrap_err().code(), tonic::Code::ResourceExhausted);
    }

    #[tokio::test]
    async fn peer_rate_limit_key_uses_the_peer_socket_address() {
        let service = setup_test_service().await;
        let mut req = Request::new(RegisterRequest {
            device_id: "test-device".to_string(),
        });
        assert_eq!(service.peer_rate_limit_key(&req), "unknown");
        req.extensions_mut()
            .insert(tonic::transport::server::TcpConnectInfo {
                local_addr: None,
                remote_addr: Some("203.0.113.7:44321".parse().unwrap()),
            });
        assert_eq!(service.peer_rate_limit_key(&req), "203.0.113.7");
    }

    #[tokio::test]
    async fn peer_rate_limit_key_honours_x_forwarded_for_from_a_trusted_proxy() {
        let mut service = setup_test_service().await;
        service.config.trusted_proxies = vec!["198.51.100.1".to_string()];

        let mut req = Request::new(RegisterRequest {
            device_id: "test-device".to_string(),
        });
        req.extensions_mut()
            .insert(tonic::transport::server::TcpConnectInfo {
                local_addr: None,
                remote_addr: Some("198.51.100.1:44321".parse().unwrap()),
            });
        req.metadata_mut()
            .insert("x-forwarded-for", "203.0.113.9:5555".parse().unwrap());
        assert_eq!(service.peer_rate_limit_key(&req), "203.0.113.9");
    }

    #[test]
    fn strip_port_handles_malformed_input_without_panicking() {
        // A `]:` at offset 0 used to slice `addr[1..0]` and panic.
        assert_eq!(strip_port("]:"), "]:");
        assert_eq!(strip_port("1.2.3.4]:80"), "1.2.3.4]:80");
        assert_eq!(strip_port("[::1]:443"), "::1");
        assert_eq!(strip_port("[::1]"), "[::1]");
        assert_eq!(strip_port("1.2.3.4:80"), "1.2.3.4");
        assert_eq!(strip_port("::1"), "::1");
        assert_eq!(strip_port(""), "");
    }

    #[tokio::test]
    async fn test_create_and_list_libraries() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "test-lib".to_string(),
        });
        let resp = service.create_library(req).await.unwrap();
        let create = resp.into_inner();
        assert!(create.success);
        assert!(!create.library_id.is_empty());

        let req = Request::new(ListLibrariesRequest {
            api_key: api_key.clone(),
            limit: 100,
            offset: 0,
        });
        let resp = service.list_libraries(req).await.unwrap();
        let list = resp.into_inner();
        assert_eq!(list.libraries.len(), 2);
        assert!(list.libraries.iter().any(|l| l.name == "test-lib"));
    }

    #[tokio::test]
    async fn test_create_duplicate_library_name() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "test-lib".to_string(),
        });
        let _ = service.create_library(req).await.unwrap();

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "test-lib".to_string(),
        });
        let resp = service.create_library(req).await;
        assert!(resp.is_err());
        assert_eq!(resp.unwrap_err().code(), tonic::Code::AlreadyExists);
    }

    #[tokio::test]
    async fn test_invalid_api_key() {
        let service = setup_test_service().await;
        let req = Request::new(GetSnippetsRequest {
            api_key: "invalid-key".to_string(),
            library_id: String::new(),
            limit: 100,
            offset: 0,
            since: 0,
        });
        let resp = service.get_snippets(req).await;
        assert!(resp.is_err());
        assert_eq!(resp.unwrap_err().code(), tonic::Code::Unauthenticated);
    }

    #[tokio::test]
    async fn test_validate_snippet_empty_id() {
        let service = setup_test_service().await;
        let snippet = ProtoSnippet {
            id: String::new(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: 0,
            updated_at: 0,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("ID is required"));
    }

    #[tokio::test]
    async fn test_validate_snippet_oversized_command() {
        let service = setup_test_service().await;
        let snippet = ProtoSnippet {
            id: "test-id".to_string(),
            description: "test".to_string(),
            command: "x".repeat(2000),
            tags: vec![],
            created_at: 0,
            updated_at: 0,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("maximum length"));
    }

    #[tokio::test]
    async fn test_validate_snippet_future_timestamp() {
        let service = setup_test_service().await;
        let future = time::OffsetDateTime::now_utc().unix_timestamp() + 600;
        let snippet = ProtoSnippet {
            id: "test-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: future,
            updated_at: future,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        let msg = result.unwrap_err().message().to_string();
        assert!(
            msg.contains("ahead of server time"),
            "Expected clock skew message, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_validate_snippet_negative_timestamp() {
        let service = setup_test_service().await;
        let snippet = ProtoSnippet {
            id: "test-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: -1,
            updated_at: -1,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("non-negative"));
    }

    #[tokio::test]
    async fn test_validate_snippet_clock_skew_reports_magnitude() {
        let service = setup_test_service().await;
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let snippet = ProtoSnippet {
            id: "skew-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: now,
            updated_at: now + 742, // 742 seconds ahead
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        let msg = result.unwrap_err().message().to_string();
        assert!(
            msg.contains("742"),
            "Clock skew message should contain magnitude, got: {msg}"
        );
        assert!(
            msg.contains("synchronize the client clock"),
            "Clock skew message should contain corrective action, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_validate_snippet_created_ahead_reports_skew() {
        let service = setup_test_service().await;
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let snippet = ProtoSnippet {
            id: "skew-created".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: now + 500,
            updated_at: now, // updated_at is fine, only created_at is ahead
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        let msg = result.unwrap_err().message().to_string();
        assert!(
            msg.contains("created_at"),
            "Should mention created_at: {msg}"
        );
        assert!(msg.contains("500"), "Should contain skew magnitude: {msg}");
    }

    #[tokio::test]
    async fn test_validate_snippet_too_many_tags() {
        let service = setup_test_service().await;
        let snippet = ProtoSnippet {
            id: "test-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: (0..100).map(|i| format!("tag{}", i)).collect(),
            created_at: 0,
            updated_at: 0,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("Too many tags"));
    }

    #[tokio::test]
    async fn test_validate_snippet_valid() {
        let service = setup_test_service().await;
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let snippet = ProtoSnippet {
            id: "test-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec!["bash".to_string()],
            created_at: now,
            updated_at: now,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        assert!(service.validate_snippet(&snippet).is_ok());
    }

    #[tokio::test]
    async fn test_validate_snippet_zero_timestamp_rejected() {
        let service = setup_test_service().await;
        let snippet = ProtoSnippet {
            id: "epoch-id".to_string(),
            description: "test".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: 0,
            updated_at: 0,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        };
        let result = service.validate_snippet(&snippet);
        assert!(result.is_err());
        let msg = result.unwrap_err().message().to_string();
        assert!(
            msg.contains("unset client clock"),
            "Expected zero-timestamp message, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_cross_user_library_access_denied() {
        let service = setup_test_service().await;
        let api_key1 = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key1.clone(),
            name: "user1-lib".to_string(),
        });
        let resp = service.create_library(req).await.unwrap();
        let library_id = resp.into_inner().library_id;

        let api_key2 = register_test_user(&service).await;

        let req = Request::new(GetSnippetsRequest {
            api_key: api_key2,
            library_id,
            limit: 100,
            offset: 0,
            since: 0,
        });
        let resp = service.get_snippets(req).await;
        assert!(resp.is_err());
        assert_eq!(resp.unwrap_err().code(), tonic::Code::NotFound);
    }

    #[tokio::test]
    async fn test_duplicate_id_across_libraries_is_rejected_not_silently_dropped() {
        // `snippets.id` is a global primary key. Pushing the same id into a
        // second library of the same user writes zero rows, and SQLite raises
        // no error for the discarded `DO UPDATE`. Counting that as accepted
        // would tell the client the upload succeeded while the snippet is
        // absent from the server forever.
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let work = service
            .create_library(Request::new(CreateLibraryRequest {
                api_key: api_key.clone(),
                name: "work".to_string(),
            }))
            .await
            .unwrap()
            .into_inner()
            .library_id;
        let personal = service
            .create_library(Request::new(CreateLibraryRequest {
                api_key: api_key.clone(),
                name: "personal".to_string(),
            }))
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let snippet = ProtoSnippet {
            id: "legacy-abc123".to_string(),
            description: "git status".to_string(),
            command: "git status".to_string(),
            tags: vec![],
            created_at: time::OffsetDateTime::now_utc().unix_timestamp(),
            updated_at: time::OffsetDateTime::now_utc().unix_timestamp(),
            device_id: "device-1".to_string(),
            deleted: false,
            encrypted: false,
        };

        let first = service
            .push_snippets(Request::new(PushSnippetsRequest {
                api_key: api_key.clone(),
                library_id: work.clone(),
                snippets: vec![snippet.clone()],
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(first.accepted_count, 1);
        assert_eq!(first.rejected_count, 0);

        let second = service
            .push_snippets(Request::new(PushSnippetsRequest {
                api_key: api_key.clone(),
                library_id: personal.clone(),
                snippets: vec![snippet],
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(
            second.rejected_count, 1,
            "cross-library id collision must be rejected, not accepted"
        );
        assert_eq!(
            second.accepted_count, 0,
            "the dropped write must not be counted as accepted"
        );
        assert!(!second.success, "a partial upload must not report success");

        // The snippet really is only stored under the first library.
        let other = service
            .get_snippets(Request::new(GetSnippetsRequest {
                api_key: api_key.clone(),
                library_id: personal.clone(),
                limit: 100,
                offset: 0,
                since: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert!(other.snippets.is_empty());

        // And `sync` reports the same collision in `skipped_ids`.
        let sync = service
            .sync(Request::new(SyncRequest {
                api_key: api_key.clone(),
                local_snippets: vec![ProtoSnippet {
                    id: "legacy-abc123".to_string(),
                    description: "git status".to_string(),
                    command: "git status".to_string(),
                    tags: vec![],
                    created_at: time::OffsetDateTime::now_utc().unix_timestamp(),
                    updated_at: time::OffsetDateTime::now_utc().unix_timestamp(),
                    device_id: "device-1".to_string(),
                    deleted: false,
                    encrypted: false,
                }],
                last_sync_timestamp: 0,
                last_sync_sequence: 0,
                library_id: personal,
                limit: 100,
                offset: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(
            sync.skipped_ids,
            vec!["legacy-abc123".to_string()],
            "sync must surface the skipped id instead of reporting a clean run"
        );
        assert_eq!(sync.skipped_count, 1);
    }

    #[tokio::test]
    async fn test_older_version_in_same_library_is_accepted_as_stale() {
        // A genuine last-write-wins dedupe also writes zero rows, but it must
        // NOT be reported as a rejection — only a foreign-scope collision is.
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;
        let library_id = service
            .create_library(Request::new(CreateLibraryRequest {
                api_key: api_key.clone(),
                name: "work".to_string(),
            }))
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let newer = ProtoSnippet {
            id: "snippet-1".to_string(),
            description: "newer".to_string(),
            command: "echo newer".to_string(),
            tags: vec![],
            created_at: now,
            updated_at: now,
            device_id: "device-1".to_string(),
            deleted: false,
            encrypted: false,
        };
        let older = ProtoSnippet {
            description: "older".to_string(),
            command: "echo older".to_string(),
            created_at: now - 500,
            updated_at: now - 500,
            ..newer.clone()
        };

        for snippet in [newer, older] {
            let push = service
                .push_snippets(Request::new(PushSnippetsRequest {
                    api_key: api_key.clone(),
                    library_id: library_id.clone(),
                    snippets: vec![snippet],
                }))
                .await
                .unwrap()
                .into_inner();
            assert_eq!(push.accepted_count, 1);
            assert_eq!(push.rejected_count, 0, "stale write is not a rejection");
        }

        let list = service
            .get_snippets(Request::new(GetSnippetsRequest {
                api_key,
                library_id,
                limit: 100,
                offset: 0,
                since: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(list.snippets.len(), 1);
        assert_eq!(list.snippets[0].command, "echo newer");
    }

    #[test]
    fn test_fit_page_to_byte_ceiling_keeps_page_within_budget() {
        // Each row is ~1 KiB of command. With a 4 KiB budget only some rows
        // fit; the rest must be dropped *and reported* so the client still
        // paginates. Dropping them silently would lose records.
        let row = |i: usize| ProtoSnippet {
            id: format!("snippet-{i}"),
            description: "d".repeat(1024),
            command: "c".repeat(1024),
            tags: vec![],
            created_at: 1,
            updated_at: 1,
            device_id: "dev".to_string(),
            deleted: false,
            encrypted: false,
        };
        let mut page: Vec<ProtoSnippet> = (0..10).map(row).collect();
        let budget = 4 * 1024usize;

        let truncated = fit_page_to_byte_ceiling(&mut page, budget);

        assert!(truncated, "page must report that rows were dropped");
        assert!(!page.is_empty(), "at least one row must always be kept");
        assert!(
            page.len() < 10,
            "rows beyond the byte budget must be dropped, got {}",
            page.len()
        );
        assert!(
            page.iter().map(|s| s.encoded_len()).sum::<usize>() <= budget,
            "kept rows must fit the budget"
        );
        // Dropping is a tail-trim, so the prefix is preserved and the client
        // can resume from `offset + kept`.
        assert_eq!(page[0].id, "snippet-0");
    }

    #[test]
    fn test_fit_page_to_byte_ceiling_keeps_at_least_one_oversized_row() {
        // A single row larger than the whole budget cannot be made to fit.
        // Returning an empty page would stall the client forever, so the row is
        // returned anyway and left for the transport to report.
        let mut page = vec![ProtoSnippet {
            id: "huge".to_string(),
            description: String::new(),
            command: "x".repeat(64 * 1024),
            tags: vec![],
            created_at: 1,
            updated_at: 1,
            device_id: "dev".to_string(),
            deleted: false,
            encrypted: true,
        }];
        let truncated = fit_page_to_byte_ceiling(&mut page, 1024);
        assert_eq!(page.len(), 1, "an oversized row must still be returned");
        assert!(!truncated, "nothing was actually dropped");
    }

    #[test]
    fn test_fit_page_to_byte_ceiling_noop_when_page_fits() {
        let mut page = vec![ProtoSnippet {
            id: "small".to_string(),
            description: "d".to_string(),
            command: "echo hi".to_string(),
            tags: vec![],
            created_at: 1,
            updated_at: 1,
            device_id: "dev".to_string(),
            deleted: false,
            encrypted: false,
        }];
        assert!(!fit_page_to_byte_ceiling(&mut page, 1024 * 1024));
        assert_eq!(page.len(), 1);
    }

    #[test]
    fn test_page_byte_ceiling_reserves_envelope_space() {
        assert_eq!(
            page_byte_ceiling(4 * 1024 * 1024, 0),
            4 * 1024 * 1024 - RESPONSE_ENVELOPE_RESERVE_BYTES
        );
        assert_eq!(
            page_byte_ceiling(4 * 1024 * 1024, 2048),
            4 * 1024 * 1024 - RESPONSE_ENVELOPE_RESERVE_BYTES - 2048
        );
        // Absurd envelope payloads must saturate, never wrap into a huge budget.
        assert_eq!(page_byte_ceiling(1024, 1024 * 1024), 0);
    }

    #[tokio::test]
    async fn test_oversized_encrypted_payload_is_rejected() {
        // Encrypted records previously skipped every size check, so storage
        // was unbounded and a record larger than the gRPC ceiling could be
        // stored but never downloaded.
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;
        let library_id = service
            .create_library(Request::new(CreateLibraryRequest {
                api_key: api_key.clone(),
                name: "work".to_string(),
            }))
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let push = service
            .push_snippets(Request::new(PushSnippetsRequest {
                api_key,
                library_id,
                snippets: vec![ProtoSnippet {
                    id: "huge".to_string(),
                    description: String::new(),
                    command: "x".repeat(DEFAULT_MAX_ENCRYPTED_PAYLOAD_LENGTH + 1),
                    tags: vec![],
                    created_at: 1,
                    updated_at: 1,
                    device_id: "dev".to_string(),
                    deleted: false,
                    encrypted: true,
                }],
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(push.rejected_count, 1, "oversized payload must be rejected");
        assert_eq!(push.accepted_count, 0);
    }

    #[tokio::test]
    async fn test_push_and_get_snippets() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "test-lib".to_string(),
        });
        let resp = service.create_library(req).await.unwrap();
        let library_id = resp.into_inner().library_id;

        let snippet = ProtoSnippet {
            id: "snippet-1".to_string(),
            description: "Test snippet".to_string(),
            command: "echo hello".to_string(),
            tags: vec!["test".to_string()],
            created_at: time::OffsetDateTime::now_utc().unix_timestamp(),
            updated_at: time::OffsetDateTime::now_utc().unix_timestamp(),
            device_id: "device-1".to_string(),
            deleted: false,
            encrypted: false,
        };
        let req = Request::new(PushSnippetsRequest {
            api_key: api_key.clone(),
            library_id: library_id.clone(),
            snippets: vec![snippet],
        });
        let resp = service.push_snippets(req).await.unwrap();
        let push = resp.into_inner();
        assert_eq!(push.accepted_count, 1);
        assert_eq!(push.rejected_count, 0);

        let req = Request::new(GetSnippetsRequest {
            api_key: api_key.clone(),
            library_id,
            limit: 100,
            offset: 0,
            since: 0,
        });
        let resp = service.get_snippets(req).await.unwrap();
        let list = resp.into_inner();
        assert_eq!(list.snippets.len(), 1);
        assert_eq!(list.snippets[0].id, "snippet-1");
        assert_eq!(list.snippets[0].command, "echo hello");
    }

    #[tokio::test]
    async fn test_delete_library() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "to-delete".to_string(),
        });
        let resp = service.create_library(req).await.unwrap();
        let library_id = resp.into_inner().library_id;

        let req = Request::new(snip_proto::DeleteLibraryRequest {
            api_key: api_key.clone(),
            library_id: library_id.clone(),
        });
        let resp = service.delete_library(req).await.unwrap();
        assert!(resp.into_inner().success);

        let req = Request::new(ListLibrariesRequest {
            api_key: api_key.clone(),
            limit: 100,
            offset: 0,
        });
        let resp = service.list_libraries(req).await.unwrap();
        let list = resp.into_inner();
        assert_eq!(list.libraries.len(), 1);
        assert_eq!(list.libraries[0].name, "default");
    }

    #[tokio::test]
    async fn test_delete_default_library_blocked() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(snip_proto::DeleteLibraryRequest {
            api_key: api_key.clone(),
            library_id: "default".to_string(),
        });
        let resp = service.delete_library(req).await;
        assert!(resp.is_err());
        assert!(resp.unwrap_err().message().contains("Cannot delete"));
    }

    #[tokio::test]
    async fn test_sync_basic() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "sync-test".to_string(),
        });
        let resp = service.create_library(req).await.unwrap();
        let library_id = resp.into_inner().library_id;

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id,
            limit: 1000,
            offset: 0,
        });
        let resp = service.sync(req).await.unwrap();
        let sync = resp.into_inner();
        assert_eq!(sync.snippets.len(), 0);
    }

    fn proto_snippet(id: &str, updated_at: i64) -> ProtoSnippet {
        ProtoSnippet {
            id: id.to_string(),
            description: "Test snippet".to_string(),
            command: "echo hello".to_string(),
            tags: vec![],
            created_at: updated_at,
            updated_at,
            device_id: "device-1".to_string(),
            deleted: false,
            encrypted: false,
        }
    }

    /// A client that sends no sequence cursor is served by the timestamp
    /// filter, exactly as before, and the response carries no sequence.
    #[tokio::test]
    async fn test_sync_without_a_sequence_cursor_serves_the_timestamp_rows() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "cursor-lib".to_string(),
        });
        let library_id = service
            .create_library(req)
            .await
            .unwrap()
            .into_inner()
            .library_id;

        for (id, updated_at) in [("a", 100_i64), ("b", 200)] {
            let req = Request::new(PushSnippetsRequest {
                api_key: api_key.clone(),
                library_id: library_id.clone(),
                snippets: vec![proto_snippet(id, updated_at)],
            });
            service.push_snippets(req).await.unwrap();
        }

        // A timestamp-only request: a non-zero timestamp cursor and no
        // sequence cursor. This is the shape an old client sends.
        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 1,
            last_sync_sequence: 0,
            library_id: library_id.clone(),
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();

        assert_eq!(sync.snippets.len(), 2);
        // A delta does not deliver the library's whole history, so its
        // watermark is not adoptable by this client and none is returned:
        // an old client never receives a value it cannot interpret.
        assert_eq!(sync.server_sequence, 0);
        assert!(sync.server_timestamp > 0);
    }

    /// A request with no cursor at all is the bootstrap: it delivers the
    /// complete library, so the client may adopt the sequence watermark.
    #[tokio::test]
    async fn test_sync_without_any_cursor_bootstraps_the_sequence_watermark() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "cursor-lib".to_string(),
        });
        let library_id = service
            .create_library(req)
            .await
            .unwrap()
            .into_inner()
            .library_id;

        for (id, updated_at) in [("a", 100_i64), ("b", 200)] {
            let req = Request::new(PushSnippetsRequest {
                api_key: api_key.clone(),
                library_id: library_id.clone(),
                snippets: vec![proto_snippet(id, updated_at)],
            });
            service.push_snippets(req).await.unwrap();
        }

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id: library_id.clone(),
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();

        assert_eq!(sync.snippets.len(), 2);
        assert_eq!(
            sync.server_sequence, 2,
            "a cursorless request is the bootstrap and reports the watermark"
        );
    }

    /// An empty library still reports a sequence, so a client can tell a
    /// server that serves the sequence from one that does not. Zero means
    /// "no sequence" in the protocol, so the reported position is the one
    /// before the library's first row; the inclusive `sequence >=` filter
    /// keeps that first row deliverable.
    #[tokio::test]
    async fn test_sync_bootstrap_on_an_empty_library_reports_a_sequence() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "empty-lib".to_string(),
        });
        let library_id = service
            .create_library(req)
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id: library_id.clone(),
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();

        assert!(sync.snippets.is_empty());
        assert_eq!(
            sync.server_sequence, 1,
            "an empty library must still report a sequence, so the client can \
             tell a sequence-capable server from one that does not serve it"
        );

        // The first row written to the library is still delivered to a client
        // that adopted the reported position.
        let req = Request::new(PushSnippetsRequest {
            api_key: api_key.clone(),
            library_id: library_id.clone(),
            snippets: vec![proto_snippet("first", 100)],
        });
        service.push_snippets(req).await.unwrap();

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: 1,
            library_id,
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();
        assert_eq!(sync.snippets.len(), 1);
        assert_eq!(sync.snippets[0].id, "first");
    }

    /// A client that holds a sequence cursor is served by the sequence
    /// filter and receives the sequence watermark back.
    #[tokio::test]
    async fn test_sync_with_a_sequence_cursor_serves_the_rows_after_it() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "cursor-lib".to_string(),
        });
        let library_id = service
            .create_library(req)
            .await
            .unwrap()
            .into_inner()
            .library_id;

        for (id, updated_at) in [("a", 100_i64), ("b", 200), ("c", 300)] {
            let req = Request::new(PushSnippetsRequest {
                api_key: api_key.clone(),
                library_id: library_id.clone(),
                snippets: vec![proto_snippet(id, updated_at)],
            });
            service.push_snippets(req).await.unwrap();
        }

        // The bootstrap request returns everything and the watermark.
        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id: library_id.clone(),
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();
        assert_eq!(sync.snippets.len(), 3);
        assert_eq!(sync.server_sequence, 3);

        // A client that knows the watermark asks with it and receives only
        // the rows written after it.
        let user_id = service
            .db
            .get_user_by_api_key(&api_key)
            .await
            .unwrap()
            .unwrap();
        let watermark = service
            .db
            .get_latest_sequence(&user_id, &library_id)
            .await
            .unwrap();
        assert_eq!(watermark, 3);

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![],
            last_sync_timestamp: 0,
            last_sync_sequence: watermark,
            library_id: library_id.clone(),
            limit: 1000,
            offset: 0,
        });
        let sync = service.sync(req).await.unwrap().into_inner();
        assert_eq!(sync.snippets.len(), 1);
        assert_eq!(sync.snippets[0].id, "c");
        assert_eq!(sync.server_sequence, watermark);
    }

    #[tokio::test]
    async fn test_sync_accepts_local_record_older_than_pull_watermark() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(CreateLibraryRequest {
            api_key: api_key.clone(),
            name: "clock-skew-test".to_string(),
        });
        let library_id = service
            .create_library(req)
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let req = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![ProtoSnippet {
                id: "clock-skewed".to_string(),
                description: "local mutation".to_string(),
                command: "echo local".to_string(),
                tags: vec![],
                created_at: 10,
                updated_at: 10,
                device_id: "device".to_string(),
                deleted: false,
                encrypted: false,
            }],
            last_sync_timestamp: 1_000,
            last_sync_sequence: 0,
            library_id: library_id.clone(),
            limit: 100,
            offset: 0,
        });
        service.sync(req).await.unwrap();

        let response = service
            .get_snippets(Request::new(GetSnippetsRequest {
                api_key,
                library_id,
                limit: 100,
                offset: 0,
                since: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(response.total_count, 1);
        assert_eq!(response.snippets[0].id, "clock-skewed");
    }

    #[tokio::test]
    async fn test_premade_filename_with_unsafe_characters_is_rejected() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let req = Request::new(GetPremadeLibraryRequest {
            api_key,
            filename: "valid-name!.toml".to_string(),
        });
        let error = service.get_premade_library(req).await.unwrap_err();

        assert_eq!(error.code(), tonic::Code::InvalidArgument);
        assert_eq!(error.message(), "Invalid filename");
    }

    #[test]
    fn config_load_missing_file_uses_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing.toml");
        let config = Config::load_from(&path, &|_| None).unwrap();
        assert_eq!(config.grpc_port, 50051);
        assert_eq!(config.http_port, 50050);
    }

    #[test]
    fn config_load_merges_file_and_environment_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[server]\ngrpc_port = 51000\nhttp_host = \"192.0.2.10\"\n",
        )
        .unwrap();
        let config = Config::load_from(&path, &|name| {
            (name == "GRPC_PORT").then(|| "52000".to_string())
        })
        .unwrap();
        assert_eq!(config.grpc_port, 52000);
        assert_eq!(config.http_host, "192.0.2.10");
    }

    #[test]
    fn config_load_rejects_malformed_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server\n").unwrap();
        let error = match Config::load_from(&path, &|_| None) {
            Ok(_) => panic!("malformed config unexpectedly loaded"),
            Err(error) => error,
        };
        let message = error.to_string();
        assert!(message.contains(&path.display().to_string()));
        assert!(message.contains("parse"));
    }

    #[test]
    fn config_load_rejects_unreadable_existing_path() {
        let dir = tempfile::tempdir().unwrap();
        let error = match Config::load_from(dir.path(), &|_| None) {
            Ok(_) => panic!("directory unexpectedly loaded as config"),
            Err(error) => error,
        };
        assert!(
            error
                .to_string()
                .contains(&dir.path().display().to_string())
        );
    }

    #[test]
    fn parse_env_valid_numeric_override() {
        let env = |name: &str| match name {
            "GRPC_PORT" => Some("60000".to_string()),
            _ => None,
        };
        let val: Option<u16> = parse_env(&env, "GRPC_PORT").unwrap();
        assert_eq!(val, Some(60000));
    }

    #[test]
    fn parse_env_malformed_numeric_returns_invalid_environment() {
        let env = |name: &str| match name {
            "GRPC_PORT" => Some("not-a-number".to_string()),
            _ => None,
        };
        let err = parse_env::<u16>(&env, "GRPC_PORT").unwrap_err();
        match err {
            ConfigLoadError::InvalidEnvironment { name, value, .. } => {
                assert_eq!(name, "GRPC_PORT");
                assert_eq!(value, "not-a-number");
            }
            other => panic!("expected InvalidEnvironment, got: {other}"),
        }
    }

    #[test]
    fn parse_env_missing_variable_returns_none() {
        let env = |_name: &str| -> Option<String> { None };
        let val: Option<u16> = parse_env(&env, "GRPC_PORT").unwrap();
        assert_eq!(val, None);
    }

    #[test]
    fn parse_bool_env_accepted_true_spellings() {
        for input in &["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
            let env = |_: &str| Some(input.to_string());
            let val = parse_bool_env(&env, "FLAG").unwrap();
            assert_eq!(val, Some(true), "expected true for {input:?}");
        }
    }

    #[test]
    fn parse_bool_env_accepted_false_spellings() {
        for input in &["false", "0", "no", "off", "FALSE", "No", "OFF"] {
            let env = |_: &str| Some(input.to_string());
            let val = parse_bool_env(&env, "FLAG").unwrap();
            assert_eq!(val, Some(false), "expected false for {input:?}");
        }
    }

    #[test]
    fn parse_bool_env_unknown_value_fails() {
        let env = |_: &str| Some("maybe".to_string());
        let err = parse_bool_env(&env, "FLAG").unwrap_err();
        match err {
            ConfigLoadError::InvalidEnvironment { name, value, .. } => {
                assert_eq!(name, "FLAG");
                assert_eq!(value, "maybe");
            }
            other => panic!("expected InvalidEnvironment, got: {other}"),
        }
    }

    #[test]
    fn parse_bool_env_missing_variable_returns_none() {
        let env = |_name: &str| -> Option<String> { None };
        let val = parse_bool_env(&env, "FLAG").unwrap();
        assert_eq!(val, None);
    }

    #[test]
    fn config_validate_rejects_zero_grpc_port() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server]\ngrpc_port = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "GRPC_PORT"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_db_max_connections() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.database]\nmax_connections = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "DB_MAX_CONNECTIONS"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_request_timeout() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.limits]\nrequest_timeout_secs = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "REQUEST_TIMEOUT_SECS"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_register_per_minute() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.rate_limit]\nregister_per_minute = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "REGISTER_PER_MINUTE"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_metrics_auth_failures_per_minute() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[server.rate_limit]\nmetrics_auth_failures_per_minute = 0\n",
        )
        .unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => {
                assert_eq!(name, "METRICS_AUTH_FAILURES_PER_MINUTE")
            }
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_defaults_new_rate_limit_keys_when_absent() {
        // An existing config that predates the keys must keep loading, and the
        // defaults must be documented values rather than zero.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.rate_limit]\nrequests_per_minute = 60\n").unwrap();
        let config = Config::load_from(&path, &|_| None).unwrap();
        assert_eq!(config.rate_limit_per_minute, 60);
        assert_eq!(config.register_per_minute, DEFAULT_REGISTER_PER_MINUTE);
        assert_eq!(
            config.metrics_auth_failures_per_minute,
            DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE
        );
    }

    #[test]
    fn config_reads_new_rate_limit_keys_from_file_and_env() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[server.rate_limit]\nregister_per_minute = 3\nmetrics_auth_failures_per_minute = 4\n",
        )
        .unwrap();
        let config = Config::load_from(&path, &|_| None).unwrap();
        assert_eq!(config.register_per_minute, 3);
        assert_eq!(config.metrics_auth_failures_per_minute, 4);

        // Environment overrides win over the file.
        let env = |name: &str| match name {
            "REGISTER_PER_MINUTE" => Some("7".to_string()),
            "METRICS_AUTH_FAILURES_PER_MINUTE" => Some("8".to_string()),
            _ => None,
        };
        let config = Config::load_from(&path, &env).unwrap();
        assert_eq!(config.register_per_minute, 7);
        assert_eq!(config.metrics_auth_failures_per_minute, 8);
    }

    #[tokio::test]
    async fn register_global_budget_rejects_without_writing_rows() {
        let mut service = setup_test_service().await;
        service.config.register_per_minute = 2;

        let count_users = |db: Arc<Database>| async move {
            let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
                .fetch_one(db.pool())
                .await
                .expect("counting users must succeed");
            count
        };

        for attempt in 1..=2 {
            let response = service
                .register(Request::new(RegisterRequest {
                    device_id: String::new(),
                }))
                .await
                .unwrap_or_else(|status| {
                    panic!("registration {attempt} should succeed, got {status:?}")
                });
            assert!(response.get_ref().success);
        }
        assert_eq!(count_users(service.db.clone()).await, 2);

        let rejection = service
            .register(Request::new(RegisterRequest {
                device_id: String::new(),
            }))
            .await
            .expect_err("the third registration must exceed the global budget");
        assert_eq!(rejection.code(), tonic::Code::ResourceExhausted);
        assert!(
            rejection.message().contains("global"),
            "the rejection must be distinguishable from the per-peer budget: {}",
            rejection.message()
        );
        assert_eq!(
            count_users(service.db.clone()).await,
            2,
            "a rejected registration must not insert a user row"
        );
    }

    #[test]
    fn config_load_rejects_malformed_numeric_env() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "").unwrap();
        let env = |name: &str| match name {
            "GRPC_PORT" => Some("abc".to_string()),
            _ => None,
        };
        let err = Config::load_from(&path, &env).unwrap_err();
        match err {
            ConfigLoadError::InvalidEnvironment { name, .. } => assert_eq!(name, "GRPC_PORT"),
            other => panic!("expected InvalidEnvironment, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_max_id_length() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.limits]\nmax_id_length = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "MAX_ID_LENGTH"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_max_device_id_length() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.limits]\nmax_device_id_length = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "MAX_DEVICE_ID_LENGTH"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_max_api_key_length() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.limits]\nmax_api_key_length = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "MAX_API_KEY_LENGTH"),
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_rejects_zero_rate_limit_per_minute() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[server.rate_limit]\nrequests_per_minute = 0\n").unwrap();
        let err = Config::load_from(&path, &|_| None).unwrap_err();
        match err {
            ConfigLoadError::InvalidRange { name, .. } => {
                assert_eq!(name, "RATE_LIMIT_PER_MINUTE")
            }
            other => panic!("expected InvalidRange, got: {other}"),
        }
    }

    #[test]
    fn config_validate_accepts_valid_boundary_values() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[server.limits]\nmax_id_length = 1\nmax_device_id_length = 1\nmax_api_key_length = 1\n[server.rate_limit]\nrequests_per_minute = 1\n",
        )
        .unwrap();
        let config = Config::load_from(&path, &|_| None).unwrap();
        assert_eq!(config.max_id_length, 1);
        assert_eq!(config.max_device_id_length, 1);
        assert_eq!(config.max_api_key_length, 1);
        assert_eq!(config.rate_limit_per_minute, 1);
    }

    #[test]
    fn authorization_scheme_is_matched_case_insensitively() {
        for scheme in ["Bearer", "bearer", "BEARER", "BeArEr"] {
            let mut request = Request::new(HealthRequest {});
            request.metadata_mut().insert(
                "authorization",
                format!("{scheme} secret-key").parse().unwrap(),
            );
            assert_eq!(
                extract_api_key(&request, ""),
                "secret-key",
                "scheme {scheme} must be accepted"
            );
        }
    }

    #[test]
    fn authorization_falls_back_to_the_body_key_for_other_schemes() {
        let mut request = Request::new(HealthRequest {});
        request
            .metadata_mut()
            .insert("authorization", "Basic dXNlcjpwYXNz".parse().unwrap());
        assert_eq!(extract_api_key(&request, "body-key"), "body-key");

        let request = Request::new(HealthRequest {});
        assert_eq!(extract_api_key(&request, "body-key"), "body-key");
    }

    fn snippet(id: &str, updated_at: i64) -> ProtoSnippet {
        ProtoSnippet {
            id: id.to_string(),
            description: format!("description {id}"),
            command: format!("echo {id}"),
            tags: vec![],
            created_at: updated_at,
            updated_at,
            device_id: "device".to_string(),
            deleted: false,
            encrypted: false,
        }
    }

    #[tokio::test]
    async fn sync_reports_a_database_failure_as_an_internal_error() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        // Fail the second insert only: if the transaction were committed the
        // first snippet would survive the failed sync.
        sqlx::query(
            "CREATE TRIGGER fail_second_insert BEFORE INSERT ON snippets \
             WHEN NEW.id = 'boom' BEGIN SELECT RAISE(ABORT, 'injected failure'); END",
        )
        .execute(service.db.pool())
        .await
        .unwrap();

        let request = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![snippet("ok-1", 100), snippet("boom", 101)],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id: String::new(),
            limit: 100,
            offset: 0,
        });

        let status = service
            .sync(request)
            .await
            .expect_err("a database failure must not be reported as a successful sync");
        assert_eq!(status.code(), tonic::Code::Internal);
        assert_eq!(
            service.metrics.db_errors_total.get(),
            1,
            "the database failure must be counted"
        );

        let stored: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM snippets")
            .fetch_one(service.db.pool())
            .await
            .unwrap();
        assert_eq!(
            stored.0, 0,
            "the failed sync must not leave a partial write behind"
        );
    }

    #[tokio::test]
    async fn sync_reports_a_database_failure_without_a_skip_count() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        sqlx::query(
            "CREATE TRIGGER fail_every_insert BEFORE INSERT ON snippets \
             BEGIN SELECT RAISE(ABORT, 'injected failure'); END",
        )
        .execute(service.db.pool())
        .await
        .unwrap();

        let request = Request::new(SyncRequest {
            api_key: api_key.clone(),
            local_snippets: vec![snippet("only", 100)],
            last_sync_timestamp: 0,
            last_sync_sequence: 0,
            library_id: String::new(),
            limit: 100,
            offset: 0,
        });

        let status = service
            .sync(request)
            .await
            .expect_err("expected an internal error");
        assert_eq!(status.code(), tonic::Code::Internal);
        // The failure is not reported as a content-level skip: the response
        // carries no snippet list at all.
        assert!(status.message().contains("Internal error"));
    }

    #[tokio::test]
    async fn sync_total_and_has_more_are_unchanged_for_a_known_dataset() {
        let service = setup_test_service().await;
        let api_key = register_test_user(&service).await;

        let library_id = service
            .create_library(Request::new(CreateLibraryRequest {
                api_key: api_key.clone(),
                name: "paging".to_string(),
            }))
            .await
            .unwrap()
            .into_inner()
            .library_id;

        let local_snippets: Vec<ProtoSnippet> = (0..5)
            .map(|index| snippet(&format!("row-{index}"), 100 + index))
            .collect();

        // First page: two of five rows, more pages follow.
        let first = service
            .sync(Request::new(SyncRequest {
                api_key: api_key.clone(),
                local_snippets,
                last_sync_timestamp: 0,
                last_sync_sequence: 0,
                library_id: library_id.clone(),
                limit: 2,
                offset: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(first.snippets.len(), 2);
        assert!(first.has_more);
        assert_eq!(first.total_count, 5);

        // Last page: the exact total is still reported.
        let last = service
            .sync(Request::new(SyncRequest {
                api_key: api_key.clone(),
                local_snippets: vec![],
                last_sync_timestamp: 0,
                last_sync_sequence: 0,
                library_id: library_id.clone(),
                limit: 2,
                offset: 4,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(last.snippets.len(), 1);
        assert!(!last.has_more);
        assert_eq!(last.total_count, 5);

        // A single page covers the whole range.
        let whole = service
            .sync(Request::new(SyncRequest {
                api_key: api_key.clone(),
                local_snippets: vec![],
                last_sync_timestamp: 0,
                last_sync_sequence: 0,
                library_id: library_id.clone(),
                limit: 100,
                offset: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(whole.snippets.len(), 5);
        assert!(!whole.has_more);
        assert_eq!(whole.total_count, 5);

        // `GetSnippets` keeps its exact total as well.
        let listed = service
            .get_snippets(Request::new(GetSnippetsRequest {
                api_key,
                library_id,
                limit: 2,
                offset: 0,
                since: 0,
            }))
            .await
            .unwrap()
            .into_inner();
        assert_eq!(listed.snippets.len(), 2);
        assert_eq!(listed.total_count, 5);
        assert!(listed.has_more);
    }
}