rstango 0.4.0

Implementation of the Tango distributed control system
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
//! A device: its interface, its model, and every request a client makes of it.

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant, SystemTime};
use std::sync::{Arc, Mutex, Weak};
use std::fmt::{self, Debug};
use std::future::Future;
use std::borrow::Cow;
use std::any::Any;

use futures::future::{join, ready, BoxFuture};
use tracing::{debug, error, info, warn};
use futures::stream::BoxStream;

use crate::dev::{All, AttrConfig, AttrInfo, AttrMemorized, AttrQuality, AttrRead, AttrReady, AttrValueEvent, CommandInfo, DevInfo, Named, NamedResult, RecordedResult, ToNames, ToNamesNotAll, 
    DevSource, DevState};
use crate::value::{IntoValue, Scalar, Spectrum, Value};
use crate::error::{reason, Error, ErrorKind, Result};
use crate::database::{GetPropSpec, SetPropSpec};
use crate::local::{self, LocalDevHandle};
use crate::name::{self, Name, ArcName};
use crate::backend::BackendDev;
use crate::pool;

use super::def::{AttrDef, CommandDef, DeleteFn, InitFn, StateFn, StatusFn, WriteFn};
use super::{reserved_name, Model, DEFAULT_HISTORY_DEPTH, DEFAULT_STATE, DEFAULT_STATUS, INIT_NAME, 
    MISSING_STATUS, RESERVED_ATTRS, RESERVED_COMMANDS, STATE_NAME, STATUS_NAME};
use super::polling::{self, PollItem, PolledHistory, PolledKind, Polled, DEFAULT_VALIDITY_PERIODS};
use super::class::{AnyClass, Class};
use super::attr::{Attr, AttrAlarm, AttrRole};
use super::command::Command;
use super::server::Server;


/// The model-erased view of a [`Dev`], which is how a server refers to the devices it
/// serves, whatever the model of the class they belong to.
pub(super) trait AnyDev: Debug + Send + Sync {

    /// The name of that device, shared so that it is cheaply copied out.
    fn name(&self) -> &Arc<str>;

    /// The class of that device.
    fn class(&self) -> &dyn AnyClass;

    /// Initialize that device: its model, if it has one, is deleted, and a new one is built
    /// by the init function of its class, on the pool of the server when that may block.
    /// This only fails when the initialization never ran to its end, its function having
    /// panicked: one that failed is kept by the device instead.
    fn init(&self) -> BoxFuture<'_, Result<()>>;

    /// Stop serving that device, for good, and delete its model, if it has one, giving it
    /// back to the delete function of its class so that it may release what it owns: what
    /// a device goes through once it is removed from its server, or when the server shuts
    /// down. Not to be confused with the deletion of the model alone, which is also what an
    /// initialization starts with, see [`Dev::init`].
    /// 
    /// The backend is told first, so that no new request reaches a device that is being
    /// deleted, see [`crate::backend::BackendServer::remove`]. A request it was answering
    /// may still be running, and the model is only deleted once it is through with it,
    /// which is why a request of that device must never wait for this.
    fn withdraw(&self) -> BoxFuture<'_, Result<()>>;

    /// Mark that device as withdrawn, see [`Dev::is_withdrawn`], and take it out of the
    /// local registry, so that no client of this process finds it anymore: the first step
    /// of [`Self::withdraw`], and all that becomes of the devices of a server that ended
    /// without being stopped.
    fn withdraw_now(&self);

    /// Start serving that device through the backend of its server, giving back the ITR it
    /// is reached at. This is quick and never blocks, see
    /// [`crate::backend::BackendServer::add`].
    fn serve(&self) -> Result<Arc<str>>;

    /// That device as [`Any`], for it to be downcast to the [`Dev`] it is.
    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;

    /// Poll those objects of that device once, which are due together, see
    /// [`super::polling`]: read the attributes, or execute the commands, as a client asking
    /// the device does, on the pool of the server when that may block, and record what
    /// each gave in its history, valid for as long as its item says. A polled attribute is
    /// also sent as a periodic event once its period has passed since the last one was
    /// sent, see [`Dev::poll_attrs`], and when the last one was sent is given back for
    /// each item, never for a command.
    ///
    /// An object the device does not have anymore is left out. This only fails when the
    /// pool dropped the poll before it ran to its end, see [`pool::run`]: a read or an
    /// execution that failed is recorded as such.
    fn poll(&self, kind: PolledKind, items: &[PollItem]) -> BoxFuture<'static, Result<Vec<Option<Instant>>>>;

    /// What the history of that object of that device holds, for its polling status, see
    /// [`PolledHistory`], absent if the device has no such object.
    fn polled_history(&self, kind: PolledKind, name: &str) -> Option<PolledHistory>;

    /// The name of that object of that device, as its definition gives it, failing if the
    /// device has no such object or if it cannot be polled, see [`Attr::is_pollable`] and
    /// [`Command::is_pollable`].
    fn check_pollable(&self, kind: PolledKind, name: &str) -> Result<Arc<str>>;

}

/// The handle to a device from within its own execution functions, giving access to the
/// device outside of its model.
/// 
/// A device can be served while having no model: until it is initialized, or when its
/// initialization failed. It is then in UNKNOWN or FAULT state, with a status describing
/// why it has no model. The idea behind this is that the Init command, which deletes then
/// initializes a device, might fail, however we don't want to stop serving the device
/// for that. This also allows a server to start if any of its devices fails to init, the
/// device will be available but it will not be usable in any way, it will just be possible
/// to call Init and try to fix it, individually from the other devices that might be
/// running.
pub struct Dev<M: Model> {
    /// Self reference, for what a device hands the backend of itself.
    this: Weak<Self>,
    /// The name of the device.
    name: Arc<str>,
    /// The class this device is an instance of, through which its definition is reached.
    class: Arc<Class<M>>,
    /// The interface of this device, see [`DevMutable`]. It is locked very shortly so 
    /// there is no need for 
    mutable: Mutex<DevMutable<M>>,
    /// The internal model of the device, absent until the device is initialized.
    /// 
    /// An asynchronous lock, held across the awaits of the asynchronous handlers.
    model: async_lock::RwLock<Option<Result<M>>>,
    /// The device recorded as served by this process while it is served, which is how a
    /// client of this process reaches it directly, see [`crate::local`].
    local_handle: Mutex<Option<LocalDevHandle>>,
    /// Set once this device is withdrawn from its server, see [`Self::is_withdrawn`].
    withdrawn: AtomicBool,
}

impl<M: Model> Dev<M> {

    pub(super) fn new(class: Arc<Class<M>>, name: Arc<str>) -> Arc<Self> {
        let state_attr = Arc::new(Attr::new_with_role(Arc::clone(&class.def().state_attr), AttrRole::State));
        let status_attr = Arc::new(Attr::new_with_role(Arc::clone(&class.def().status_attr), AttrRole::Status));
        Arc::new_cyclic(|this| Self {
            this: this.clone(),
            name,
            class,
            mutable: Mutex::new(DevMutable {
                black_box: VecDeque::new(),
                commands: HashMap::new(),
                attrs: HashMap::new(),
                state_attr,
                status_attr,
                auto_alarm_states: Arc::from([DevState::On]),
            }),
            model: async_lock::RwLock::new(None),
            local_handle: Mutex::new(None),
            withdrawn: AtomicBool::new(false),
        })
    }

    /// The name of this device.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The class this device is an instance of.
    #[inline]
    pub fn class(&self) -> &Class<M> {
        &self.class
    }

    /// The server serving this device.
    #[inline]
    pub fn server(&self) -> &Server {
        self.class.server()
    }

    /// Whether this device is gone for good: removed from its server and deleted, or its
    /// server ended. Nothing of it is served from then on, and pushing events or setting
    /// anything of its attributes fails, which is how a thread of its own learns to stop. A
    /// device added again under the same name, which is what a restart is, is another
    /// device, which this one never becomes.
    #[inline]
    pub fn is_withdrawn(&self) -> bool {
        self.withdrawn.load(Ordering::Acquire)
    }

    /// Fail once this device is withdrawn, see [`Self::is_withdrawn`].
    fn check_withdrawn(&self) -> Result<()> {
        if self.is_withdrawn() {
            return Err(Error::new(ErrorKind::DevNotConnected)
                .with_description(format!("Device {:?} is no longer served", self.name)));
        }
        Ok(())
    }

    // The properties of a device are the database's: everything below asks the database 
    // of the server for what it holds of this device, see the very same methods on
    // [`crate::database::DatabaseProxy`]. The blocking forms are for synchronous handlers, 
    // which run on the pool, and must never run in an asynchronous one.

    /// The names of the properties of this device that match the given filter.
    pub async fn list_prop_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.server().database().list_dev_prop_async(&self.name, filter).await
    }

    /// The names of the properties of this device, see [`Self::list_prop_async`].
    pub fn list_prop(&self, filter: &str) -> Result<Spectrum<str>> {
        self.server().database().list_dev_prop(&self.name, filter)
    }

    /// The properties of this device, parsed into the shape the given names ask for, see
    /// [`crate::database::DatabaseProxy::get_dev_prop`].
    pub fn get_prop_async<Spec, Names: ToNames>(&self, names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetPropSpec<Names>,
    {
        self.server().database().get_dev_prop_async::<Spec, Names>(&self.name, names)
    }

    /// The properties of this device, see [`Self::get_prop_async`].
    pub fn get_prop<Spec, Names: ToNames>(&self, names: Names) -> Result<Spec::Output>
    where
        Spec: GetPropSpec<Names>,
    {
        self.server().database().get_dev_prop::<Spec, Names>(&self.name, names)
    }

    /// Write the given properties of this device.
    pub fn set_prop_async<'a, Spec>(&'a self, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetPropSpec<'a>,
    {
        self.server().database().set_dev_prop_async(&self.name, spec)
    }

    /// Write the given properties of this device, see [`Self::set_prop_async`].
    pub fn set_prop<'a, Spec>(&'a self, spec: Spec) -> Result<()>
    where
        Spec: SetPropSpec<'a>,
    {
        self.server().database().set_dev_prop(&self.name, spec)
    }

    /// Delete the given properties of this device.
    pub fn delete_prop_async<Names: ToNamesNotAll>(&self, names: Names) -> impl Future<Output = Result<()>> + Send {
        self.server().database().delete_dev_prop_async(&self.name, names)
    }

    /// Delete the given properties of this device, see [`Self::delete_prop_async`].
    pub fn delete_prop<Names: ToNamesNotAll>(&self, names: Names) -> Result<()> {
        self.server().database().delete_dev_prop(&self.name, names)
    }

    /// This device, shared, which is how a handler, only given a reference to it, hands it
    /// to a thread of its own. Holding it does not keep it served, see
    /// [`Self::is_withdrawn`].
    #[inline]
    pub fn arc(&self) -> Arc<Self> {
        // A device is only ever reached through a reference to it, so it is alive.
        self.this.upgrade().unwrap()
    }

    /// Add a command to that device only, from its definition, which is what a device
    /// whose interface depends on its properties does at initialization; a command every
    /// device of the class has is defined on the class instead, see [`ClassDef::command`].
    /// 
    /// A name the class already defines is refused rather than shadowed: the device was
    /// given every command of its class before its initialization ran.
    /// 
    /// [`ClassDef::command`]: super::def::ClassDef::command
    pub fn add_command(&self, def: CommandDef<M>) -> Result<()> {

        // Refused rather than panicked on, unlike the same name given to a class, see
        // [`ClassDef::command`]: what a device adds to itself it usually reads from its
        // properties, so a reserved name here is a configuration to report, not a
        // definition to fix.
        if !name::check_tango_command_name(&def.name) {
            return Err(Error::new(ErrorKind::CommandNameInvalid)
                .with_description(format!("Command {:?} of device {:?} has an invalid name, it should \
                    be made of letters, digits, '_' and '-', at most 255 long", def.name, self.name)));
        }

        if let Some(reserved) = reserved_name(&def.name, RESERVED_COMMANDS) {
            return Err(Error::new(ErrorKind::CommandNameInvalid)
                .with_description(format!("Command {:?} cannot be defined on device {:?}, \
                    {reserved:?} is answered by the server itself", def.name, self.name)));
        }

        let mut mutable = self.mutable.lock().unwrap();
        if mutable.commands.contains_key(Name::new(&def.name)) {
            return Err(Error::new(ErrorKind::CommandAlreadyDefined)
                .with_description(format!("Command {:?} is already defined on device {:?}", def.name, self.name)));
        }

        let name = ArcName::from(&*def.name);
        mutable.commands.insert(name, Arc::new(Command::new(Arc::new(def))));
        Ok(())

    }

    /// Remove a command from that device, telling whether it was defined.
    pub fn remove_command(&self, name: &str) -> bool {
        self.mutable.lock().unwrap().commands.remove(Name::new(name)).is_some()
    }

    /// Add an attribute to that device only, from its definition, see
    /// [`Self::add_command`] and [`ClassDef::attr`].
    /// 
    /// An attribute added by the initialization of the device is configured from the
    /// database once the initialization returns. One added at any other time keeps the
    /// configuration of its definition.
    /// 
    /// [`ClassDef::attr`]: super::def::ClassDef::attr
    pub fn add_attr(&self, def: AttrDef<M>) -> Result<()> {

        if !name::check_tango_attr_name(&def.name) {
            return Err(Error::new(ErrorKind::AttrNameInvalid)
                .with_description(format!("Attribute {:?} of device {:?} has an invalid name, it should \
                    be made of letters, digits, '_' and '-', at most 255 long", 
                    def.name, self.name)));
        }

        if let Some(reserved) = reserved_name(&def.name, RESERVED_ATTRS) {
            return Err(Error::new(ErrorKind::AttrNameInvalid)
                .with_description(format!("Attribute {:?} cannot be defined on device {:?}, \
                    {reserved:?} is answered by the server itself", 
                    def.name, self.name)));
        }

        if let Err(err) = def.check() {
            return Err(Error::new(ErrorKind::Reason(reason::API_AttrWrongDefined))
                .with_description(format!("Attribute {:?} cannot be defined on device {:?}, {err}",
                    def.name, self.name)));
        }

        let mut mutable = self.mutable.lock().unwrap();
        if mutable.attrs.contains_key(Name::new(&def.name)) {
            return Err(Error::new(ErrorKind::AttrAlreadyDefined)
                .with_description(format!("Attribute {:?} is already defined on device {:?}", 
                    def.name, self.name)));
        }

        let name = ArcName::from(&*def.name);
        mutable.attrs.insert(name, Arc::new(Attr::new(Arc::new(def))));
        Ok(())

    }

    /// Give the attribute of that name a new set point without writing it, which every read
    /// gives back as its write value from then on, and which the database remembers if the
    /// attribute is memorized, see [`AttrMemorized`].
    /// 
    /// This is for a device whose set point changes by itself, a motor stopped short of its
    /// target for instance, so that a client and the next initialization find the value
    /// the device actually works towards. An attribute that cannot be written, the State
    /// and the Status included, is refused.
    pub async fn set_attr_w_value_async(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.check_withdrawn()?;
        let attr = self.find_attr(name)?;
        attr.set_w_value(self, value.into_value()).await
    }

    /// The blocking form of [`Self::set_attr_w_value_async`], which must never run in an
    /// asynchronous handler; it gives up after the timeout of the database of the server.
    pub fn set_attr_w_value(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.server().database().block_on(self.set_attr_w_value_async(name, value))?
    }

    /// Change the configuration of the attribute of that name, given as the whole of it,
    /// which is what a client changing it does: refused if it is incoherent, stored in the
    /// database, and pushed to the subscribers of the configuration of that attribute. Its
    /// current configuration is the one [`Attr::config`] gives.
    pub async fn set_attr_config_async(&self, name: &str, config: &AttrConfig) -> Result<()> {
        self.check_withdrawn()?;
        self.change_attr_config(name, config).await
    }

    /// The blocking form of [`Self::set_attr_config_async`], which must never run in an
    /// asynchronous handler; it gives up after the timeout of the database of the server.
    pub fn set_attr_config(&self, name: &str, config: &AttrConfig) -> Result<()> {
        self.server().database().block_on(self.set_attr_config_async(name, config))?
    }

    /// Set the states in which this device is put in ALARM when one of its attributes is in
    /// alarm, which is only [`DevState::On`] unless set otherwise, an empty list leaving
    /// the state of the device to its state function alone.
    /// 
    /// When the state function gives one of those states, the attributes that have any
    /// alarm configured are read, and a single one of them in alarm or in warning makes
    /// the device ALARM, its status telling which and why, the way cppTango does. Getting
    /// the state of the device then borrows its model the way reading those attributes
    /// does.
    pub fn set_auto_alarm_states(&self, states: &[DevState]) {
        self.mutable.lock().unwrap().auto_alarm_states = Arc::from(states);
    }

    /// Remove an attribute from that device, telling whether it was defined.
    pub fn remove_attr(&self, name: &str) -> bool {
        self.mutable.lock().unwrap().attrs.remove(Name::new(name)).is_some()
    }

    /// The command of that name on this device, absent when it has none of that name: the
    /// State, the Status and the Init every device has, whatever its class defines, or else
    /// one of its interface.
    /// 
    /// Every request on a command goes through this, and it is shared rather than borrowed
    /// from the interface store: the interface store is unlocked as soon as the command is
    /// out of it, because a handler is free to change the interface of its own device, and
    /// that store is the lock taken *under* the model, never around it.
    pub fn get_command(&self, name: &str) -> Option<Arc<Command<M>>> {
        if name.eq_ignore_ascii_case(STATE_NAME) {
            Some(Arc::new(Command::new_with_attr(self.state_attr())))
        } else if name.eq_ignore_ascii_case(STATUS_NAME) {
            Some(Arc::new(Command::new_with_attr(self.status_attr())))
        } else if name.eq_ignore_ascii_case(INIT_NAME) {
            Some(Arc::new(Command::new_with_init()))
        } else {
            self.mutable.lock().unwrap().commands.get(Name::new(name)).map(Arc::clone)
        }
    }

    /// The attribute of that name on this device, the State and the Status included,
    /// reached the way [`Self::get_command`] reaches a command.
    pub fn get_attr(&self, name: &str) -> Option<Arc<Attr<M>>> {
        let mutable = self.mutable.lock().unwrap();
        if name.eq_ignore_ascii_case(STATE_NAME) {
            Some(Arc::clone(&mutable.state_attr))
        } else if name.eq_ignore_ascii_case(STATUS_NAME) {
            Some(Arc::clone(&mutable.status_attr))
        } else {
            mutable.attrs.get(Name::new(name)).map(Arc::clone)
        }
    }

    /// Every command of this device: the three every device has first, then its whole
    /// interface.
    pub fn commands(&self) -> Vec<Arc<Command<M>>> {
        let mutable = self.mutable.lock().unwrap();
        [
            Command::new_with_attr(Arc::clone(&mutable.state_attr)), 
            Command::new_with_attr(Arc::clone(&mutable.status_attr)), 
            Command::new_with_init(),
        ]
            .into_iter()
            .map(Arc::new)
            .chain(mutable.commands.values().map(Arc::clone))
            .collect()
    }

    /// Every attribute of this device: the two every device has first, then its whole
    /// interface.
    /// 
    /// TODO: The order of the interface is the one of the interface store, which is a hash
    /// map and therefore arbitrary; a client reading a whole interface expects a stable one.
    pub fn attrs(&self) -> Vec<Arc<Attr<M>>> {
        let mutable = self.mutable.lock().unwrap();
        [&mutable.state_attr, &mutable.status_attr]
            .into_iter()
            .chain(mutable.attrs.values())
            .map(Arc::clone)
            .collect()
    }

    // The events of the attributes of this device are pushed to the subscriptions its
    // server keeps of them, see [`Server::events`]. A push never blocks and needs no
    // executor, so that it is made from anywhere, a thread of the device's own included.
    // Nothing is sent of an event no client subscribed to.

    /// Push an event of that kind for the attribute of that name, the state and the status
    /// included: a reading, or the error reading it, failing if the device has no such
    /// attribute, or if that attribute does not declare it pushes such events, see
    /// [`AttrDef::push_change_event`]. See the methods below for what a device pushes most.
    ///
    /// A reading must have a read value, so an attribute that cannot be read pushes none,
    /// and be of a valid quality for the state and the status. A reading with no write value
    /// is given the set point of its attribute, and one with a write value makes it the set
    /// point, the way a read does, so that an event and a read of a writable attribute
    /// carry the same, as with cppTango.
    pub fn push_attr_event(&self, name: &str, event: AttrValueEvent, mut read: Result<AttrRead<Value>>) -> Result<()> {
        self.check_withdrawn()?;
        let attr = self.find_attr(name)?;
        attr.check_push_event(self, event)?;
        if let Ok(read) = &mut read {
            attr.check_pushed(read)?;
            attr.merge_w_value(read);
        }
        self.server().push_attr_value(&self.name, attr.name(), event, read);
        Ok(())
    }

    /// Push a change event for the attribute of that name, a value of a valid quality read
    /// now, see [`Self::push_attr_event`].
    pub fn push_change_event(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.push_attr_event(name, AttrValueEvent::Change, Ok(read_now(value)))
    }

    /// Push an archive event for the attribute of that name, see [`Self::push_change_event`].
    pub fn push_archive_event(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.push_attr_event(name, AttrValueEvent::Archive, Ok(read_now(value)))
    }

    /// Push a user event for the attribute of that name, see [`Self::push_change_event`].
    pub fn push_user_event(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.push_attr_event(name, AttrValueEvent::User, Ok(read_now(value)))
    }

    /// Push an alarm event for the attribute of that name, see [`Self::push_change_event`].
    pub fn push_alarm_event(&self, name: &str, value: impl IntoValue) -> Result<()> {
        self.push_attr_event(name, AttrValueEvent::Alarm, Ok(read_now(value)))
    }

    /// Push that the attribute of that name is ready to be read, with a counter of the
    /// device's own telling which of its readings it is, see [`AttrReady`]. This fails if
    /// the device has no such attribute, or does not declare it announced, see
    /// [`AttrDef::push_data_ready_event`].
    pub fn push_data_ready_event(&self, name: &str, counter: i32) -> Result<()> {
        self.check_withdrawn()?;
        let attr = self.find_attr(name)?;
        attr.check_data_ready(self)?;
        let ready = AttrReady { data_kind: attr.data_kind()?, counter };
        self.server().push_attr_ready(&self.name, attr.name(), Ok(ready));
        Ok(())
    }

    /// Initialize this device: delete its model, if it has one, and build a new one with
    /// the init function of its class. A failure is kept in place of the model, reported as
    /// FAULT and in the status.
    /// 
    /// This runs when a synchronization picks the device up, and on every `Init` command.
    /// 
    /// The model is taken exclusively for the whole initialization, so that a request
    /// arriving in the middle of it waits for it rather than seeing a half built device.
    /// This is also why the init function of a class must not reach the model of the very
    /// device it is building: it is that lock it would be asking for.
    /// 
    /// The attributes are configured from the database around the init function: those of
    /// the class before it, so that it finds them configured, and those it added after it,
    /// see [`Self::load_all_attr_config`].
    pub(super) async fn init(&self) {

        let def = self.class.def();
        let mut model = self.model.write().await;

        // A device withdrawn meanwhile had its model deleted for good, which is never
        // built again: the Init command that asked for it is told so, see
        // [`Self::check_model`].
        if self.is_withdrawn() {
            return;
        }

        // An initialization is a delete-then-init, which is what the Init command of a
        // device is: a device that was running is deleted first, and a device whose
        // previous initialization failed has only that error to drop.
        self.delete_model(&mut model).await;

        // The interface goes with the model it was built for: whatever the previous
        // initialization added to this device alone is gone, and the next one is free to
        // add it again, possibly differently.
        //
        // What the class defines is put back, so that the device starts again from the
        // interface every device of its class has and its initialization only adds to it,
        // see [`Self::add_attr`].
        self.reset_interface();
        self.load_all_attr_config().await;

        let mut res = match &def.init {
            InitFn::Sync(init) => init(self),
            InitFn::Async(init) => init(self).await,
        };

        // We re-load attribute config afterward in case new attributes have been added,
        // in which case only their config will be loaded. The memorized values are then
        // written back, which needs the model.
        if let Ok(new_model) = &mut res {
            self.load_all_attr_config().await;
            for attr in self.attrs() {
                attr.restore(self, new_model).await;
            }
        }

        // Initialize, we just log the result but keep the error for state/status.
        *model = Some(match res {
            Ok(new_model) => {
                info!(dev = %self.name, class = %def.name, "Initialized the device");
                Ok(new_model)
            }
            Err(err) => {
                error!(dev = %self.name, class = %def.name, %err, "Failed to initialize the device");
                Err(err)
            }
        });

        // Whatever the initialization gave, what the device has is polled, a device that
        // failed recording the failure of every poll, as cppTango does.
        self.setup_polling().await;

    }

    /// Give the polling of the server what this device is polled for, and the histories of
    /// its attributes and commands their depth, from what the database holds for it and
    /// what its definitions ask for, see [`super::polling`] for which has the last word.
    ///
    /// A property that cannot be read is taken as absent, and an entry of it that names
    /// an object the device does not have, or one that cannot be polled, is left out, both
    /// with a warning: the device is polled for the rest all the same.
    async fn setup_polling(&self) {

        const PROPS: [&str; 6] = [
            "polled_attr", 
            "polled_cmd", 
            "poll_ring_depth", 
            "attr_poll_ring_depth", 
            "cmd_poll_ring_depth", 
            "poll_old_factor",
        ];

        let Some(poller) = self.server().poller() else {
            return;
        };

        let props = match self.server().database().get_dev_prop_async::<Spectrum<str>, _>(&self.name, PROPS).await {
            Ok(props) => props,
            Err(err) => {
                warn!(dev = %self.name, %err, "Failed to read the polling properties of the device, polling it as defined");
                PROPS.map(|_| Ok(Spectrum::<str>::from(&[] as &[&str])))
            }
        };

        let [
            polled_attr,
            polled_cmd,
            ring_depth,
            attr_depths,
            cmd_depths,
            validity_periods,
        ] = props.into_iter()
            .zip(PROPS)
            .map(|(prop, name)| prop.unwrap_or_else(|err| {
                warn!(dev = %self.name, prop = %name, %err, "Failed to read a polling property of the device, ignoring it");
                Spectrum::<str>::from(&[] as &[&str])
            }))
            .collect::<Vec<_>>()
            .try_into()
            .expect("one value per property");

        // The depths of the histories, of every attribute and command whether polled or
        // not, a device being free to record in them itself.
        let ring_depth = first_number(&self.name, PROPS[2], &ring_depth).unwrap_or(DEFAULT_HISTORY_DEPTH);
        let validity_periods = first_number(&self.name, PROPS[5], &validity_periods)
            .filter(|&factor| factor > 0)
            .unwrap_or(DEFAULT_VALIDITY_PERIODS);

        let attr_depths = polling::parse_depths(&self.name, PROPS[3], attr_depths.iter()).into_iter()
            .map(|(name, depth)| (ArcName::from(name), depth))
            .collect::<HashMap<_, _>>();
        let cmd_depths = polling::parse_depths(&self.name, PROPS[4], cmd_depths.iter()).into_iter()
            .map(|(name, depth)| (ArcName::from(name), depth))
            .collect::<HashMap<_, _>>();

        let (attrs, commands) = (self.attrs(), self.commands());

        for attr in &attrs {
            attr.set_history_depth(attr_depths.get(Name::new(attr.name())).copied().unwrap_or(ring_depth));
        }

        // The State and the Status have the history of their attribute, which their
        // command only gives a depth of its own when the property names it.
        for command in &commands {
            match cmd_depths.get(Name::new(command.name())) {
                Some(&depth) => command.set_history_depth(depth),
                None if !command.involves_state() => command.set_history_depth(ring_depth),
                None => {}
            }
        }

        // The periods, the database first, then the definitions for what it does not list.
        let mut polled = Vec::new();
        for (kind, prop) in [(PolledKind::Attr, &polled_attr), (PolledKind::Command, &polled_cmd)] {

            let prop_name = match kind {
                PolledKind::Attr => PROPS[0],
                PolledKind::Command => PROPS[1],
            };

            let mut listed = HashSet::new();
            for (name, period) in polling::parse_periods(&self.name, prop_name, prop.iter()) {
                match self.check_pollable(kind, name) {
                    Ok(name) => {
                        listed.insert(ArcName::from(Arc::clone(&name)));
                        polled.push(Polled { kind, name, period });
                    }
                    Err(err) => warn!(dev = %self.name, prop = %prop_name, %name, %err, "Ignored a polled object"),
                }
            }

            let defined = match kind {
                PolledKind::Attr => attrs.iter()
                    .filter_map(|attr| attr.poll_period().map(|period| (attr.name(), period)))
                    .collect::<Vec<_>>(),
                PolledKind::Command => commands.iter()
                    .filter_map(|command| command.poll_period().map(|period| (command.name(), period)))
                    .collect::<Vec<_>>(),
            };

            for (name, period) in defined {
                if !listed.contains(Name::new(name)) {
                    polled.push(Polled { kind, name: Arc::from(name), period: period.max(polling::MIN_PERIOD) });
                }
            }

        }

        debug!(dev = %self.name, polled = polled.len(), "Polling the device");
        poller.set_dev(&(self.arc() as Arc<dyn AnyDev>), validity_periods, polled);

    }

    /// Poll those attributes, see [`AnyDev::poll`]: read at once, as a client reading
    /// them together does, see [`BackendDev::read_attr`], each reading recorded in the
    /// history of its attribute and sent as a periodic event, see [`Self::record_poll`].
    fn poll_attrs(self: Arc<Self>, items: &[PollItem]) -> BoxFuture<'static, Result<Vec<Option<Instant>>>> {

        let mut last_periodics = items.iter()
            .map(|item| item.last_periodic)
            .collect::<Vec<_>>();

        // A device withdrawn meanwhile is not polled anymore, see [`Self::is_withdrawn`].
        if self.is_withdrawn() {
            return Box::pin(ready(Ok(last_periodics)));
        }

        // Each attribute along with the index of its item.
        let mut polled = Vec::new();
        for (index, item) in items.iter().enumerate() {
            match self.find_attr(&item.name) {
                Ok(attr) => polled.push((index, attr, item.valid_for)),
                Err(err) => debug!(dev = %self.name, attr = %item.name, %err, "Failed to poll the attribute"),
            }
        }

        if polled.is_empty() {
            return Box::pin(ready(Ok(last_periodics)));
        }

        let targets = polled.iter()
            .map(|(_, attr, _)| Ok(Arc::clone(attr)))
            .collect::<Vec<_>>();

        let ctx = ReadCtx::new(&self, polled.iter().any(|(_, attr, _)| attr.role() != AttrRole::Interface));
        let blocking = polled.iter().any(|(_, attr, _)| attr.read_may_block(&self, &ctx));

        pool::run(blocking, async move {

            // A request that failed as a whole, the device having no model for instance, is
            // the failure of every reading.
            let mut reads = self.exec_read_attr(targets, ctx, DevSource::Dev).await
                .map(Vec::into_iter);

            for (index, attr, valid_for) in polled {
                let read = match &mut reads {
                    Ok(reads) => reads.next().expect("every attribute is read").value,
                    Err(err) => Err(err.clone()),
                };
                last_periodics[index] = self.record_poll(&attr, read, valid_for, last_periodics[index]);
            }

            Ok(last_periodics)

        })

    }

    /// Record that reading of that attribute polled in its history, valid for that long,
    /// and send it as a periodic event once the period of that event has passed since the
    /// last one was, see [`crate::dev::AttrPeriodicEventConfig`], giving back when the
    /// last one was sent. A read that failed is both recorded and sent as the error it
    /// failed with.
    fn record_poll(&self, attr: &Attr<M>, read: Result<AttrRead<Value>>, valid_for: Duration, last_periodic: Option<Instant>) -> Option<Instant> {

        let read = read.and_then(|read| attr.check_pushed(&read).map(|()| read));

        if let Err(err) = attr.push_history(read.clone(), Some(valid_for)) {
            debug!(dev = %self.name, attr = %attr.name(), %err, "Failed to record the attribute polled");
        }

        let now = Instant::now();
        let period = attr.config().periodic_event.period.unwrap_or(polling::DEFAULT_PERIODIC_EVENT_PERIOD);
        if last_periodic.is_some_and(|last| now.duration_since(last) < period.mul_f64(polling::PERIODIC_EVENT_TOLERANCE)) {
            return last_periodic;
        }

        let read = read.map(|mut read| {
            attr.merge_w_value(&mut read);
            read
        });

        self.server().push_attr_value(&self.name, attr.name(), AttrValueEvent::Periodic, read);
        Some(now)

    }

    /// Poll those commands, see [`AnyDev::poll`]: executed together, with no argument,
    /// see [`Self::exec_many_command`], each result recorded in the history of its command.
    /// A command sends no periodic event, so none was ever sent.
    fn poll_commands(self: Arc<Self>, items: &[PollItem]) -> BoxFuture<'static, Result<Vec<Option<Instant>>>> {

        let none = vec![None; items.len()];

        // A device withdrawn meanwhile is not polled anymore, see [`Self::is_withdrawn`].
        if self.is_withdrawn() {
            return Box::pin(ready(Ok(none)));
        }

        // Each command along with how long what it gives is valid for.
        let mut polled = Vec::new();
        for item in items {
            match self.find_command(&item.name) {
                Ok(command) => polled.push((command, item.valid_for)),
                Err(err) => debug!(dev = %self.name, command = %item.name, %err, "Failed to poll the command"),
            }
        }

        if polled.is_empty() {
            return Box::pin(ready(Ok(none)));
        }

        let targets = polled.iter()
            .map(|(command, _)| (Ok(Arc::clone(command)), Value::Void))
            .collect::<Vec<_>>();

        let ctx = ReadCtx::new(&self, polled.iter().any(|(command, _)| command.involves_state()));
        let blocking = polled.iter().any(|(command, _)| command.may_block(&self, &ctx));

        pool::run(blocking, async move {

            // A request that failed as a whole is the failure of every command.
            let mut results = self.exec_many_command(targets, ctx, DevSource::Dev).await
                .map(Vec::into_iter);

            for (command, valid_for) in polled {
                let res = match &mut results {
                    Ok(results) => results.next().expect("every command is executed").value,
                    Err(err) => Err(err.clone()),
                };
                if let Err(err) = command.push_history(res, Some(valid_for)) {
                    debug!(dev = %self.name, command = %command.name(), %err, "Failed to record the command polled");
                }
            }

            Ok(none)

        })

    }

    /// Delete the model of this device, if it has one, giving it back to the delete
    /// function of its class so that it may release what it owns, taking the model
    /// already locked so that [`Self::init`] can delete and initialize under a single
    /// lock.
    /// 
    /// The device itself keeps existing, with no model, until it is initialized again:
    /// every request needing the model fails until then, but its state and its status
    /// still answer, saying why it has none, see [`Self::no_model_answer`].
    async fn delete_model(&self, model: &mut Option<Result<M>>) {

        // Only a model that was actually built is deleted: the error of a failed
        // initialization is dropped, there being nothing to give back.
        let Some(Ok(prev)) = model.take() else {
            return;
        };

        let def = self.class.def();
        debug!(dev = %self.name, class = %def.name, "Deleting the model of the device");

        match &def.delete {
            Some(DeleteFn::Sync(delete)) => delete(prev, self),
            Some(DeleteFn::Async(delete)) => delete(prev, self).await,
            None => {}
        }

    }

    /// Give this device the interface of its class and nothing else, dropping whatever it
    /// had added to its own: what a device starts every initialization from, and therefore
    /// what it has no part of until it is initialized once.
    fn reset_interface(&self) {

        let def = self.class.def();
        let mut mutable = self.mutable.lock().unwrap();

        mutable.commands.clear();
        mutable.attrs.clear();
        mutable.state_attr = Arc::new(Attr::new_with_role(Arc::clone(&def.state_attr), AttrRole::State));
        mutable.status_attr = Arc::new(Attr::new_with_role(Arc::clone(&def.status_attr), AttrRole::Status));

        for def in &def.commands {
            let name = ArcName::from(&*def.name);
            mutable.commands.insert(name, Arc::new(Command::new(Arc::clone(def))));
        }

        for def in &def.attrs {
            let name = ArcName::from(&*def.name);
            mutable.attrs.insert(name, Arc::new(Attr::new(Arc::clone(def))));
        }

    }

    /// Configure every attribute of this device that is not yet from what the database holds
    /// for its class and for this device, both asked at once, see [`Attr::load_config`].
    /// 
    /// A request that fails does not fail the device: it is kept as the error of every
    /// attribute it was for, which a client finds out reading any of them.
    async fn load_all_attr_config(&self) {

        // Find all attributes that are not yet loaded from the database, the State and the
        // Status included.
        let attrs = {
            let mutable = self.mutable.lock().unwrap();
            [&mutable.state_attr, &mutable.status_attr]
                .into_iter()
                .chain(mutable.attrs.values())
                .filter(|attr| !attr.is_loaded())
                .map(Arc::clone)
                .collect::<Vec<_>>()
        };

        self.load_given_attr_config(&attrs).await;

    }

    /// Configure those attributes from what the database holds for them, see
    /// [`Self::load_all_attr_config`].
    async fn load_given_attr_config(&self, attrs: &[Arc<Attr<M>>]) {

        if attrs.is_empty() {
            return;
        }

        // Now we collect the names of the attributes.
        let names = attrs
            .iter()
            .map(|attr| attr.name())
            .collect::<Vec<_>>();

        // Waiting on both class attr properties and dev attr properties.
        let (
            class_props, 
            dev_props,
        ) = join(
            self.class.attr_props(&names), 
            self.server()
                .database()
                .get_dev_attr_prop_async::<Spectrum<str>, _, _>(&self.name, names.as_slice(), All),
        ).await;

        let dev_props = dev_props.and_then(|props| props
                .into_iter()
                .collect::<Result<Vec<_>>>());

        for (index, attr) in attrs.iter().enumerate() {
            attr.load_config(self,
                class_props.as_ref().map(|props| &*props[index]),
                dev_props.as_ref().map(|props| &*props[index]));
        }

    }

    /// What a device that has no model answers for an attribute or a command of that role,
    /// given the error its initialization failed with, if it failed at all: the State and
    /// the Status say what the device is, the FAULT of a failed initialization along with
    /// the error it failed with, which is what keeping that error is for, or the UNKNOWN of
    /// a device that has not been initialized yet along with saying so. Everything else
    /// fails with why the device has no model, see [`init_err`].
    fn no_model_answer(&self, role: AttrRole, failure: Option<&Error>) -> Result<Value> {
        match (role, failure) {
            (AttrRole::State, Some(_)) => Ok(DevState::Fault.into()),
            (AttrRole::State, None) => Ok(DevState::Unknown.into()),
            (AttrRole::Status, Some(err)) => Ok(make_failed_status(err).into()),
            (AttrRole::Status, None) => Ok(Scalar::from(MISSING_STATUS).into()),
            (AttrRole::Interface, _) => Err(init_err(failure, &self.name)),
        }
    }

    /// The state of the device derived from its model, which is already borrowed with the
    /// access [`Self::state_access`] asked for, which is how its State attribute is read,
    /// see [`Attr::read`], so that a request reading the state among other attributes
    /// derives it under the same borrow as the rest of them.
    /// 
    /// The state the state function gives is ALARM when an attribute is in alarm, see
    /// [`Self::set_auto_alarm_states`].
    pub(super) async fn model_state(&self, model: &mut ModelRef<'_, M>, ctx: &mut ReadCtx<M>) -> Result<DevState> {
        let state = self.model_state_inner(model, ctx).await?;
        if self.attrs_in_alarm(ctx, state, model, false).await.is_empty() {
            Ok(state)
        } else {
            Ok(DevState::Alarm)
        }
    }

    /// The counterpart of [`Self::model_state`] for the status of the device, which tells
    /// every attribute in alarm after what the status function gives.
    pub(super) async fn model_status(&self, model: &mut ModelRef<'_, M>, ctx: &mut ReadCtx<M>) -> Result<Scalar<str>> {

        let status = match &self.class.def().status {
            Some(StatusFn::SharedSync(func)) => func(model.shared(), self),
            Some(StatusFn::ExclusiveSync(func)) => func(model.exclusive()?, self),
            Some(StatusFn::SharedAsync(func)) => func(model.shared(), self).await,
            Some(StatusFn::ExclusiveAsync(func)) => func(model.exclusive()?, self).await,
            None => Ok(Scalar::from(DEFAULT_STATUS)),
        }?;

        if !ctx.has_alarm() {
            return Ok(status);
        }

        let state = self.model_state_inner(model, ctx).await?;
        let alarms = self.attrs_in_alarm(ctx, state, model, true).await;
        if alarms.is_empty() {
            return Ok(status);
        }

        let mut status = status.value().to_owned();
        for (attr, alarm) in alarms {
            status.push('\n');
            status.push_str(&alarm.describe(attr.name()));
        }

        Ok(Scalar::from(status.as_str()))

    }

    /// The state the state function of the class gives, see [`Self::model_state`], called
    /// once for the whole request, see [`ReadCtx::state`].
    async fn model_state_inner(&self, model: &mut ModelRef<'_, M>, ctx: &mut ReadCtx<M>) -> Result<DevState> {

        if let Some(state) = ctx.state {
            return Ok(state);
        }

        let state = match &self.class.def().state {
            Some(StateFn::SharedSync(func)) => func(model.shared(), self),
            Some(StateFn::ExclusiveSync(func)) => func(model.exclusive()?, self),
            Some(StateFn::SharedAsync(func)) => func(model.shared(), self).await,
            Some(StateFn::ExclusiveAsync(func)) => func(model.exclusive()?, self).await,
            None => Ok(DEFAULT_STATE),
        }?;

        ctx.state = Some(state);
        Ok(state)

    }

    /// The attributes in alarm, with the alarm each is in, when the state function gave
    /// a state that alarms put the device in ALARM in, see [`Self::set_auto_alarm_states`].
    /// Only the first is looked for unless every one is asked for.
    /// 
    /// An attribute the request already read is not read again, see [`AlarmAttr::read`].
    async fn attrs_in_alarm(&self, ctx: &mut ReadCtx<M>, state: DevState, model: &mut ModelRef<'_, M>, every: bool) -> Vec<(Arc<Attr<M>>, AttrAlarm)> {

        let mut found = Vec::new();
        if !ctx.may_alarm(state) {
            return found;
        }

        // Taken out of the context while its attributes are read with it: none of them is
        // the State nor the Status, so none of their reads looks at it.
        let mut alarm_ctx = ctx.alarm.take();
        for alarm_attr in alarm_ctx.iter_mut().flat_map(|alarm| &mut alarm.attrs) {

            let alarm = match alarm_attr.read {
                Some(alarm) => alarm,
                None => {
                    
                    // The attribute hasn't been read in the request, so we read it here
                    // just to know its alarm state, we ignore the value! Like cppTango
                    // does for a polled attribute, its latest reading recorded is used
                    // when there is one, whatever the source of the request.
                    let alarm = alarm_attr.attr.read_with_alarm(self, model, ctx, DevSource::CacheDev).await
                        .ok()
                        .and_then(|(_, alarm)| alarm);

                    alarm_attr.read = Some(alarm);
                    alarm
                    
                }
            };

            if let Some(alarm) = alarm {
                found.push((Arc::clone(&alarm_attr.attr), alarm));
                if !every {
                    break;
                }
            }

        }

        ctx.alarm = alarm_ctx;
        found

    }

    /// The access deriving the state of the device needs to its model, which reads the
    /// attributes that may put it in ALARM as well.
    pub(super) fn state_access(&self, ctx: &ReadCtx<M>) -> Access {
        let access = match &self.class.def().state {
            Some(StateFn::ExclusiveSync(_) | StateFn::ExclusiveAsync(_)) => Access::Exclusive,
            _ => Access::Shared,
        };
        access.merge(ctx.access(self))
    }

    /// The access deriving the status of the device needs to its model, which derives its
    /// state as well when the attributes may put it in ALARM.
    pub(super) fn status_access(&self, ctx: &ReadCtx<M>) -> Access {
        let access = match &self.class.def().status {
            Some(StatusFn::ExclusiveSync(_) | StatusFn::ExclusiveAsync(_)) => Access::Exclusive,
            _ => Access::Shared,
        };
        if ctx.has_alarm() { access.merge(self.state_access(ctx)) } else { access }
    }

    /// Whether initializing this device may block, its init function or its delete
    /// function being synchronous, see [`pool::run`].
    /// 
    /// The memorized values the initialization writes back count too, though only those of
    /// the attributes of the class are known beforehand.
    pub(super) fn init_may_block(&self) -> bool {
        let def = self.class.def();
        matches!(def.init, InitFn::Sync(_)) || self.delete_may_block() || def.attrs.iter().any(|attr| {
            attr.memorized == Some(AttrMemorized::RestoreAndWrite)
                && matches!(attr.write, Some(WriteFn::SharedSync(_) | WriteFn::ExclusiveSync(_)))
        })
    }

    /// Whether deleting the model of this device may block, its delete function being
    /// synchronous, see [`pool::run`].
    fn delete_may_block(&self) -> bool {
        matches!(self.class.def().delete, Some(DeleteFn::Sync(_)))
    }

    /// Whether deriving the state of this device may block, see [`pool::run`], reading
    /// the attributes that may put it in ALARM included.
    pub(super) fn state_may_block(&self, ctx: &ReadCtx<M>) -> bool {
        matches!(&self.class.def().state, Some(StateFn::SharedSync(_) | StateFn::ExclusiveSync(_)))
            || ctx.may_block(self)
    }

    /// Whether deriving the status of this device may block, see [`pool::run`], deriving
    /// its state included when the attributes may put it in ALARM.
    pub(super) fn status_may_block(&self, ctx: &ReadCtx<M>) -> bool {
        matches!(&self.class.def().status, Some(StatusFn::SharedSync(_) | StatusFn::ExclusiveSync(_)))
            || (ctx.has_alarm() && self.state_may_block(ctx))
    }

    /// Lock the model of this device with the given access, whether it has one or not.
    async fn lock(&self, access: Access) -> ModelGuard<'_, M> {
        match access {
            Access::Shared => ModelGuard::Shared(self.model.read().await),
            Access::Exclusive => ModelGuard::Exclusive(self.model.write().await),
        }
    }

    /// Lock the model of this device with the given access, which is how every request
    /// that needs the model reaches it.
    /// 
    /// A device that has no model fails instead: with the error of its failed
    /// initialization, so that the caller is told the actual cause, or with
    /// [`ErrorKind::DevNotConnected`] when it has not been initialized yet.
    pub(super) async fn lock_model(&self, access: Access) -> Result<ModelGuard<'_, M>> {
        let guard = self.lock(access).await;
        match guard.get() {
            Some(Ok(_)) => Ok(guard),
            Some(Err(err)) => Err(init_err(Some(err), &self.name)),
            None => Err(init_err(None, &self.name)),
        }
    }

    /// Fail if this device has no model to serve a request with, with the error saying
    /// why: what a request that does not itself need the model answers with.
    pub(super) async fn check_model(&self) -> Result<()> {
        match &*self.model.read().await {
            Some(Ok(_)) => Ok(()),
            Some(Err(err)) => Err(init_err(Some(err), &self.name)),
            None => Err(init_err(None, &self.name)),
        }
    }

    /// The command of that name, see [`Self::get_command`], and the error a client is
    /// answered with when the device has no command of that name.
    fn find_command(&self, name: &str) -> Result<Arc<Command<M>>> {
        self.get_command(name)
            .ok_or_else(|| Error::new(ErrorKind::CommandNotFound)
                .with_description(format!("Command {name:?} is not defined on device {:?}", self.name)))
    }

    /// The counterpart of [`Self::find_command`] for the attributes.
    fn find_attr(&self, name: &str) -> Result<Arc<Attr<M>>> {
        self.get_attr(name)
            .ok_or_else(|| Error::new(ErrorKind::AttrNotFound)
                .with_description(format!("Attribute {name:?} is not defined on device {:?}", self.name)))
    }

    /// The State attribute of this device, kept out of its interface, which reads the state
    /// through the state function of its class, see [`Self::model_state`].
    fn state_attr(&self) -> Arc<Attr<M>> {
        Arc::clone(&self.mutable.lock().unwrap().state_attr)
    }

    /// The Status attribute of this device, see [`Self::state_attr`].
    fn status_attr(&self) -> Arc<Attr<M>> {
        Arc::clone(&self.mutable.lock().unwrap().status_attr)
    }

    /// The attributes of the given names, or every one when none is given, resolved before
    /// the model is borrowed, since resolving one locks the interface store. A name that
    /// resolves to nothing only fails that one attribute: the others are still answered.
    fn attr_targets(&self, names: Option<Spectrum<str>>) -> Vec<Resolved<Arc<Attr<M>>>> {
        match names {
            Some(names) => scalars(&names)
                .map(|name| {
                    let target = self.find_attr(name.value());
                    resolved(name, target)
                })
                .collect(),
            None => self.attrs().into_iter().map(Ok).collect(),
        }
    }

    /// The counterpart of [`Self::attr_targets`] for the commands.
    fn command_targets(&self, names: Option<Spectrum<str>>) -> Vec<Resolved<Arc<Command<M>>>> {
        match names {
            Some(names) => scalars(&names)
                .map(|name| {
                    let target = self.find_command(name.value());
                    resolved(name, target)
                })
                .collect(),
            None => self.commands().into_iter().map(Ok).collect(),
        }
    }

    /// Execute a command, resolved beforehand, see [`BackendDev::command`]: under its own
    /// borrow of the model, as [`Self::exec_many_command`] executes several, a device that
    /// has no model answering the same, see [`Self::no_model_answer`]. The Init is executed
    /// apart, since it rebuilds the model rather than borrowing it, see [`Self::init`].
    async fn exec_command(&self, target: Result<Arc<Command<M>>>, input: Value, mut ctx: ReadCtx<M>, source: DevSource) -> Result<Value> {

        // A device whose initialization failed only has what its class defines, so a name
        // it does not have may well be one it would have had: its own failure is what a
        // client needs to hear then, not that the name is unknown.
        let command = match target {
            Ok(command) => command,
            Err(err) => return Err(self.check_model().await.err().unwrap_or(err)),
        };

        // The Init is never answered from the cache, and an initialization that failed is a
        // failed Init: the device keeps that error to report it in its status, and the
        // client that asked for the initialization is given it too.
        if command.is_init() {

            if source == DevSource::Cache {
                return Err(command.not_polled_err(self));
            }

            self.init().await;
            self.check_model().await?;
            return Ok(Value::Void);

        }

        let mut guard = self.lock(command.exec_access(self, &ctx)).await;
        if let Some(failure) = guard.failure() {
            return self.no_model_answer(command.attr_role(), failure.as_ref());
        }

        command.exec(self, &mut guard.model(), input, &mut ctx, source).await

    }

    /// Execute commands, resolved beforehand, each with its argument, under a single borrow
    /// of the model, exclusive as soon as one of the execution functions asks for it: the
    /// counterpart for commands of [`Self::exec_read_attr`], which is how the commands
    /// polled together are executed, see [`Self::poll_commands`]. A single command is
    /// executed the same way, without the batch, see [`Self::exec_command`].
    ///
    /// The Init cannot be among them, see [`Self::exec_command`].
    async fn exec_many_command(&self, targets: Vec<(Resolved<Arc<Command<M>>>, Value)>, mut ctx: ReadCtx<M>, source: DevSource) -> Result<Vec<NamedResult<Value>>> {

        let access = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .fold(Access::Shared, |access, command| access.merge(command.exec_access(self, &ctx)));

        let mut guard = self.lock(access).await;

        // A device that has no model answers each command on its own, see
        // [`Self::no_model_answer`], as a multiple read does.
        if let Some(failure) = guard.failure() {
            return Ok(targets.into_iter()
                .map(|(target, _)| match target {
                    Ok(command) => Named::new(Scalar::from(command.name()), self.no_model_answer(command.attr_role(), failure.as_ref())),
                    Err(unresolved) => unresolved.map(Err),
                })
                .collect());
        }

        let mut model = guard.model();
        let mut results = Vec::with_capacity(targets.len());

        for (target, input) in targets {
            results.push(match target {
                Ok(command) => {
                    let res = command.exec(self, &mut model, input, &mut ctx, source).await;
                    Named::new(Scalar::from(command.name()), res)
                }
                Err(unresolved) => unresolved.map(Err),
            });
        }

        Ok(results)

    }

    /// Read attributes, resolved beforehand, see [`BackendDev::read_attr`].
    async fn exec_read_attr(&self, targets: Vec<Resolved<Arc<Attr<M>>>>, mut ctx: ReadCtx<M>, source: DevSource) -> Result<Vec<NamedResult<AttrRead<Value>>>> {

        // They are all read under a single borrow of the model, which is what makes the
        // values of a multiple read consistent with each other, and that borrow is
        // exclusive as soon as one of the read functions asks for it.
        let access = targets.iter()
            .filter_map(|target| target.as_ref().ok())
            .fold(Access::Shared, |access, attr| access.merge(attr.read_access(self, &ctx)));

        let mut guard = self.lock(access).await;

        // A device that has no model answers each attribute on its own, see
        // [`Self::no_model_answer`]: a client reading the State of a broken device is told
        // it is broken, and why, not that the request failed.
        if let Some(failure) = guard.failure() {
            return Ok(targets.into_iter()
                .map(|target| match target {
                    Ok(attr) => Named::new(Scalar::from(attr.name()), self.no_model_answer(attr.role(), failure.as_ref()).map(read_now)),
                    Err(unresolved) => unresolved.map(Err),
                })
                .collect());
        }

        // The attributes are read first and the state and the status derived after them, so
        // that an attribute that may put the device in ALARM is read once, its reading being
        // what the state is derived from, see [`ReadCtx::record`]. Each is answered where it
        // was asked for all the same.
        let mut model = guard.model();
        let mut reads = vec![const { None }; targets.len()];

        for interface in [true, false] {
            for (target, slot) in targets.iter().zip(&mut reads) {
                if let Ok(attr) = target
                && (attr.role() == AttrRole::Interface) == interface {
                    let read = attr.read_with_alarm(self, &mut model, &mut ctx, source).await;
                    ctx.record(attr, read.as_ref().ok().and_then(|(_, alarm)| *alarm));
                    *slot = Some(Named::new(Scalar::from(attr.name()), read.map(|(read, _)| read)));
                }
            }
        }

        for (target, slot) in targets.into_iter().zip(&mut reads) {
            if let Err(unresolved) = target {
                *slot = Some(unresolved.map(Err));
            }
        }

        Ok(reads.into_iter().map(|read| read.expect("every target is read")).collect())

    }

    /// Write attributes, resolved beforehand, see [`BackendDev::write_attr`].
    async fn exec_write_attr(&self, targets: Vec<(Result<Arc<Attr<M>>>, Value)>) -> Result<Vec<Result<()>>> {

        // Written under a single borrow of the model, so that a client writing several
        // attributes at once has them written together.
        let access = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .fold(Access::Shared, |access, attr| access.merge(attr.write_access()));

        let mut guard = self.lock_model(access).await?;
        let mut model = guard.model();

        let mut writes = Vec::with_capacity(targets.len());
        for (target, value) in targets {
            writes.push(match target {
                Ok(attr) => attr.write(self, &mut model, value).await,
                Err(err) => Err(err),
            });
        }

        Ok(writes)

    }

    /// Change the configuration of attributes, each given as the whole configuration it is
    /// to have, see [`BackendDev::set_attr_config`].
    /// 
    /// Every attribute is changed on its own, one failing leaving the others to be changed:
    /// on the device first, and then in the database, the way cppTango does.
    async fn exec_set_attr_config(&self, configs: Vec<Named<AttrConfig>>) -> Vec<Result<()>> {
        let mut results = Vec::with_capacity(configs.len());
        for Named { name, value } in configs {
            results.push(self.change_attr_config(name.value(), &value).await);
        }
        results
    }

    /// Change the configuration of one attribute, see [`Self::exec_set_attr_config`].
    /// 
    /// A change the database fails to store is the one the device has all the same, until
    /// it is configured from the database again, and is therefore pushed all the same.
    async fn change_attr_config(&self, name: &str, config: &AttrConfig) -> Result<()> {

        let attr = self.find_attr(name)?;
        let class_props = self.class.attr_props(&[attr.name()]).await?;
        let changes = attr.change_config(&class_props[0], config)
            .map_err(|err| Error::new(ErrorKind::Reason(reason::API_IncoherentValues))
                .with_description(format!("Configuration of attribute {:?} of device {:?} \
                    cannot be changed, {err}", attr.name(), self.name)))?;

        if changes.is_empty() {
            return Ok(());
        }

        self.server().push_attr_config(&self.name, attr.name(), attr.info());

        let database = self.server().database();

        if !changes.put.is_empty() {
            let put = changes.put.into_iter()
                .map(|(prop, values)| (prop.name(), values))
                .collect::<Vec<_>>();
            database.set_dev_attr_prop_async(&self.name, (attr.name(), put)).await?;
        }

        if !changes.del.is_empty() {
            let del = changes.del.iter().map(|prop| prop.name()).collect::<Vec<_>>();
            database.delete_dev_attr_prop_async(&self.name, attr.name(), del.as_slice()).await?;
        }

        Ok(())

    }

    /// Write then read back attributes, resolved beforehand, see
    /// [`BackendDev::write_read_attr`].
    async fn exec_write_read_attr(&self, targets: Vec<(Resolved<Arc<Attr<M>>>, Value)>, mut ctx: ReadCtx<M>) -> Result<Vec<NamedResult<AttrRead<Value>>>> {

        // Every value is written and read back under a single borrow of the model, which is
        // the whole point of asking for the two together: what a client is given is what the
        // device had right after its write, with nothing of anyone else in between.
        let access = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .fold(Access::Shared, |access, attr| access.merge(attr.write_access()).merge(attr.read_access(self, &ctx)));

        let mut guard = self.lock_model(access).await?;
        let mut model = guard.model();

        let mut reads = Vec::with_capacity(targets.len());
        for (target, value) in targets {
            reads.push(match target {
                // A write that failed is not read back: what a client gets of that
                // attribute is the reason its write was refused.
                Ok(attr) => {
                    let read = match attr.write(self, &mut model, value).await {
                        Ok(()) => attr.read(self, &mut model, &mut ctx, DevSource::Dev).await,
                        Err(err) => Err(err),
                    };
                    Named::new(Scalar::from(attr.name()), read)
                }
                Err(unresolved) => unresolved.map(Err),
            });
        }

        Ok(reads)

    }
}

impl<M: Model> AnyDev for Dev<M> {

    #[inline]
    fn name(&self) -> &Arc<str> {
        &self.name
    }

    #[inline]
    fn class(&self) -> &dyn AnyClass {
        &*self.class
    }

    fn init(&self) -> BoxFuture<'_, Result<()>> {
        let dev = self.arc();
        pool::run(self.init_may_block(), async move {
            dev.init().await;
            Ok(())
        })
    }

    fn withdraw(&self) -> BoxFuture<'_, Result<()>> {
        let dev = self.arc();
        Box::pin(async move {

            // Out of reach of the clients of this process first, as of the others next.
            dev.withdraw_now();
            if let Some(backend) = dev.server().backend() {
                backend.remove(&dev.name);
            }

            pool::run(dev.delete_may_block(), async move {
                dev.delete_model(&mut *dev.model.write().await).await;
                Ok(())
            }).await

        })
    }

    fn withdraw_now(&self) {
        self.withdrawn.store(true, Ordering::Release);
        self.local_handle.lock().unwrap().take();
        if let Some(poller) = self.server().poller() {
            poller.remove_dev(self);
        }
    }

    fn serve(&self) -> Result<Arc<str>> {
        let backend = self.server().backend_checked()?;
        let dev = DevImpl::from_arc(self.arc()) as Arc<dyn BackendDev>;
        let itr = backend.add(&self.name, Arc::clone(&dev))?;
        if self.server().local {
            let local_handle = local::register(&dev, Arc::clone(&itr), backend.host(), backend.port(), Arc::clone(&self.name));
            *self.local_handle.lock().unwrap() = Some(local_handle);
        }
        Ok(itr)
    }

    #[inline]
    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
        self
    }

    fn poll(&self, kind: PolledKind, items: &[PollItem]) -> BoxFuture<'static, Result<Vec<Option<Instant>>>> {
        match kind {
            PolledKind::Attr => self.arc().poll_attrs(items),
            PolledKind::Command => self.arc().poll_commands(items),
        }
    }

    fn polled_history(&self, kind: PolledKind, name: &str) -> Option<PolledHistory> {

        /// How many of the latest results the polling status tells the times of.
        const RECORDS: usize = 5;

        let (depth, entries) = match kind {
            PolledKind::Attr => {
                let attr = self.get_attr(name)?;
                let entries = attr.history(RECORDS).into_iter()
                    .map(|entry| (entry.time, entry.value.err()))
                    .collect::<Vec<_>>();
                (attr.history_depth(), entries)
            }
            PolledKind::Command => {
                let command = self.get_command(name)?;
                let entries = command.history(RECORDS).into_iter()
                    .map(|entry| (entry.time, entry.value.err()))
                    .collect::<Vec<_>>();
                (command.history_depth(), entries)
            }
        };

        let failure = entries.last().and_then(|(_, err)| err.clone());
        Some(PolledHistory {
            depth,
            times: entries.into_iter().map(|(time, _)| time).collect(),
            failure,
        })

    }

    fn check_pollable(&self, kind: PolledKind, name: &str) -> Result<Arc<str>> {
        match kind {
            PolledKind::Attr => {
                let attr = self.find_attr(name)?;
                if !attr.is_pollable() {
                    return Err(Error::new(ErrorKind::Reason(reason::API_NotSupported))
                        .with_description(format!("Attribute {:?} of device {:?} cannot be polled, it is write-only", 
                            attr.name(), self.name)));
                }
                Ok(Arc::from(attr.name()))
            }
            PolledKind::Command => {
                let command = self.find_command(name)?;
                if !command.is_pollable() {
                    return Err(Error::new(ErrorKind::Reason(reason::API_NotSupported))
                        .with_description(format!("Command {:?} of device {:?} cannot be polled, only one taking no argument can", 
                            command.name(), self.name)));
                }
                Ok(Arc::from(command.name()))
            }
        }
    }

}

/// The first value of that property parsed as a number, absent if it has none, or with a
/// warning if it is not one.
fn first_number<T: std::str::FromStr>(dev: &str, prop: &str, values: &Spectrum<str>) -> Option<T> {
    let value = values.iter().next()?;
    match value.trim().parse() {
        Ok(number) => Some(number),
        Err(_) => {
            warn!(%dev, %prop, %value, "Ignored an invalid polling property");
            None
        }
    }
}

impl<M: Model> Debug for Dev<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Dev").field("name", &self.name).finish_non_exhaustive()
    }
}

/// The interface of a single device, which every device owns its own copy of because it
/// can be altered device by device.
struct DevMutable<M: Model> {
    /// The black box of the device where past commands, attribute reads/writes and other
    /// accesses to this device.
    black_box: VecDeque<String>,
    /// The commands the device currently registers.
    commands: HashMap<ArcName, Arc<Command<M>>>,
    attrs: HashMap<ArcName, Arc<Attr<M>>>,
    /// The State and the Status of the device, kept out of the interface since every device
    /// has them whatever its class, see [`Dev::state_attr`].
    state_attr: Arc<Attr<M>>,
    status_attr: Arc<Attr<M>>,
    /// The states in which the device is put in ALARM when one of its attributes is in
    /// alarm, see [`Dev::set_auto_alarm_states`].
    auto_alarm_states: Arc<[DevState]>,
}

/// What a request reading a device learns of it as it goes, so that it reads nothing twice:
/// what may put the device in ALARM, along with what the request read of it, and the state
/// the state function gave, see [`Dev::set_auto_alarm_states`].
pub(super) struct ReadCtx<M: Model> {
    /// What may put the device in ALARM, which only a request involving the state or the
    /// status takes, and only when anything may, see [`ReadCtx::new`].
    alarm: Option<AlarmCtx<M>>,
    /// The state the state function gave, once called, so that the state and the status
    /// asked for together call it once.
    state: Option<DevState>,
}

/// What may put a device in ALARM, taken out of the interface store once for a whole
/// request, so that what the request borrows the model for and what it reads are the same:
/// the states in which the device may be put in ALARM, and the attributes that have any
/// alarm configured, by name.
struct AlarmCtx<M: Model> {
    states: Arc<[DevState]>,
    attrs: Vec<AlarmAttr<M>>,
}

/// An attribute that may put a device in ALARM, see [`AlarmCtx`].
struct AlarmAttr<M: Model> {
    attr: Arc<Attr<M>>,
    /// What the request found reading the attribute, so that it is read only once:
    /// - `None`: not read yet;
    /// - `Some(None)`: read, and in no alarm, or could not be read;
    /// - `Some(Some(alarm))`: read, and in that alarm.
    read: Option<Option<AttrAlarm>>,
}

impl<M: Model> ReadCtx<M> {

    /// The context of a request on that device, which takes what may put the device in
    /// ALARM out of its interface store only if the request involves its state or its
    /// status, and only keeps it if the device has states to be put in ALARM in and
    /// attributes that have any alarm configured.
    fn new(dev: &Dev<M>, involves_state_status: bool) -> Self {

        let alarm = involves_state_status.then(|| {

            let mutable = dev.mutable.lock().unwrap();
            if mutable.auto_alarm_states.is_empty() {
                return None;
            }

            let mut attrs = mutable.attrs.values()
                .filter(|attr| attr.has_alarms())
                .map(|attr| AlarmAttr {
                    attr: Arc::clone(attr),
                    read: None,
                })
                .collect::<Vec<_>>();

            if attrs.is_empty() {
                return None;
            }

            attrs.sort_by(|a, b| a.attr.name().cmp(b.attr.name()));
            Some(AlarmCtx {
                states: Arc::clone(&mutable.auto_alarm_states),
                attrs,
            })

        }).flatten();

        Self { 
            alarm, 
            state: None,
        }

    }

    /// Whether anything may put the device in ALARM, in any state.
    fn has_alarm(&self) -> bool {
        self.alarm.is_some()
    }

    /// Whether anything may put the device in ALARM when the state function gave that
    /// state, see [`Dev::set_auto_alarm_states`].
    fn may_alarm(&self, state: DevState) -> bool {
        self.alarm.as_ref().is_some_and(|alarm| alarm.states.contains(&state))
    }

    /// Keep the alarm the request found that attribute in, if it may put the device in
    /// ALARM, so that it is not read again.
    fn record(&mut self, attr: &Arc<Attr<M>>, alarm: Option<AttrAlarm>) {
        
        let alarm_attr = self.alarm.iter_mut()
            .flat_map(|alarm| &mut alarm.attrs)
            .find(|alarm_attr| Arc::ptr_eq(&alarm_attr.attr, attr));

        if let Some(alarm_attr) = alarm_attr {
            alarm_attr.read = Some(alarm);
        }
        
    }

    /// The access reading the attributes that may put the device in ALARM needs to the
    /// model.
    fn access(&self, dev: &Dev<M>) -> Access {
        self.alarm.iter()
            .flat_map(|alarm| &alarm.attrs)
            .fold(Access::Shared, |access, alarm_attr| access.merge(alarm_attr.attr.read_access(dev, self)))
    }

    /// Whether reading the attributes that may put the device in ALARM may block, see
    /// [`pool::run`].
    fn may_block(&self, dev: &Dev<M>) -> bool {
        self.alarm.iter()
            .flat_map(|alarm| &alarm.attrs)
            .any(|alarm_attr| alarm_attr.attr.read_may_block(dev, self))
    }

}

/// A reading of a value of a valid quality, made now, which is what a device pushes most.
fn read_now(value: impl IntoValue) -> AttrRead<Value> {
    AttrRead {
        value: Some(value.into_value()),
        w_value: None,
        quality: AttrQuality::Valid,
        time: SystemTime::now(),
    }
}

/// The access a request needs to the model of a device: shared when every handler it runs
/// takes the model by reference, so that such requests run in parallel, and exclusive as
/// soon as one of them takes it mutably.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Access {
    Shared,
    Exclusive,
}

impl Access {

    /// The access covering both, which is exclusive as soon as either is: a request
    /// touching several attributes at once borrows the model once, for what the most
    /// demanding of its handlers needs.
    pub fn merge(self, other: Self) -> Self {
        match (self, other) {
            (Self::Shared, Self::Shared) => Self::Shared,
            _ => Self::Exclusive,
        }
    }

}

/// The lock of the model of a device, held for the duration of a request with the access
/// that request asked for.
pub enum ModelGuard<'a, M> {
    Shared(async_lock::RwLockReadGuard<'a, Option<Result<M>>>),
    Exclusive(async_lock::RwLockWriteGuard<'a, Option<Result<M>>>),
}

impl<M> ModelGuard<'_, M> {

    /// The model of the device if it has one, or the error of its failed initialization.
    #[inline]
    fn get(&self) -> &Option<Result<M>> {
        match self {
            Self::Shared(guard) => guard,
            Self::Exclusive(guard) => guard,
        }
    }

    /// Why the device has no model, if it has none: the error its initialization failed
    /// with, if it failed at all, see [`Dev::no_model_answer`].
    fn failure(&self) -> Option<Option<Error>> {
        match self.get() {
            Some(Ok(_)) => None,
            Some(Err(err)) => Some(Some(err.clone())),
            None => Some(None),
        }
    }

    /// The model, borrowed with the access the lock was taken with.
    /// 
    /// # Panics
    /// 
    /// If the device has no model, which [`Dev::lock_model`] checks beforehand.
    pub(super) fn model(&mut self) -> ModelRef<'_, M> {
        match self {
            Self::Shared(guard) => match &**guard {
                Some(Ok(model)) => ModelRef::Shared(model),
                _ => panic!("the device has no model"),
            }
            Self::Exclusive(guard) => match &mut **guard {
                Some(Ok(model)) => ModelRef::Exclusive(model),
                _ => panic!("the device has no model"),
            }
        }
    }

}

/// The model of a device, borrowed for the duration of a request with the access that
/// request asked for, which is what lets every handler of a single request run under one
/// borrow of the model.
pub enum ModelRef<'m, M> {
    Shared(&'m M),
    Exclusive(&'m mut M),
}

impl<M> ModelRef<'_, M> {

    /// The model, shared, which either access gives.
    #[inline]
    pub fn shared(&self) -> &M {
        match self {
            Self::Shared(model) => model,
            Self::Exclusive(model) => model,
        }
    }

    /// The model, exclusively, which only an exclusive access gives.
    /// 
    /// Failing here is a bug of the server and not of the device: the access is computed
    /// from the very handlers the request then runs, see [`Access::merge`], so a handler
    /// asking for the model mutably has been counted before it is called.
    #[inline]
    pub fn exclusive(&mut self) -> Result<&mut M> {
        match self {
            Self::Exclusive(model) => Ok(model),
            Self::Shared(_) => Err(Error::new(ErrorKind::Internal)
                .with_description("The model was borrowed shared while a handler of that \
                    request needs it exclusively")),
        }
    }

}

/// The status of a device whose initialization failed: the error it failed with, which is
/// what a client reads to know why the device is not running.
fn make_failed_status(err: &Error) -> Scalar<str> {
    Scalar::from(format!("The initialization of the device failed:\n{err}").as_str())
}

/// The error every request on a device that has no model fails with, given the error
/// its initialization failed with, if it failed at all.
fn init_err(failure: Option<&Error>, name: &str) -> Error {
    match failure {
        Some(err) => Error::new(ErrorKind::DevInitFailed)
            .with_description(format!("Device {name:?} failed to initialize"))
            .with_parent(err.clone()),
        None => Error::new(ErrorKind::DevNotConnected)
            .with_description(format!("Device {name:?} is not initialized")),
    }
}

/// The documentation of a definition as a client is told it, an empty one being none.
pub fn some_doc(doc: &Cow<'static, str>) -> Option<Cow<'static, str>> {
    (!doc.is_empty()).then(|| doc.clone())
}

// =================== //
//   Device backend    //
// =================== //

/// The backend of a device, which is the device itself seen through a transparent wrapper,
/// so that the backend methods are not methods of [`Dev`] itself. The backend serving a
/// device holds it as such, and it is reached directly by a proxy of this process when the
/// server is local, see [`crate::local`].
#[repr(transparent)]
struct DevImpl<M: Model>(Dev<M>);

impl<M: Model> DevImpl<M> {

    /// See a device as its backend.
    #[inline]
    fn from_arc(dev: Arc<Dev<M>>) -> Arc<Self> {
        // SAFETY: DevImpl is a repr(transparent) wrapper around Dev, so both have the same
        // layout and an Arc of one is an Arc of the other.
        unsafe { Arc::from_raw(Arc::into_raw(dev) as *const Self) }
    }

}

impl<M: Model> Debug for DevImpl<M> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

/// What touches the model is run on the pool of the server when one of the handlers it
/// runs may block, and polled by the executor of the backend otherwise, see [`pool::run`];
/// what only reads the definitions and the interface is answered on the call itself.
///
/// Every request is refused once the device is withdrawn, see [`Dev::is_withdrawn`], which
/// a client holding the device may still be asking it. A request withdrawn meanwhile finds
/// no model once it holds its lock, the withdrawal deleting it under that lock, and is
/// answered as a device that is not initialized.
impl<M: Model> BackendDev for DevImpl<M> {

    fn name(&self) -> BoxFuture<'_, Result<Arc<str>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(Ok(Arc::clone(&self.0.name))))

    }

    fn admin_dev_name(&self) -> BoxFuture<'_, Result<Arc<str>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(Ok(Arc::clone(&self.0.server().admin_dev_name))))

    }

    fn description(&self) -> BoxFuture<'_, Result<Arc<str>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(Ok(Arc::from(&*self.0.class.def().doc))))

    }

    /// None of this is the device's own: the class it is an instance of, and the server
    /// running it, are what a client is told here, so all of it is read off the definition
    /// of its class and off the server it belongs to.
    fn info(&self) -> BoxFuture<'_, Result<DevInfo>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let def = self.0.class.def();
        let server = self.0.server();
        let backend = match server.backend_checked() {
            Ok(backend) => backend,
            Err(err) => return Box::pin(ready(Err(err))),
        };

        Box::pin(ready(Ok(DevInfo {
            class: def.name.to_string(),
            server_id: server.name().to_string(),
            server_host: backend.host().to_string(),
            server_version: backend.version(),
            doc_url: def.doc_url.clone(),
            // The description of the class, this crate having the one string where Tango
            // has two: what the device *is* and what it says of itself are the same here.
            dev_type: Some(def.doc.clone()),
            version_info: vec![
                (Cow::Borrowed("rstango"), Cow::Borrowed(env!("CARGO_PKG_VERSION"))),
            ],
        })))

    }

    fn ping(&self) -> BoxFuture<'_, Result<()>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(Ok(())))

    }

    fn state(&self) -> BoxFuture<'_, Result<DevState>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let command = Arc::new(Command::new_with_attr(dev.state_attr()));
        let ctx = ReadCtx::new(&dev, true);
        pool::run(command.may_block(&dev, &ctx), async move {
            DevState::try_from(dev.exec_command(Ok(command), Value::Void, ctx, DevSource::CacheDev).await?)
        })

    }

    fn status(&self) -> BoxFuture<'_, Result<Scalar<str>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let command = Arc::new(Command::new_with_attr(dev.status_attr()));
        let ctx = ReadCtx::new(&dev, true);
        pool::run(command.may_block(&dev, &ctx), async move {
            Scalar::<str>::try_from(dev.exec_command(Ok(command), Value::Void, ctx, DevSource::CacheDev).await?)
        })

    }

    fn black_box(&self, max: Option<usize>) -> BoxFuture<'_, Result<Spectrum<str>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let mutable = self.0.mutable.lock().unwrap();
        let black_box = Spectrum::from_strs(mutable.black_box.iter().take(max.unwrap_or(usize::MAX)))
            .expect("strings of more than 4 GiB");

        Box::pin(ready(Ok(black_box)))

    }

    fn command(&self, name: Scalar<str>, input: Value, source: DevSource) -> BoxFuture<'_, Result<Value>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let target = dev.find_command(name.value());
        let ctx = ReadCtx::new(&dev, target.as_ref().is_ok_and(|command| command.involves_state()));

        let blocking = target.as_ref().is_ok_and(|command| command.may_block(&dev, &ctx));
        pool::run(blocking, async move {
            let res = dev.exec_command(target, input, ctx, source).await;
            if let Err(err) = &res {
                debug!(dev = %dev.name, command = %name.value(), %err, "Failed to execute the command");
            }
            res
        })

    }

    fn read_attr(&self, names: Option<Spectrum<str>>, source: DevSource) -> BoxFuture<'_, Result<Vec<NamedResult<AttrRead<Value>>>>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let targets = dev.attr_targets(names);
        let ctx = ReadCtx::new(&dev, targets.iter().flatten().any(|attr| attr.role() != AttrRole::Interface));

        let blocking = targets.iter().flatten().any(|attr| attr.read_may_block(&dev, &ctx));
        pool::run(blocking, async move { dev.exec_read_attr(targets, ctx, source).await })

    }

    fn write_attr(&self, values: Vec<Named<Value>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let targets = values.into_iter()
            .map(|write| (dev.find_attr(write.name.value()), write.value))
            .collect::<Vec<_>>();
        
        let blocking = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .any(|attr| attr.write_may_block());
        pool::run(blocking, async move { dev.exec_write_attr(targets).await })
        
    }

    fn write_read_attr(&self, values: Vec<Named<Value>>) -> BoxFuture<'_, Result<Vec<NamedResult<AttrRead<Value>>>>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let dev = self.0.arc();
        let targets = values.into_iter()
            .map(|write| {
                let target = dev.find_attr(write.name.value());
                (resolved(write.name, target), write.value)
            })
            .collect::<Vec<_>>();
        
        let ctx = ReadCtx::new(&dev, false);
        let blocking = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .any(|attr| attr.write_may_block() || attr.read_may_block(&dev, &ctx));
        pool::run(blocking, async move { dev.exec_write_read_attr(targets, ctx).await })

    }

    /// The definitions and nothing else, so this borrows no model: a device that failed to
    /// initialize still describes the interface of its class, which is how a client knows
    /// to ask it for the state and the status that say it failed.
    fn command_info(&self, names: Option<Spectrum<str>>) -> BoxFuture<'_, Result<Vec<NamedResult<CommandInfo>>>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let infos = self.0.command_targets(names).into_iter()
            .map(|target| match target {
                Ok(target) => Named::new(Scalar::from(target.name()), Ok(target.info())),
                Err(unresolved) => unresolved.map(Err),
            })
            .collect();
        
        Box::pin(ready(Ok(infos)))

    }

    /// The counterpart of [`Self::command_info`], and the same absence of any model.
    fn attr_info(&self, names: Option<Spectrum<str>>) -> BoxFuture<'_, Result<Vec<NamedResult<AttrInfo>>>> {
        
        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        let infos = self.0.attr_targets(names).into_iter()
            .map(|target| match target {
                Ok(target) => Named::new(Scalar::from(target.name()), target.info()),
                Err(unresolved) => unresolved.map(Err),
            })
            .collect();

        Box::pin(ready(Ok(infos)))

    }

    /// Change the configuration of each attribute on its own, see [`Dev::exec_set_attr_config`].
    fn set_attr_config(&self, configs: Vec<Named<AttrConfig>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(async move { Ok(self.0.exec_set_attr_config(configs).await) })

    }

    /// What the device recorded itself, or its polling recorded, in the history of that
    /// command, see [`Command::history`]: a command nothing was recorded of fails rather
    /// than giving an empty history, whether it is polled or not.
    fn command_history(&self, name: Scalar<str>, max: usize) -> BoxFuture<'_, Result<Vec<RecordedResult<Value>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(self.0.find_command(name.value()).and_then(|command| {
            let history = command.history(max);
            if history.is_empty() {
                return Err(Error::new(ErrorKind::CommandNotPolled)
                    .with_description(format!("Command {:?} of device {:?} has no history recorded", 
                        command.name(), self.0.name)));
            }
            Ok(history)
        })))

    }

    /// The counterpart of [`Self::command_history`] for the attributes, see [`Attr::history`].
    fn attr_history(&self, name: Scalar<str>, max: usize) -> BoxFuture<'_, Result<Vec<RecordedResult<AttrRead<Value>>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(self.0.find_attr(name.value()).and_then(|attr| {
            let history = attr.history(max);
            if history.is_empty() {
                return Err(Error::new(ErrorKind::AttrNotPolled)
                    .with_description(format!("Attribute {:?} of device {:?} has no history recorded", 
                        attr.name(), self.0.name)));
            }
            Ok(history)
        })))

    }

    // The subscriptions are the server's, which keeps them for as long as the device is
    // served under that name, see [`Server::events`]. Only an attribute the device has can
    // be subscribed to, the state and the status included, as cppTango allows, and only to
    // an event something sends, see [`Attr::check_push_event`].

    fn subscribe_attr_value(&self, _admin: Arc<dyn BackendDev>, name: Scalar<str>, event: AttrValueEvent) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrRead<Value>>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(self.0.find_attr(name.value()).and_then(|target| {
            target.check_push_event(&self.0, event)?;
            Ok(self.0.server().subscribe_attr_value(&self.0.name, target.name(), event))
        })))

    }

    fn subscribe_attr_ready(&self, _admin: Arc<dyn BackendDev>, name: Scalar<str>) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrReady>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(self.0.find_attr(name.value()).and_then(|target| {
            target.check_data_ready(&self.0)?;
            Ok(self.0.server().subscribe_attr_ready(&self.0.name, target.name()))
        })))

    }

    fn subscribe_attr_config(&self, _admin: Arc<dyn BackendDev>, name: Scalar<str>) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrInfo>>>> {

        if let Err(err) = self.0.check_withdrawn() {
            return Box::pin(ready(Err(err)));
        }

        Box::pin(ready(self.0.find_attr(name.value()).map(|target| {
            self.0.server().subscribe_attr_config(&self.0.name, target.name())
        })))

    }

}

/// What a name a request gave resolved to, which names itself, or the name itself when it
/// resolved to nothing, along with the reason: the very name the request gave then.
type Resolved<T> = std::result::Result<T, Named<Error>>;

fn resolved<T>(name: Scalar<str>, res: Result<T>) -> Resolved<T> {
    res.map_err(|err| Named::new(name, err))
}

/// Every name a request gave, each a scalar of its own sharing them.
fn scalars(names: &Spectrum<str>) -> impl Iterator<Item = Scalar<str>> + '_ {
    (0..names.len()).map(|index| names.get_scalar([index]).expect("a name at every index"))
}


#[cfg(test)]
mod tests {

    use std::sync::Mutex;
    use std::thread;
    use std::time::Duration;

    use futures::channel::oneshot;
    use futures::executor::block_on;
    use futures::{FutureExt, StreamExt};

    use crate::dev::{ToNames, WriteAttrSpec};
    use crate::value::FromValue;

    use super::*;
    use super::super::def::{AttrDef, ClassDef, CommandDef};
    use super::super::server::ServerBuilder;
    use crate::testing::TestContext;

    /// A server with a single device of that class, which is added but not synchronized
    /// yet, on a database listing no other device, the server being served by the context.
    fn serve<M: Model>(def: ClassDef<M>) -> (TestContext, Arc<DevImpl<M>>) {
        let ctx = TestContext::new().unwrap();
        ctx.database().add_server("Test/test", &[]).unwrap();
        ctx.database().add_dev("test/dev/1", &def.name, "Test/test").unwrap();
        let server = ctx.serve(ServerBuilder::new("Test", "test")).unwrap();
        let class = server.add_class(def).unwrap();
        let dev = class.add_dev("test/dev/1").unwrap();
        let dev = DevImpl::from_arc(dev);
        drop(class);
        (ctx, dev)
    }

    #[test]
    fn push_event() {

        let (ctx, dev) = serve(model_def());
        let server = ctx.server("Test/test").unwrap();
        server.sync().unwrap();
        let mut state = server.subscribe_attr_value("test/dev/1", "State", AttrValueEvent::Change);
        let mut count = server.subscribe_attr_value("test/dev/1", "Count", AttrValueEvent::Change);

        thread::scope(|scope| {
            scope.spawn(|| dev.0.push_change_event("state", DevState::Moving).unwrap());
        });

        let read = block_on(state.next()).unwrap().unwrap();
        assert_eq!(read.value, Some(Value::from(DevState::Moving)));
        assert_eq!(read.w_value, None);
        assert_eq!(read.quality, AttrQuality::Valid);

        // A writable attribute is pushed with its set point, as it is read.
        dev.0.set_attr_w_value("Count", 5).unwrap();
        dev.0.push_change_event("Count", 3).unwrap();
        let read = block_on(count.next()).unwrap().unwrap();
        assert_eq!(read.value, Some(Value::from(3)));
        assert_eq!(read.w_value, Some(Value::from(5)));

        assert!(dev.0.push_change_event("Missing", 1.0).is_err());

        // A reading with no read value, or a State of another quality than valid, is refused.
        let mut empty = read_now(3);
        empty.value = None;
        assert_eq!(dev.0.push_attr_event("Count", AttrValueEvent::Change, Ok(empty)).unwrap_err().kind(), ErrorKind::InvalidData);
        let alarm = read_now(DevState::Moving).with_quality(AttrQuality::Alarm);
        assert_eq!(dev.0.push_attr_event("State", AttrValueEvent::Change, Ok(alarm)).unwrap_err().kind(), ErrorKind::InvalidData);

        // An event the attribute does not declare it pushes is refused.
        let err = dev.0.push_archive_event("Count", 3).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Reason(reason::API_AttributePollingNotStarted));
        dev.0.push_user_event("Count", 3).unwrap();

    }

    #[test]
    fn set_attr_config() {

        let (ctx, dev) = serve(model_def());
        let server = ctx.server("Test/test").unwrap();
        server.sync().unwrap();
        let mut conf = server.subscribe_attr_config("test/dev/1", "Count");

        let mut config = dev.0.get_attr("Count").unwrap().config();
        config.label = Some("Counter".into());
        dev.0.set_attr_config("count", &config).unwrap();

        assert_eq!(dev.0.get_attr("Count").unwrap().config().label.as_deref(), Some("Counter"));
        let info = block_on(conf.next()).unwrap().unwrap();
        assert_eq!(info.config.label.as_deref(), Some("Counter"));

        // Nothing changed, nothing pushed.
        dev.0.set_attr_config("Count", &config).unwrap();
        assert!(conf.next().now_or_never().is_none());

    }

    /// A read from the cache is answered with the latest reading recorded while it is
    /// valid, the State command shares the history of its attribute, and a history is
    /// given oldest first.
    #[test]
    fn attr_history() {

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        let read = |name: &str, source| block_on(dev.read_attr(name.to_names(), source)).unwrap().pop().unwrap().value;

        let err = read("Count", DevSource::Cache).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AttrNotPolled);
        assert!(read("Count", DevSource::CacheDev).is_ok());
        assert_eq!(block_on(dev.attr_history(Scalar::from("Count"), 10)).unwrap_err().kind(), ErrorKind::AttrNotPolled);

        let count = dev.0.get_attr("Count").unwrap();
        count.push_history(Ok(read_now(5)), None).unwrap();
        count.push_history(Ok(read_now(6)), None).unwrap();
        assert_eq!(read("Count", DevSource::Cache).unwrap().value, Some(Value::from(6)));
        assert_eq!(read("Count", DevSource::Dev).unwrap().value, Some(Value::from(0)));

        let history = block_on(dev.attr_history(Scalar::from("Count"), 10)).unwrap();
        let values = history.into_iter().map(|entry| entry.value.unwrap().value.unwrap()).collect::<Vec<_>>();
        assert_eq!(values, [Value::from(5), Value::from(6)]);

        count.set_history_depth(1);
        assert_eq!(count.history(10).len(), 1);

        // An outdated reading is read again from the device, or refused from the cache alone.
        count.push_history(Ok(read_now(7)), Some(Duration::ZERO)).unwrap();
        assert_eq!(read("Count", DevSource::Cache).unwrap_err().kind(), ErrorKind::ValueOutdated);
        assert_eq!(read("Count", DevSource::CacheDev).unwrap().value, Some(Value::from(0)));

        count.clear_history();
        assert!(count.history(10).is_empty());

        // The State is only recorded valid, and its command answers from that history.
        let state = dev.0.get_attr("State").unwrap();
        let mut alarm = read_now(DevState::Fault);
        alarm.quality = AttrQuality::Alarm;
        assert!(state.push_history(Ok(alarm), None).is_err());
        let mut empty = read_now(DevState::Fault);
        empty.value = None;
        assert!(state.push_history(Ok(empty), None).is_err());
        state.push_history(Ok(read_now(DevState::Fault)), None).unwrap();
        let value = block_on(dev.command(Scalar::from("State"), Value::Void, DevSource::Cache)).unwrap();
        assert_eq!(DevState::try_from(value).unwrap(), DevState::Fault);
        let history = block_on(dev.command_history(Scalar::from("state"), 10)).unwrap();
        assert_eq!(history.len(), 1);

    }

    /// A command is answered from the cache the way an attribute is read from it, and only
    /// one taking no argument is recorded.
    #[test]
    fn command_history() {

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        let exec = |name: &str, source| block_on(dev.command(Scalar::from(name), Value::Void, source));

        assert_eq!(exec("GetCount", DevSource::Cache).unwrap_err().kind(), ErrorKind::CommandNotPolled);
        assert_eq!(exec("GetCount", DevSource::CacheDev).unwrap(), Value::from(0));
        assert_eq!(block_on(dev.command_history(Scalar::from("GetCount"), 10)).unwrap_err().kind(), ErrorKind::CommandNotPolled);

        let get_count = dev.0.get_command("GetCount").unwrap();
        get_count.push_history(Ok(Value::from(5)), None).unwrap();
        get_count.push_history(Err(Error::new(ErrorKind::TimedOut)), None).unwrap();
        assert_eq!(exec("GetCount", DevSource::Cache).unwrap_err().kind(), ErrorKind::TimedOut);
        assert_eq!(exec("GetCount", DevSource::Dev).unwrap(), Value::from(0));

        let history = block_on(dev.command_history(Scalar::from("getcount"), 10)).unwrap();
        assert_eq!(history.len(), 2);
        assert_eq!(history[0].value.as_ref().unwrap(), &Value::from(5));
        assert!(history[1].value.is_err());

        // An outdated result is executed again, or refused from the cache alone.
        get_count.push_history(Ok(Value::from(6)), Some(Duration::ZERO)).unwrap();
        assert_eq!(exec("GetCount", DevSource::Cache).unwrap_err().kind(), ErrorKind::ValueOutdated);
        assert_eq!(exec("GetCount", DevSource::CacheDev).unwrap(), Value::from(0));

        let incr = dev.0.get_command("Incr").unwrap();
        assert!(incr.push_history(Ok(Value::from(1)), None).is_err());
        assert!(dev.0.get_command("Init").unwrap().push_history(Ok(Value::Void), None).is_err());
        assert_eq!(exec("Init", DevSource::Cache).unwrap_err().kind(), ErrorKind::CommandNotPolled);

        // The State command records in its attribute.
        dev.0.get_command("State").unwrap().push_history(Ok(DevState::Alarm.into()), None).unwrap();
        let read = dev.0.get_attr("State").unwrap().history(1).pop().unwrap().value.unwrap();
        assert_eq!(read.value, Some(Value::from(DevState::Alarm)));

    }

    /// A motor whose initialization always fails, which is served with no model.
    fn failing_def() -> ClassDef<Motor> {
        ClassDef::<Motor>::new_async_with("Motor", |_dev| Box::pin(async {
            Err(Error::new(ErrorKind::Internal).with_description("No hardware"))
        }))
            .command(CommandDef::new("GetCount").exec_async(Motor::get_count))
            .attr(AttrDef::new("Count").read_async(Motor::count))
    }

    /// A device that has no model answers each attribute of a read on its own: the State
    /// and the Status saying what it is, the others failing with why it has no model.
    #[test]
    fn no_model_reads() {

        let (_ctx, dev) = serve(failing_def());
        let read = |names: &[&str]| block_on(dev.read_attr(names.to_names(), DevSource::Dev)).unwrap();
        let value = |read: &NamedResult<AttrRead<Value>>| read.value.as_ref().unwrap().value.clone().unwrap();

        // Not initialized yet.
        let reads = read(&["State", "Status"]);
        assert_eq!(DevState::try_from(value(&reads[0])).unwrap(), DevState::Unknown);
        assert_eq!(Scalar::<str>::try_from(value(&reads[1])).unwrap().value(), MISSING_STATUS);

        dev.0.server().sync().unwrap();

        let reads = read(&["State", "Status", "Count", "Missing"]);
        assert_eq!(DevState::try_from(value(&reads[0])).unwrap(), DevState::Fault);
        assert!(Scalar::<str>::try_from(value(&reads[1])).unwrap().value().contains("No hardware"));
        assert_eq!(reads[2].value.as_ref().unwrap_err().kind(), ErrorKind::DevInitFailed);
        assert_eq!(reads[3].value.as_ref().unwrap_err().kind(), ErrorKind::AttrNotFound);

    }

    /// Commands executed together under a single borrow, each answered in its order, as a
    /// multiple read is, a device that has no model included.
    #[test]
    fn exec_many_command() {

        let exec = |dev: &DevImpl<Motor>, names: &[&str]| {
            let targets = names.iter()
                .map(|&name| (resolved(Scalar::from(name), dev.0.find_command(name)), Value::Void))
                .collect();
            block_on(dev.0.exec_many_command(targets, ReadCtx::new(&dev.0, true), DevSource::Dev)).unwrap()
        };

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        let results = exec(&dev, &["GetCount", "State", "Missing"]);
        assert_eq!(results[0].value.as_ref().unwrap(), &Value::from(0));
        assert_eq!(DevState::try_from(results[1].value.clone().unwrap()).unwrap(), DevState::On);
        assert_eq!(results[2].value.as_ref().unwrap_err().kind(), ErrorKind::CommandNotFound);

        let (_ctx, dev) = serve(failing_def());
        dev.0.server().sync().unwrap();

        let results = exec(&dev, &["GetCount", "State", "Status"]);
        assert_eq!(results[0].value.as_ref().unwrap_err().kind(), ErrorKind::DevInitFailed);
        assert_eq!(DevState::try_from(results[1].value.clone().unwrap()).unwrap(), DevState::Fault);
        assert!(Scalar::<str>::try_from(results[2].value.clone().unwrap()).unwrap().value().contains("No hardware"));

    }

    fn thread_name() -> String {
        thread::current().name().unwrap_or_default().to_string()
    }

    struct Motor {
        count: i32,
    }

    impl Motor {

        async fn init(_dev: &Dev<Self>) -> Result<Self> {
            Ok(Self { count: 0 })
        }

        async fn incr(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<i32> {
            self.count += arg;
            Ok(self.count)
        }

        async fn count(&self, _dev: &Dev<Self>) -> Result<i32> {
            Ok(self.count)
        }

        async fn get_count(&self, _dev: &Dev<Self>, _: ()) -> Result<i32> {
            Ok(self.count)
        }

        async fn set_count(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<()> {
            self.count = arg;
            Ok(())
        }

        async fn state(&self, _dev: &Dev<Self>) -> Result<DevState> {
            Ok(if self.count == 0 { DevState::On } else { DevState::Moving })
        }

        fn thread(&self, _dev: &Dev<Self>) -> Result<String> {
            Ok(thread_name())
        }

        async fn thread_async(&self, _dev: &Dev<Self>) -> Result<String> {
            Ok(thread_name())
        }

    }

    fn model_def() -> ClassDef<Motor> {
        ClassDef::new_async("Motor", Motor::init)
            .state_async(Motor::state)
            .push_state_events(Some(false), None)
            .command(CommandDef::new("Incr").exec_exclusive_async(Motor::incr))
            .command(CommandDef::new("GetCount").exec_async(Motor::get_count))
            .attr(AttrDef::new("Count").read_async(Motor::count).write_exclusive_async(Motor::set_count)
                .push_change_event(false))
            .attr(AttrDef::new("Thread").read(Motor::thread))
            .attr(AttrDef::new("ThreadAsync").read_async(Motor::thread_async))
    }

    fn read_one<T: FromValue>(dev: &DevImpl<Motor>, name: &str) -> T {
        let mut reads = block_on(dev.read_attr(name.to_names(), DevSource::Dev)).unwrap();
        let read = reads.pop().unwrap().value;
        T::from_value(read.unwrap().value.unwrap()).unwrap()
    }

    /// Every asynchronous handler, from the initialization to the state, run as a client
    /// asks for it.
    #[test]
    fn async_handlers() {

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        assert_eq!(block_on(dev.state()).unwrap(), DevState::On);
        let count = block_on(dev.command(Scalar::from("Incr"), Value::from(3), DevSource::Dev)).unwrap();
        assert_eq!(i32::from_value(count).unwrap(), 3);
        assert_eq!(block_on(dev.state()).unwrap(), DevState::Moving);

        let writes = block_on(dev.write_attr(("Count", 7).into_values())).unwrap();
        assert!(writes.into_iter().all(|write| write.is_ok()));
        assert_eq!(read_one::<i32>(&dev, "Count"), 7);

        // The Init command builds the model again.
        block_on(dev.command(Scalar::from("Init"), Value::Void, DevSource::Dev)).unwrap();
        assert_eq!(read_one::<i32>(&dev, "Count"), 0);

    }

    /// A name that resolves to nothing is answered with the very name the request gave,
    /// sharing its octets, and a known one with the name of its definition.
    #[test]
    fn unknown_attr_name() {

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        let names = Spectrum::from(&["count", "Nothing"][..]);
        let reads = block_on(dev.read_attr(Some(names.clone()), DevSource::Dev)).unwrap();

        assert_eq!(reads[0].name.value(), "Count");
        assert!(reads[0].value.is_ok());

        assert_eq!(reads[1].name.value().as_ptr(), names.get([1]).unwrap().as_ptr());
        assert_eq!(reads[1].value.as_ref().unwrap_err().kind(), ErrorKind::AttrNotFound);

    }

    /// A request runs on the pool as soon as one of its handlers is synchronous, the
    /// asynchronous ones being blocked on there, and is polled where it is awaited
    /// otherwise.
    #[test]
    fn request_threads() {

        let (_ctx, dev) = serve(model_def());
        dev.0.server().sync().unwrap();

        let on_pool = |name: &str| name.starts_with("pool-");
        assert!(on_pool(&read_one::<String>(&dev, "Thread")));
        assert!(!on_pool(&read_one::<String>(&dev, "ThreadAsync")));

        let reads = block_on(dev.read_attr(["ThreadAsync", "Thread"].to_names(), DevSource::Dev)).unwrap();
        for read in reads {
            assert!(on_pool(&String::from_value(read.value.unwrap().value.unwrap()).unwrap()));
        }

    }

    /// The model stays locked across the awaits of an asynchronous handler: a request
    /// arriving meanwhile waits for it.
    #[test]
    fn lock_across_await() {

        let (tx, rx) = oneshot::channel::<()>();
        let gate = Mutex::new(Some(rx));
        let def = model_def()
            .command(CommandDef::new("Wait").exec_exclusive_async_with(move |_model: &mut Motor, _dev, _input| {
                let rx = gate.lock().unwrap().take();
                Box::pin(async move {
                    if let Some(rx) = rx {
                        let _ = rx.await;
                    }
                    Ok(Value::Void)
                })
            }));

        let (_ctx, dev) = serve(def);
        dev.0.server().sync().unwrap();

        let mut wait = dev.command(Scalar::from("Wait"), Value::Void, DevSource::Dev);
        assert!((&mut wait).now_or_never().is_none());
        let mut read = dev.read_attr("Count".to_names(), DevSource::Dev);
        assert!((&mut read).now_or_never().is_none());

        tx.send(()).unwrap();
        block_on(wait).unwrap();
        assert!(block_on(read).unwrap().pop().unwrap().value.is_ok());

    }

    /// A device whose asynchronous initialization failed keeps the error, and gives it
    /// instead of running anything.
    #[test]
    fn async_init_failed() {

        let def = ClassDef::<Motor>::new_async_with("Motor", |_dev| Box::pin(async {
            Err(Error::new(ErrorKind::Internal).with_description("No hardware"))
        }));

        let (_ctx, dev) = serve(def);
        assert_eq!(block_on(dev.state()).unwrap(), DevState::Unknown);
        dev.0.server().sync().unwrap();

        assert_eq!(block_on(dev.state()).unwrap(), DevState::Fault);
        assert!(block_on(dev.status()).unwrap().value().contains("No hardware"));
        assert!(block_on(dev.command(Scalar::from("Init"), Value::Void, DevSource::Dev)).is_err());

    }

}