rstango 0.3.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
//! A device: its interface, its model, and every request a client makes of it.

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, Weak};
use std::fmt::{self, Debug};
use std::future::Future;
use std::borrow::Cow;
use std::time::SystemTime;

use async_lock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use futures::future::{join, ready, BoxFuture};
use tracing::{debug, error, info};
use futures::stream::BoxStream;

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

use super::def::{AttrDef, CommandDef, DeleteFn, InitFn, StateFn, StatusFn, WriteFn};
use super::{reserved_name, Model, Ref, DEFAULT_STATE, DEFAULT_STATUS, INIT_NAME, 
    MISSING_STATUS, RESERVED_ATTRS, RESERVED_COMMANDS, STATE_NAME, STATUS_NAME};
use super::class::{AnyClass, Class};
use super::attr::{Attr, AttrAlarm};
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 trait AnyDev: Debug + Send + Sync {

    /// The name of that device.
    fn name(&self) -> &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<()>>;

    /// 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>>;

}

/// 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, that
/// delete-then-init 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>>,
    /// Mutable state of the device where the commands and attributes definitions with
    /// polling cache and more are stored.
    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: 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>>,
}

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(Arc::clone(&class.def().state_attr)));
        let status_attr = Arc::new(Attr::new(Arc::clone(&class.def().status_attr)));
        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: RwLock::new(None),
            local_handle: Mutex::new(None),
        })
    }

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

    #[inline]
    pub fn class(&self) -> &Class<M> {
        &self.class
    }

    #[inline]
    pub fn server(&self) -> &Server {
        self.class.server()
    }

    // 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 del_prop_async<Names: ToNamesNotAll>(&self, names: Names) -> impl Future<Output = Result<()>> + Send {
        self.server().database().del_dev_prop_async(&self.name, names)
    }

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

    /// The device, strongly, for a request to run on the pool with, see [`pool::run`].
    #[inline]
    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 let Some(reserved) = reserved_name(&def.name, RESERVED_COMMANDS) {
            return Err(Error::new(ErrorKind::CommandNameInvalid)
                .with_description(format!("Command {} cannot be defined in the 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_append_description(format_args!("Command {:?}", def.name)));
        }

        let name = ArcName::from(Arc::<str>::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 let Some(reserved) = reserved_name(&def.name, RESERVED_ATTRS) {
            return Err(Error::new(ErrorKind::AttrNameInvalid)
                .with_description(format!("Attribute {} cannot be defined in the device {}, \
                    {reserved} is answered by the server itself", def.name, self.name)));
        }

        if let Err(err) = def.check() {
            return Err(Error::new(ErrorKind::AttrNameInvalid)
                .with_description(format!("Attribute {} cannot be defined in the 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_append_description(format_args!("Attribute {:?}", def.name)));
        }

        let name = ArcName::from(Arc::<str>::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.
    pub async fn set_attr_w_value_async(&self, name: &str, value: impl IntoValue) -> Result<()> {
        let attr = self.find_attr(name)?;
        attr.set_w_value(self, value.into_value()).await
    }

    /// Give the attribute of that name a new set point, see [`Self::set_attr_w_value_async`],
    /// which must therefore never run in an asynchronous handler. Giving up after the
    /// timeout of the database of the server, which is what it waits for.
    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.change_attr_config(name, config).await
    }

    /// Change the configuration of the attribute of that name, see
    /// [`Self::set_attr_config_async`], which must therefore never run in an asynchronous
    /// handler. Giving up after the timeout of the database of the server, which is what it
    /// waits for.
    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.
    /// 
    /// Every request on a command goes through this, and it is borrowed rather than kept:
    /// 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<Ref<'_, Command<M>>> {
        self.find_command(name).ok().map(Ref::new)
    }

    /// The attribute of that name on this device, reached the way [`Self::get_command`]
    /// reaches a command.
    pub fn get_attr(&self, name: &str) -> Option<Ref<'_, Attr<M>>> {
        self.find_attr(name).ok().map(Ref::new)
    }

    /// Every command of the interface of this device.
    pub fn commands(&self) -> Vec<Ref<'_, Command<M>>> {
        self.all_commands().into_iter().map(Ref::new).collect()
    }

    /// Every attribute of the interface of this device.
    /// 
    /// TODO: The order 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<Ref<'_, Attr<M>>> {
        self.all_attrs().into_iter().map(Ref::new).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 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<()> {
        let attr = self.resolve_attr(name)?.into_attr();
        attr.check_push_event(self, event)?;
        if let Ok(read) = &mut 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, failing if the device has
    /// no such attribute.
    pub fn push_data_ready_event(&self, name: &str) -> Result<()> {
        let target = self.resolve_attr(name)?;
        self.server().push_attr_ready(&self.name, target.name(), Ok(()));
        Ok(())
    }

    /// Initialize this device by deleting (if previously existing), and init a new model
    /// for this device.
    /// 
    /// If this fails, the error is reported into the model and will later be reported in 
    /// the device's status and the device will be in FAULT.
    /// 
    /// This will usually be called once when the device is first added and after explicit
    /// synchronization of the server.
    /// 
    /// 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_attr_config`].
    async fn init(&self) {

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

        // 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.all_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)
            }
        });

    }

    /// 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 on it fails until then, but its state and its status still answer,
    /// see [`Self::state`].
    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(Arc::clone(&def.state_attr)));
        mutable.status_attr = Arc::new(Attr::new(Arc::clone(&def.status_attr)));

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

        for def in &def.attrs {
            let name = ArcName::from(Arc::<str>::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_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]));
        }

    }

    /// The state of the device as a client gets it: what the state function of the class
    /// derives from the model or, for a device that has no model, what the device says of
    /// itself: the FAULT of a failed initialization, or the UNKNOWN of a device that has
    /// not been initialized yet.
    /// 
    /// Neither of those is an error: a client asking a broken device what is wrong with
    /// it is answered, the reason itself being in its status, see [`Self::status`].
    async fn state(&self, ctx: &mut ReadCtx<M>) -> Result<DevState> {
        let mut guard = self.lock(self.state_access(ctx)).await;
        match guard.get() {
            Some(Ok(_)) => self.model_state(&mut guard.model(), ctx).await,
            Some(Err(_)) => Ok(DevState::Fault),
            None => Ok(DevState::Unknown),
        }
    }

    /// The status of the device, the counterpart of [`Self::state`]: a device that failed
    /// to initialize gives the error it failed with, which is what keeping that error is
    /// for, and a device that has not been initialized yet says so.
    async fn status(&self, ctx: &mut ReadCtx<M>) -> Result<String> {
        let mut guard = self.lock(self.status_access(ctx)).await;
        match guard.get() {
            Some(Ok(_)) => self.model_status(&mut guard.model(), ctx).await,
            Some(Err(err)) => Ok(make_failed_status(err)),
            None => Ok(MISSING_STATUS.to_string()),
        }
    }

    /// The state of the device derived from its model, which is already borrowed with the
    /// access [`Self::state_access`] asked for: the half of [`Self::state`] that needs a
    /// model, 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`].
    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.
    async fn model_status(&self, model: &mut ModelRef<'_, M>, ctx: &mut ReadCtx<M>) -> Result<String> {

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

        if ctx.has_alarm() {
            let state = self.model_state_inner(model, ctx).await?;
            for (attr, alarm) in self.attrs_in_alarm(ctx, state, model, true).await {
                status.push('\n');
                status.push_str(&alarm.describe(attr.name()));
            }
        }

        Ok(status)

    }

    /// 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;
        }

        for alarm_attr in ctx.alarm.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!
                    let alarm = alarm_attr.attr.read_with_alarm(self, model).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;
                }
            }

        }

        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.
    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())
    }

    /// 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.
    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.
    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.
    fn state_may_block(&self, ctx: &ReadCtx<M>) -> bool {
        matches!(&self.class.def().state, Some(StateFn::SharedSync(_) | StateFn::ExclusiveSync(_)))
            || ctx.may_block()
    }

    /// Whether deriving the status of this device may block, see [`pool::run`], deriving
    /// its state included when the attributes may put it in ALARM.
    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))
    }

    /// Whether reading that target may block, see [`pool::run`].
    fn read_may_block(&self, target: &AttrTarget<M>, ctx: &ReadCtx<M>) -> bool {
        match target {
            AttrTarget::State(_) => self.state_may_block(ctx),
            AttrTarget::Status(_) => self.status_may_block(ctx),
            AttrTarget::Attr(attr) => attr.read_may_block(),
        }
    }

    /// Whether executing that target may block, see [`pool::run`].
    fn command_may_block(&self, target: &CommandTarget<M>, ctx: &ReadCtx<M>) -> bool {
        match target {
            CommandTarget::State(_) => self.state_may_block(ctx),
            CommandTarget::Status(_) => self.status_may_block(ctx),
            CommandTarget::Init => self.init_may_block(),
            CommandTarget::Command(command) => command.may_block(),
        }
    }

    /// The access reading that target needs to the model.
    fn read_access(&self, target: &AttrTarget<M>, ctx: &ReadCtx<M>) -> Access {
        match target {
            AttrTarget::State(_) => self.state_access(ctx),
            AttrTarget::Status(_) => self.status_access(ctx),
            AttrTarget::Attr(attr) => attr.read_access(),
        }
    }

    /// 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.
    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, owned to run it with the interface store unlocked, 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.mutable.lock().unwrap().commands.get(Name::new(name))
            .map(Arc::clone)
            .ok_or_else(|| Error::new(ErrorKind::CommandNotFound)
                .with_append_description(format_args!("Command {name:?} of the device {:?}", self.name)))
    }

    /// The counterpart of [`Self::find_command`] for the attributes.
    fn find_attr(&self, name: &str) -> Result<Arc<Attr<M>>> {
        self.mutable.lock().unwrap().attrs.get(Name::new(name))
            .map(Arc::clone)
            .ok_or_else(|| Error::new(ErrorKind::AttrNotFound)
                .with_append_description(format_args!("Attribute {name:?} of the device {:?}", self.name)))
    }

    /// Every command of the interface, owned, see [`Self::find_command`].
    fn all_commands(&self) -> Vec<Arc<Command<M>>> {
        self.mutable.lock().unwrap().commands.values().map(Arc::clone).collect()
    }

    /// Every attribute of the interface, owned, see [`Self::find_attr`].
    fn all_attrs(&self) -> Vec<Arc<Attr<M>>> {
        self.mutable.lock().unwrap().attrs.values().map(Arc::clone).collect()
    }

    /// The State attribute of this device, which holds its configuration, the state itself
    /// being read through the state function, see [`Self::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)
    }

    /// What a name a client asked an attribute of is on this device: the state and the
    /// status are answered by the device itself, whatever its class defines, and every
    /// other name is looked up in its interface.
    fn resolve_attr(&self, name: &str) -> Result<AttrTarget<M>> {
        if name.eq_ignore_ascii_case(STATE_NAME) {
            Ok(AttrTarget::State(self.state_attr()))
        } else if name.eq_ignore_ascii_case(STATUS_NAME) {
            Ok(AttrTarget::Status(self.status_attr()))
        } else {
            self.find_attr(name).map(AttrTarget::Attr)
        }
    }

    /// The attribute of that name to write, the two every device has being refused here
    /// already since neither is writable.
    fn resolve_writable_attr(&self, name: &str) -> Result<Arc<Attr<M>>> {
        match self.resolve_attr(name)? {
            AttrTarget::Attr(attr) => Ok(attr),
            AttrTarget::State(_) | AttrTarget::Status(_) => Err(not_writable_err(self, name)),
        }
    }

    /// What a name a client asked a command of is on this device, the counterpart of
    /// [`Self::resolve_attr`]: the state, the status and the initialization are the server's
    /// own, and every other name is looked up in the interface of the device.
    fn resolve_command(&self, name: &str) -> Result<CommandTarget<M>> {
        if name.eq_ignore_ascii_case(STATE_NAME) {
            Ok(CommandTarget::State(self.state_attr()))
        } else if name.eq_ignore_ascii_case(STATUS_NAME) {
            Ok(CommandTarget::Status(self.status_attr()))
        } else if name.eq_ignore_ascii_case(INIT_NAME) {
            Ok(CommandTarget::Init)
        } else {
            self.find_command(name).map(CommandTarget::Command)
        }
    }

    /// Every attribute a client asking for none in particular is answered with: the two
    /// every device has first, then its whole interface.
    fn all_attr_targets(&self) -> Vec<Resolved<AttrTarget<M>>> {
        [Ok(AttrTarget::State(self.state_attr())), Ok(AttrTarget::Status(self.status_attr()))]
            .into_iter()
            .chain(self.all_attrs().into_iter().map(|attr| Ok(AttrTarget::Attr(attr))))
            .collect()
    }

    /// 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<AttrTarget<M>>> {
        match names {
            Some(names) => scalars(&names)
                .map(|name| {
                    let target = self.resolve_attr(name.value());
                    resolved(name, target)
                })
                .collect(),
            None => self.all_attr_targets(),
        }
    }

    /// The counterpart of [`Self::attr_targets`] for the commands, the three every device
    /// has coming first.
    fn command_targets(&self, names: Option<Spectrum<str>>) -> Vec<Resolved<CommandTarget<M>>> {
        match names {
            Some(names) => scalars(&names)
                .map(|name| {
                    let target = self.resolve_command(name.value());
                    resolved(name, target)
                })
                .collect(),
            None => [Ok(CommandTarget::State(self.state_attr())), Ok(CommandTarget::Status(self.status_attr())), Ok(CommandTarget::Init)]
                .into_iter()
                .chain(self.all_commands().into_iter().map(|command| Ok(CommandTarget::Command(command))))
                .collect(),
        }
    }

    /// Execute a command, resolved beforehand, see [`BackendDev::command`].
    async fn exec_command(&self, target: Result<CommandTarget<M>>, input: Value, mut ctx: ReadCtx<M>) -> 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 target = match target {
            Ok(target) => target,
            Err(err) => return Err(self.check_model().await.err().unwrap_or(err)),
        };

        match target {
            // The three commands every Tango device has, whatever its class, none of them
            // borrowing the model: the two things the device says of itself, and the one
            // that rebuilds that model, which could not run while it was borrowed.
            CommandTarget::State(_) => Ok(self.state(&mut ctx).await?.into()),
            CommandTarget::Status(_) => Ok(self.status(&mut ctx).await?.into()),
            CommandTarget::Init => {
                self.init().await;
                // 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.
                self.check_model().await?;
                Ok(Value::Void)
            }
            CommandTarget::Command(command) => {
                let mut guard = self.lock_model(command.access()).await?;
                command.exec(self, &mut guard.model(), input).await
            }
        }

    }

    /// Read attributes, resolved beforehand, see [`BackendDev::read_attr`].
    async fn exec_read_attr(&self, targets: Vec<Resolved<AttrTarget<M>>>, mut ctx: ReadCtx<M>) -> 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, target| access.merge(self.read_access(target, &ctx)));

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

        // 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 reads = targets
            .iter()
            .map(|_| None)
            .collect::<Vec<_>>();

        for (target, slot) in targets.iter().zip(&mut reads) {
            if let Ok(AttrTarget::Attr(attr)) = target {
                let read = attr.read_with_alarm(self, &mut model).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) {
            *slot = Some(match target {
                Ok(AttrTarget::Attr(_)) => continue,
                Ok(AttrTarget::State(_)) => Named::new(Scalar::from(STATE_NAME), self.model_state(&mut model, &mut ctx).await
                    .map(|state| AttrRead::new(state.into()))),
                Ok(AttrTarget::Status(_)) => Named::new(Scalar::from(STATUS_NAME), self.model_status(&mut model, &mut ctx).await
                    .map(|status| AttrRead::new(status.into()))),
                Err(unresolved) => 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 target = self.resolve_attr(name)?;
        let attr = target.attr();

        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!("The configuration of the attribute {:?} of the device {:?} \
                    cannot be changed: {err}", attr.name(), self.name)))?;

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

        self.server().push_attr_conf(&self.name, attr.name(), target.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.del_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)>) -> 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()));

        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).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) -> &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.local_handle.lock().unwrap().take();
            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 serve(&self) -> Result<Arc<str>> {
        let backend = self.server().served_backend()?;
        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)
    }

}

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> {
    black_box: VecDeque<String>,
    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`].
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: bool) -> Self {

        let alarm = involves_state.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) -> Access {
        self.alarm.iter()
            .flat_map(|alarm| &alarm.attrs)
            .fold(Access::Shared, |access, alarm_attr| access.merge(alarm_attr.attr.read_access()))
    }

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

}

/// What a name a client asked an attribute of resolves to on a device: one of the two
/// attributes every Tango device has, whatever its class defines, or an attribute of its
/// interface, taken out of the interface store so that it is read with the store unlocked.
enum AttrTarget<M: Model> {
    State(Arc<Attr<M>>),
    Status(Arc<Attr<M>>),
    Attr(Arc<Attr<M>>),
}

impl<M: Model> AttrTarget<M> {

    /// Whether the request may have to derive the state of the device for that target,
    /// see [`ReadCtx::new`].
    fn involves_state(&self) -> bool {
        matches!(self, Self::State(_) | Self::Status(_))
    }

    /// The attribute of the device that target is, see [`Self::into_attr`].
    fn attr(&self) -> &Arc<Attr<M>> {
        match self {
            Self::State(attr) | 
            Self::Status(attr) | 
            Self::Attr(attr) => attr,
        }
    }

    /// The attribute of the device that target is, which holds its configuration.
    fn into_attr(self) -> Arc<Attr<M>> {
        match self {
            Self::State(attr) | 
            Self::Status(attr) | 
            Self::Attr(attr) => attr,
        }
    }

    /// What that attribute is named, which the entries answered for it are named by.
    fn name(&self) -> &str {
        match self {
            Self::State(attr) | 
            Self::Status(attr) | 
            Self::Attr(attr) => attr.name(),
        }
    }

    /// What a client is told of that attribute, the two every device has being read-only
    /// whatever their definitions, see [`Attr::info_as`].
    fn info(&self) -> Result<AttrInfo> {
        match self {
            Self::State(attr) | 
            Self::Status(attr) => attr.info_as(AttrMode::Read),
            Self::Attr(attr) => attr.info(),
        }
    }

}

/// What a name a client asked a command of resolves to on a device, the counterpart of
/// [`AttrTarget`] for the commands: the three every Tango device has, whatever its class, or a
/// command of its interface.
enum CommandTarget<M: Model> {
    State(Arc<Attr<M>>),
    Status(Arc<Attr<M>>),
    Init,
    Command(Arc<Command<M>>),
}

impl<M: Model> CommandTarget<M> {

    /// Whether the request may have to derive the state of the device for that target,
    /// see [`ReadCtx::new`].
    fn involves_state(&self) -> bool {
        matches!(self, Self::State(_) | Self::Status(_))
    }

    /// What that command is named, which the entries answered for it are named by.
    fn name(&self) -> &str {
        match self {
            Self::State(attr) | 
            Self::Status(attr) => attr.name(),
            Self::Init => INIT_NAME,
            Self::Command(command) => command.name(),
        }
    }

    /// What a client is told of that command, the three every device has being described by
    /// the server itself.
    fn info(&self) -> CommandInfo {
        match self {
            Self::State(_) => CommandInfo {
                display_level: DisplayLevel::Operator,
                in_kind: CommandDataKind::Void,
                out_kind: CommandDataKind::State,
                in_doc: None,
                out_doc: Some(Cow::Borrowed("The state of the device")),
            },
            Self::Status(_) => CommandInfo {
                display_level: DisplayLevel::Operator,
                in_kind: CommandDataKind::Void,
                out_kind: CommandDataKind::String,
                in_doc: None,
                out_doc: Some(Cow::Borrowed("The status of the device")),
            },
            Self::Init => CommandInfo {
                display_level: DisplayLevel::Operator,
                in_kind: CommandDataKind::Void,
                out_kind: CommandDataKind::Void,
                in_doc: None,
                out_doc: None,
            },
            Self::Command(command) => command.info(),
        }
    }

}

/// The error writing one of the two attributes every device has fails with: they are what
/// the device says of itself, not something a client tells it.
/// 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(),
    }
}

fn not_writable_err<M: Model>(dev: &Dev<M>, name: &str) -> Error {
    Error::new(ErrorKind::AttrNotWritable)
        .with_append_description(format_args!("Attribute {name:?} of the device {:?}",
            dev.name()))
}

/// Refuse to answer a request from the polling buffer, there being none: a client asking
/// for the cache alone is told that nothing is polled, and one that accepts both the cache
/// and the device is served by the device itself.
/// 
/// TODO: Answer from the polling buffer, once the server polls.
fn check_polled(source: DevSource, what: fmt::Arguments<'_>) -> Result<()> {
    match source {
        DevSource::Dev | DevSource::CacheDev => Ok(()),
        DevSource::Cache => Err(Error::new(ErrorKind::Reason(reason::API_DeviceNotPolled))
            .with_description(format!("Cannot answer from the polling cache, this server \
                polls nothing yet ({what})"))),
    }
}

/// 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(RwLockReadGuard<'a, Option<Result<M>>>),
    Exclusive(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,
        }
    }

    /// The model, borrowed with the access the lock was taken with.
    /// 
    /// # Panics
    /// 
    /// If the device has no model, which [`Dev::lock_model`] checks beforehand.
    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) -> String {
    format!("The initialization of the device failed:\n{err}")
}

/// 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_append_description(format_args!("Device {name:?}"))
            .with_append_description(err),
        None => Error::new(ErrorKind::DevNotConnected)
            .with_description(format!("The 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 a proxy made in this process to a device of this server
/// could talk to it directly, without going through any protocol.
#[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.
impl<M: Model> BackendDev for DevImpl<M> {

    fn name(&self) -> BoxFuture<'_, Result<Arc<str>>> {
        Box::pin(ready(Ok(Arc::clone(&self.0.name))))
    }

    fn admin_dev_name(&self) -> BoxFuture<'_, Result<Arc<str>>> {
        Box::pin(ready(Ok(Arc::clone(&self.0.server().admin_dev_name))))
    }

    fn description(&self) -> BoxFuture<'_, Result<Arc<str>>> {
        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>> {
        let def = self.0.class.def();
        let server = self.0.server();
        let backend = match server.served_backend() {
            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<()>> {
        Box::pin(ready(Ok(())))
    }

    fn state(&self) -> BoxFuture<'_, Result<DevState>> {
        let dev = self.0.arc();
        let mut ctx = ReadCtx::new(&dev, true);
        pool::run(dev.state_may_block(&ctx), async move { dev.state(&mut ctx).await })
    }

    fn status(&self) -> BoxFuture<'_, Result<String>> {
        let dev = self.0.arc();
        let mut ctx = ReadCtx::new(&dev, true);
        pool::run(dev.status_may_block(&ctx), async move { dev.status(&mut ctx).await })
    }

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

        let mutable = self.0.mutable.lock().unwrap();
        let black_box = mutable.black_box.iter()
            .take(max.unwrap_or(usize::MAX))
            .cloned()
            .collect();

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

    }

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

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

        let blocking = target.as_ref().is_ok_and(|target| dev.command_may_block(target, &ctx));
        pool::run(blocking, async move {
            let res = dev.exec_command(target, input, ctx).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) = check_polled(source, format_args!("the attributes of the device {}", self.0.name)) {
            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(AttrTarget::involves_state));

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

    }

    fn write_attr(&self, values: Vec<Named<Value>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {
        
        let dev = self.0.arc();
        let targets = values.into_iter()
            .map(|write| (dev.resolve_writable_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>>>>> {
        
        let dev = self.0.arc();
        let targets = values.into_iter()
            .map(|write| {
                let target = dev.resolve_writable_attr(write.name.value());
                (resolved(write.name, target), write.value)
            })
            .collect::<Vec<_>>();
        
        let blocking = targets.iter()
            .filter_map(|(target, _)| target.as_ref().ok())
            .any(|attr| attr.write_may_block() || attr.read_may_block());
        pool::run(blocking, async move { dev.exec_write_read_attr(targets).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>>>> {
        
        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)))

    }

    fn attr_info(&self, names: Option<Spectrum<str>>) -> BoxFuture<'_, Result<Vec<NamedResult<AttrInfo>>>> {
        
        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)))

    }

    /// The counterpart of [`Self::command_info`], and the same absence of any model.
    fn set_attr_config(&self, configs: Vec<Named<AttrConfig>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {
        Box::pin(async move { Ok(self.0.exec_set_attr_config(configs).await) })
    }

    fn command_history<'a>(&'a self, _name: &'a str, _max: usize) -> BoxFuture<'a, Result<Vec<(SystemTime, Result<Value>)>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_append_description("The recorded history of a command"))))
    }

    fn attr_history<'a>(&'a self, _name: &'a str, _max: usize) -> BoxFuture<'a, Result<Vec<Result<AttrRead<Value>>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_append_description("The recorded history of an attribute"))))
    }

    // 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<'a>(&'a self, _admin: Arc<dyn BackendDev>, name: &'a str, event: AttrValueEvent) -> BoxFuture<'a, Result<BoxStream<'static, Result<AttrRead<Value>>>>> {
        Box::pin(ready(self.0.resolve_attr(name).and_then(|target| {
            target.attr().check_push_event(&self.0, event)?;
            Ok(self.0.server().subscribe_attr_value(&self.0.name, target.name(), event))
        })))
    }

    fn subscribe_attr_ready<'a>(&'a self, _admin: Arc<dyn BackendDev>, name: &'a str) -> BoxFuture<'a, Result<BoxStream<'static, Result<()>>>> {
        Box::pin(ready(self.0.resolve_attr(name).map(|target| {
            self.0.server().subscribe_attr_ready(&self.0.name, target.name())
        })))
    }

    fn subscribe_attr_conf<'a>(&'a self, _admin: Arc<dyn BackendDev>, name: &'a str) -> BoxFuture<'a, Result<BoxStream<'static, Result<AttrInfo>>>> {
        Box::pin(ready(self.0.resolve_attr(name).map(|target| {
            self.0.server().subscribe_attr_conf(&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 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(Arc::clone(&dev.inner));
        drop(class);
        (ctx, dev)
    }

    #[test]
    fn push_event() {

        let (ctx, dev) = serve(model_def());
        let server = ctx.server("Test/test").unwrap();
        server.sync_blocking().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());

        // 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_blocking().unwrap();
        let mut conf = server.subscribe_attr_conf("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());

    }

    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 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))
            .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_blocking().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_blocking().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_blocking().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_blocking().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_blocking().unwrap();

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

    }

}