rstango 0.4.0

Implementation of the Tango distributed control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! The Tango database of a test, which answers the commands of the database device the
//! way `Databaseds` does, see [`super::TestContext`]. It is held in memory and made to tell
//! what it was asked and to fail on demand, which is what a test needs, and not what a
//! database meant to be used for real does.
//!
//! Its content is only ever altered through those very commands, that is through the
//! methods of a [`crate::database::DatabaseProxy`], so that what a test sets up is what a
//! real database would have been told.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::fmt;

use futures::future::{ready, BoxFuture};
use futures::stream::BoxStream;

use crate::dev::{AttrConfig, AttrInfo, AttrRead, AttrReady, AttrValueEvent, CommandInfo, DevInfo, DevSource, DevState, Named, NamedResult, RecordedResult};
use crate::error::{Error, ErrorKind, Result, reason};
use crate::value::{Scalar, Spectrum, Value};
use crate::backend::BackendDev;


/// The name the database device answers with, the one of a real database.
pub const NAME: &str = "sys/database/2";

/// The class of the admin device of every server.
const ADMIN_CLASS: &str = "DServer";

// =========================== //
//          Database           //
// =========================== //

/// The database of a test, held in memory, every name being looked up regardless of its
/// case, as `Databaseds` does.
///
/// Besides answering the commands of the database device, it records them, see
/// [`Self::log`], and can be made to fail some of them, see [`Self::add_fail`], which
/// is what testing how a server or a client copes with its database takes.
#[derive(Default)]
pub struct TestDatabase {
    state: Mutex<State>,
    /// Every command answered, in order, with its argument.
    log: Mutex<Vec<(String, Value)>>,
    /// The error each failing command fails with, by name.
    failing: Mutex<HashMap<String, Error>>,
}

impl fmt::Debug for TestDatabase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TestDatabase")
            .field("state", &self.state)
            .field("log", &self.log)
            .field("failing", &self.failing.lock().unwrap().keys())
            .finish()
    }
}

impl TestDatabase {

    /// Every command answered so far, in order, with its argument, those that failed
    /// included.
    pub fn log(&self) -> Vec<(String, Value)> {
        self.log.lock().unwrap().clone()
    }

    /// Forget every command answered so far, see [`Self::log`].
    pub fn clear_log(&self) {
        self.log.lock().unwrap().clear();
    }

    /// Fail every command of that name from now on, with that error, as a broken database
    /// does, until [`Self::remove_fail`].
    pub fn add_fail(&self, name: &str, err: Error) {
        self.failing.lock().unwrap().insert(name.to_string(), err);
    }

    /// Answer the commands of that name again, see [`Self::add_fail`].
    pub fn remove_fail(&self, name: &str) {
        self.failing.lock().unwrap().remove(name);
    }

    /// Answer a command of the database device.
    pub fn command(&self, name: &str, input: Value) -> Result<Value> {

        self.log.lock().unwrap().push((name.to_string(), input.clone()));

        if let Some(err) = self.failing.lock().unwrap().get(name) {
            return Err(err.clone());
        }

        let mut state = self.state.lock().unwrap();

        let res = match name {

            // Servers and devices.
            "DbAddServer" => state.add_server_cmd(input),
            "DbDeleteServer" => state.delete_server_cmd(input),
            "DbAddDevice" => state.add_dev_cmd(input),
            "DbDeleteDevice" => state.delete_dev_cmd(input),
            "DbGetDeviceClassList" => state.list_server_dev(input),

            // Exporting and importing.
            "DbExportDevice" | "DbExportServer" => state.export(input),
            "DbUnExportDevice" => state.unexport_dev(input),
            "DbUnExportServer" => state.unexport_server(input),
            "DbImportDevice" => state.import_dev(input),

            // Properties of devices and classes.
            "DbGetDeviceProperty" | "DbGetClassProperty" => state.get_prop(Kind::of(name), input),
            "DbGetDevicePropertyList" | "DbGetClassPropertyList" => state.list_prop(Kind::of(name), input),
            "DbPutDeviceProperty" | "DbPutClassProperty" => state.put_prop(Kind::of(name), input),
            "DbDeleteDeviceProperty" | "DbDeleteClassProperty" => state.delete_prop(Kind::of(name), input),

            // Properties of the attributes of devices and classes.
            "DbGetDeviceAttributeProperty2" | "DbGetClassAttributeProperty2" => state.get_attr_prop(Kind::of(name), input),
            "DbGetDeviceAttributeList" | "DbGetClassAttributeList" => state.list_attr(Kind::of(name), input),
            "DbPutDeviceAttributeProperty2" | "DbPutClassAttributeProperty2" => state.put_attr_prop(Kind::of(name), input),
            "DbDeleteDeviceAttributeProperty" | "DbDeleteClassAttributeProperty" => state.delete_attr_prop(Kind::of(name), input),

            _ => return Err(Error::not_implemented()
                .with_description(format!("Command {name:?} of the database of a test is not implemented"))),

        };

        res.map_err(|err| err.with_append_description(format_args!("Tried: command {name:?} of the database of a test")))

    }

}

/// What the database holds.
#[derive(Debug, Default)]
struct State {
    /// The lowercase names of the devices of each server, by lowercase `exe/inst` name, in
    /// the order they were added.
    servers: HashMap<String, Vec<String>>,
    /// The devices, by lowercase name.
    devs: HashMap<String, Dev>,
    /// The properties of each object.
    props: HashMap<Object, Props>,
    /// The properties of the attributes of each object.
    attr_props: HashMap<Object, Entries<Props>>,
}

/// One device, as it was defined and as it was last exported.
#[derive(Debug)]
struct Dev {
    name: String,
    class: String,
    server: String,
    /// What the device was last exported with, which a real database keeps once it is
    /// unexported, only the flag telling it is not running anymore.
    export: Option<Export>,
    exported: bool,
}

#[derive(Debug)]
struct Export {
    itr: String,
    host: String,
    version: String,
    pid: i32,
}

/// An object properties are of, a device or a class, by its lowercase name.
type Object = (Kind, String);

/// The kind of object a property is of.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Kind {
    Device,
    Class,
}

impl Kind {

    /// What a property command is about.
    fn of(command: &str) -> Self {
        if command.contains("Class") { Self::Class } else { Self::Device }
    }

    fn object(self, name: &str) -> Object {
        (self, name.to_lowercase())
    }

}

/// The properties of an object or an attribute, each with its values.
type Props = Entries<Vec<String>>;

/// Named entries, kept in the order they were first written and looked up regardless of
/// the case of their name, which keeps the case it was first written with.
#[derive(Debug)]
struct Entries<T>(Vec<(String, T)>);

impl<T> Default for Entries<T> {
    fn default() -> Self {
        Self(Vec::new())
    }
}

impl<T> Entries<T> {

    fn get(&self, name: &str) -> Option<&T> {
        self.0.iter().find(|(other, _)| other.eq_ignore_ascii_case(name)).map(|(_, value)| value)
    }

    /// The entry of that name, added empty if there is none.
    fn entry(&mut self, name: &str) -> &mut T where T: Default {
        let index = match self.0.iter().position(|(other, _)| other.eq_ignore_ascii_case(name)) {
            Some(index) => index,
            None => {
                self.0.push((name.to_string(), T::default()));
                self.0.len() - 1
            }
        };
        &mut self.0[index].1
    }

    /// Remove the entries of those names.
    fn remove(&mut self, names: &[String]) {
        self.0.retain(|(name, _)| !names.iter().any(|removed| removed.eq_ignore_ascii_case(name)));
    }

    /// The names matching a filter, see [`wildcard`].
    fn names(&self, filter: &str) -> Vec<&str> {
        self.0.iter().map(|(name, _)| name.as_str()).filter(|name| wildcard(filter, name)).collect()
    }

}

// -- Servers and devices --

impl State {

    /// The server, then a device and its class, as many times as it has some.
    fn add_server_cmd(&mut self, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [server, pairs @ ..] = &args[..] else { return Err(malformed_err()) };
        if pairs.len() % 2 != 0 {
            return Err(malformed_err());
        }
        self.add_server(server);
        for [dev, class] in pairs.as_chunks::<2>().0 {
            self.add_dev(server, dev, class);
        }
        Ok(Value::Void)
    }

    fn delete_server_cmd(&mut self, input: Value) -> Result<Value> {
        let server = String::try_from(input)?;
        for dev in self.servers.remove(&server.to_lowercase()).unwrap_or_default() {
            self.devs.remove(&dev);
        }
        Ok(Value::Void)
    }

    /// The server, the device and its class.
    fn add_dev_cmd(&mut self, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [server, dev, class] = &args[..] else { return Err(malformed_err()) };
        self.add_server(server);
        self.add_dev(server, dev, class);
        Ok(Value::Void)
    }

    fn delete_dev_cmd(&mut self, input: Value) -> Result<Value> {
        let dev = String::try_from(input)?.to_lowercase();
        if let Some(removed) = self.devs.remove(&dev) {
            self.server_devs(&removed.server).retain(|other| *other != dev);
        }
        Ok(Value::Void)
    }

    /// Every device of the server, then its class, one after the other.
    fn list_server_dev(&mut self, input: Value) -> Result<Value> {
        let server = String::try_from(input)?;
        let listing = self.servers.get(&server.to_lowercase())
            .into_iter()
            .flatten()
            .filter_map(|dev| self.devs.get(dev))
            .flat_map(|dev| [dev.name.as_str(), dev.class.as_str()])
            .collect::<Vec<_>>();
        Ok(Value::from(Spectrum::<str>::from(&listing[..])))
    }

    /// Define a server if it is not already, along with its admin device, as the tools
    /// registering a server do, since a server always exports it.
    fn add_server(&mut self, server: &str) {
        if !self.servers.contains_key(&server.to_lowercase()) {
            self.add_dev(server, &format!("dserver/{server}"), ADMIN_CLASS);
        }
    }

    /// Define a device in a server, moving it there if it was already defined in another
    /// one, as `Databaseds` does, what it was last exported with being kept.
    fn add_dev(&mut self, server: &str, name: &str, class: &str) {

        let key = name.to_lowercase();
        let previous = self.devs.remove(&key);

        if let Some(previous) = &previous {
            self.server_devs(&previous.server).retain(|other| *other != key);
        }
        self.server_devs(server).push(key.clone());

        let (export, exported) = previous.map_or((None, false), |dev| (dev.export, dev.exported));
        self.devs.insert(key, Dev {
            name: name.to_string(),
            class: class.to_string(),
            server: server.to_string(),
            export,
            exported,
        });

    }

    /// The devices of a server, which is defined with none if it was not.
    fn server_devs(&mut self, server: &str) -> &mut Vec<String> {
        self.servers.entry(server.to_lowercase()).or_default()
    }

}

// -- Exporting and importing --

impl State {

    /// Five strings per device: its name, its reference, its host, the process running it
    /// and its version.
    fn export(&mut self, input: Value) -> Result<Value> {
        let args = strings(input)?;
        if args.len() % 5 != 0 {
            return Err(malformed_err());
        }
        for [name, itr, host, pid, version] in args.as_chunks::<5>().0 {
            let dev = self.devs.get_mut(&name.to_lowercase())
                .ok_or_else(|| not_defined_err(name))?;
            dev.export = Some(Export {
                itr: itr.clone(),
                host: host.clone(),
                pid: pid.parse().map_err(|_| malformed_err())?,
                version: version.clone(),
            });
            dev.exported = true;
        }
        Ok(Value::Void)
    }

    fn unexport_dev(&mut self, input: Value) -> Result<Value> {
        let dev = String::try_from(input)?;
        if let Some(dev) = self.devs.get_mut(&dev.to_lowercase()) {
            dev.exported = false;
        }
        Ok(Value::Void)
    }

    fn unexport_server(&mut self, input: Value) -> Result<Value> {
        let server = String::try_from(input)?;
        for dev in self.servers.get(&server.to_lowercase()).into_iter().flatten() {
            if let Some(dev) = self.devs.get_mut(dev) {
                dev.exported = false;
            }
        }
        Ok(Value::Void)
    }

    /// The exported flag and the process, then the name, the reference, the version, the
    /// server, the host and the class.
    fn import_dev(&mut self, input: Value) -> Result<Value> {
        let name = String::try_from(input)?;
        let dev = self.devs.get(&name.to_lowercase())
            .ok_or_else(|| not_defined_err(&name))?;
        let (itr, version, host, pid) = match &dev.export {
            Some(export) => (&*export.itr, &*export.version, &*export.host, export.pid),
            None => ("nada", "0", "nada", 0),
        };
        let strings = [&*dev.name, itr, version, &*dev.server, host, &*dev.class];
        Ok(Value::LongString(
            Spectrum::from(vec![i32::from(dev.exported), pid]),
            Spectrum::<str>::from(&strings[..]),
        ))
    }

}

// -- Properties --

impl State {

    /// The object, then the properties, answered with the object and how many properties,
    /// then each property with how many values it has and its values, a property that has
    /// none being said to have none.
    fn get_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, prop_names @ ..] = &args[..] else { return Err(malformed_err()) };
        let props = self.props.get(&kind.object(obj_name));
        let mut listing = vec![obj_name.clone(), prop_names.len().to_string()];
        for prop_name in prop_names {
            let values = props.and_then(|props| props.get(prop_name)).map_or(&[][..], Vec::as_slice);
            listing.push(prop_name.clone());
            listing.push(values.len().to_string());
            listing.extend(values.iter().cloned());
        }
        Ok(Value::from(Spectrum::<str>::from(&listing[..])))
    }

    /// The object and a filter.
    fn list_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, filter] = &args[..] else { return Err(malformed_err()) };
        let names = self.props.get(&kind.object(obj_name)).map_or_else(Vec::new, |props| props.names(filter));
        Ok(Value::from(Spectrum::<str>::from(&names[..])))
    }

    /// The object and how many properties, then each property with how many values it has
    /// and its values.
    fn put_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let mut cursor = Cursor::new(&args);
        let props = self.props.entry(kind.object(cursor.next()?)).or_default();
        for _ in 0..cursor.count()? {
            let prop_name = cursor.next()?;
            *props.entry(prop_name) = cursor.values()?.to_vec();
        }
        cursor.end()?;
        Ok(Value::Void)
    }

    /// The object, then the properties.
    fn delete_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, prop_names @ ..] = &args[..] else { return Err(malformed_err()) };
        if let Some(props) = self.props.get_mut(&kind.object(obj_name)) {
            props.remove(prop_names);
        }
        Ok(Value::Void)
    }

}

// -- Properties of attributes --

impl State {

    /// The object, then the attributes, answered with the object and how many attributes,
    /// then each attribute with how many properties it has, then each property with how
    /// many values it has and its values.
    fn get_attr_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, attr_names @ ..] = &args[..] else { return Err(malformed_err()) };
        let attrs = self.attr_props.get(&kind.object(obj_name));
        let mut listing = vec![obj_name.clone(), attr_names.len().to_string()];
        for attr_name in attr_names {
            let props = attrs.and_then(|attrs| attrs.get(attr_name)).map_or(&[][..], |props| &props.0[..]);
            listing.push(attr_name.clone());
            listing.push(props.len().to_string());
            for (prop_name, values) in props {
                listing.push(prop_name.clone());
                listing.push(values.len().to_string());
                // A property holding no value is followed by a placeholder, which is what
                // the database server sends for one.
                if values.is_empty() {
                    listing.push(" ".to_string());
                }
                listing.extend(values.iter().cloned());
            }
        }
        Ok(Value::from(Spectrum::<str>::from(&listing[..])))
    }

    /// The object and a filter.
    fn list_attr(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, filter] = &args[..] else { return Err(malformed_err()) };
        let names = self.attr_props.get(&kind.object(obj_name)).map_or_else(Vec::new, |attrs| attrs.names(filter));
        Ok(Value::from(Spectrum::<str>::from(&names[..])))
    }

    /// The object and how many attributes, then each attribute with how many properties it
    /// has, then each property with how many values it has and its values.
    fn put_attr_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let mut cursor = Cursor::new(&args);
        let attrs = self.attr_props.entry(kind.object(cursor.next()?)).or_default();
        for _ in 0..cursor.count()? {
            let props = attrs.entry(cursor.next()?);
            for _ in 0..cursor.count()? {
                let prop_name = cursor.next()?;
                *props.entry(prop_name) = cursor.values()?.to_vec();
            }
        }
        cursor.end()?;
        Ok(Value::Void)
    }

    /// The object and the attribute, then the properties.
    fn delete_attr_prop(&mut self, kind: Kind, input: Value) -> Result<Value> {
        let args = strings(input)?;
        let [obj_name, attr_name, prop_names @ ..] = &args[..] else { return Err(malformed_err()) };
        if let Some(attrs) = self.attr_props.get_mut(&kind.object(obj_name)) {
            attrs.entry(attr_name).remove(prop_names);
            // An attribute left with no property is no longer listed.
            attrs.0.retain(|(_, props)| !props.0.is_empty());
        }
        Ok(Value::Void)
    }

}

// -- Arguments --

/// Reading a command argument made of counted runs of strings.
struct Cursor<'a> {
    args: &'a [String],
    pos: usize,
}

impl<'a> Cursor<'a> {

    fn new(args: &'a [String]) -> Self {
        Self { args, pos: 0 }
    }

    fn next(&mut self) -> Result<&'a str> {
        let arg = self.args.get(self.pos).ok_or_else(malformed_err)?;
        self.pos += 1;
        Ok(arg)
    }

    fn count(&mut self) -> Result<usize> {
        self.next()?.parse().map_err(|_| malformed_err())
    }

    /// A count, then that many values.
    fn values(&mut self) -> Result<&'a [String]> {
        let len = self.count()?;
        let values = self.args.get(self.pos..self.pos + len).ok_or_else(malformed_err)?;
        self.pos += len;
        Ok(values)
    }

    /// Fail if anything was left unread, which is a count that does not match.
    fn end(&self) -> Result<()> {
        match self.pos == self.args.len() {
            true => Ok(()),
            false => Err(malformed_err()),
        }
    }

}

/// The strings of a command argument.
fn strings(input: Value) -> Result<Vec<String>> {
    Vec::<String>::try_from(input)
}

/// Whether a name matches a filter of the database, in which `*` stands for anything,
/// regardless of case.
fn wildcard(filter: &str, name: &str) -> bool {

    let (filter, name) = (filter.to_lowercase(), name.to_lowercase());
    let mut parts = filter.split('*');

    // Without any star the filter is the name itself.
    let first = parts.next().unwrap_or_default();
    let Some(mut rest) = name.strip_prefix(first) else { return false };

    let parts = parts.collect::<Vec<_>>();
    let Some((last, middle)) = parts.split_last() else { return rest.is_empty() };

    for part in middle {
        match rest.find(part) {
            Some(index) => rest = &rest[index + part.len()..],
            None => return false,
        }
    }

    rest.ends_with(last)

}

fn malformed_err() -> Error {
    Error::new(ErrorKind::InvalidData)
        .with_description("Argument is malformed")
}

fn not_defined_err(dev: &str) -> Error {
    Error::new(ErrorKind::Reason(reason::DB_DeviceNotDefined))
        .with_description(format!("Device {dev:?} is not defined in the database"))
}

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

/// The database device, as a client reaches it.
#[derive(Debug)]
pub struct TestDatabaseDev(pub Arc<TestDatabase>);

fn not_implemented<'a, T: Send + 'a>(what: &'static str) -> BoxFuture<'a, Result<T>> {
    Box::pin(ready(Err(Error::not_implemented()
        .with_description(format!("{what} of the database of a test is not implemented")))))
}

impl BackendDev for TestDatabaseDev {

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

    fn admin_dev_name(&self) -> BoxFuture<'_, Result<Arc<str>>> {
        not_implemented("Getting the admin device")
    }

    fn description(&self) -> BoxFuture<'_, Result<Arc<str>>> {
        Box::pin(ready(Ok(Arc::from("The Tango database of a test"))))
    }

    fn info(&self) -> BoxFuture<'_, Result<DevInfo>> {
        not_implemented("Getting the info")
    }

    fn ping(&self) -> BoxFuture<'_, Result<()>> {
        Box::pin(ready(Ok(())))
    }

    fn state(&self) -> BoxFuture<'_, Result<DevState>> {
        Box::pin(ready(Ok(DevState::On)))
    }

    fn status(&self) -> BoxFuture<'_, Result<Scalar<str>>> {
        Box::pin(ready(Ok(Scalar::from("The database of a test"))))
    }

    fn black_box(&self, _max: Option<usize>) -> BoxFuture<'_, Result<Spectrum<str>>> {
        not_implemented("Reading the black box")
    }

    fn command(&self, name: Scalar<str>, input: Value, _source: DevSource) -> BoxFuture<'_, Result<Value>> {
        Box::pin(ready(self.0.command(name.value(), input)))
    }

    fn read_attr(&self, _names: Option<Spectrum<str>>, _source: DevSource) -> BoxFuture<'_, Result<Vec<NamedResult<AttrRead<Value>>>>> {
        not_implemented("Reading the attributes")
    }

    fn write_attr(&self, _values: Vec<Named<Value>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {
        not_implemented("Writing the attributes")
    }

    fn write_read_attr(&self, _values: Vec<Named<Value>>) -> BoxFuture<'_, Result<Vec<NamedResult<AttrRead<Value>>>>> {
        not_implemented("Writing the attributes")
    }

    fn command_info(&self, _names: Option<Spectrum<str>>) -> BoxFuture<'_, Result<Vec<NamedResult<CommandInfo>>>> {
        not_implemented("Listing the commands")
    }

    fn attr_info(&self, _names: Option<Spectrum<str>>) -> BoxFuture<'_, Result<Vec<NamedResult<AttrInfo>>>> {
        not_implemented("Listing the attributes")
    }

    fn set_attr_config(&self, _configs: Vec<Named<AttrConfig>>) -> BoxFuture<'_, Result<Vec<Result<()>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Writing the configuration of an attribute is not implemented"))))
    }

    fn command_history(&self, _name: Scalar<str>, _max: usize) -> BoxFuture<'_, Result<Vec<RecordedResult<Value>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Reading the recorded history of a command is not implemented"))))
    }

    fn attr_history(&self, _name: Scalar<str>, _max: usize) -> BoxFuture<'_, Result<Vec<RecordedResult<AttrRead<Value>>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Reading the recorded history of an attribute is not implemented"))))
    }

    fn subscribe_attr_value(&self, _admin: Arc<dyn BackendDev>, _name: Scalar<str>, _event: AttrValueEvent) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrRead<Value>>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Subscribing to the readings of an attribute is not implemented"))))
    }

    fn subscribe_attr_ready(&self, _admin: Arc<dyn BackendDev>, _name: Scalar<str>) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrReady>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Subscribing to an attribute being ready is not implemented"))))
    }

    fn subscribe_attr_config(&self, _admin: Arc<dyn BackendDev>, _name: Scalar<str>) -> BoxFuture<'_, Result<BoxStream<'static, Result<AttrInfo>>>> {
        Box::pin(ready(Err(Error::not_implemented()
            .with_description("Subscribing to the configuration of an attribute is not implemented"))))
    }

}

#[cfg(test)]
mod tests {

    use super::*;

    use crate::database::ExportDevInfo;
    use crate::testing::TestContext;

    fn context() -> TestContext {
        TestContext::new().unwrap()
    }

    #[test]
    fn wildcards() {
        assert!(wildcard("*", "anything"));
        assert!(wildcard("Pos*", "position"));
        assert!(wildcard("*tion", "Position"));
        assert!(wildcard("p*s*n", "position"));
        assert!(wildcard("position", "POSITION"));
        assert!(!wildcard("pos", "position"));
        assert!(!wildcard("p*x*n", "position"));
    }

    #[test]
    fn servers_and_devices() {

        let ctx = context();
        let db = ctx.database();
        db.add_server("Motor/test", &[("test/motor/1", "Motor"), ("test/motor/2", "Motor")]).unwrap();
        db.add_dev("test/axis/1", "Axis", "Motor/test").unwrap();

        let listed = db.list_server_dev("motor/TEST").unwrap();
        let listed = listed.iter().map(|dev| (dev.name.value(), dev.value.value())).collect::<Vec<_>>();
        assert_eq!(listed, [
            ("dserver/Motor/test", "DServer"),
            ("test/motor/1", "Motor"),
            ("test/motor/2", "Motor"),
            ("test/axis/1", "Axis"),
        ]);

        db.delete_dev("TEST/MOTOR/2").unwrap();
        assert_eq!(db.list_server_dev("Motor/test").unwrap().len(), 3);

        db.delete_server("Motor/test").unwrap();
        assert!(db.list_server_dev("Motor/test").unwrap().is_empty());
        assert_eq!(db.import_dev("test/motor/1").unwrap_err().kind(), ErrorKind::DevNotFound);

    }

    #[test]
    fn export_and_import() {

        let ctx = context();
        let db = ctx.database();
        db.add_dev("test/motor/1", "Motor", "Motor/test").unwrap();

        let info = db.import_dev("test/motor/1").unwrap();
        assert!(!info.exported);
        assert_eq!(info.class.as_ref().map(|class| class.value()), Some("Motor"));

        db.export_server(&[ExportDevInfo {
            name: "test/motor/1".into(),
            itr: "IOR:0123".into(),
            host: "localhost".into(),
            version: "6".into(),
            pid: 42,
        }]).unwrap();

        let info = db.import_dev("test/motor/1").unwrap();
        assert!(info.exported);
        assert_eq!((info.itr.value(), info.host.value(), info.version.value(), info.server.value(), info.pid),
            ("IOR:0123", "localhost", "6", "Motor/test", 42));

        // Unexported, the reference stays, only the flag goes down.
        db.unexport_server("motor/test").unwrap();
        let info = db.import_dev("test/motor/1").unwrap();
        assert!(!info.exported);
        assert_eq!(info.itr.value(), "IOR:0123");

    }

    #[test]
    fn properties() {

        let ctx = context();
        let db = ctx.database();

        db.set_dev_prop("test/motor/1", [("Limit", "90"), ("Unit", "deg")]).unwrap();
        db.set_dev_prop("TEST/motor/1", ("limit", "45")).unwrap();
        assert_eq!(db.get_dev_prop::<f64, _>("test/motor/1", "Limit").unwrap(), 45.0);
        assert_eq!(db.list_dev_prop("test/motor/1", "*").unwrap().len(), 2);

        db.delete_dev_prop("test/motor/1", "unit").unwrap();
        assert_eq!(db.list_dev_prop("test/motor/1", "*").unwrap().len(), 1);

        // Classes and devices do not share their properties.
        db.set_class_prop("Motor", ("Limit", "10")).unwrap();
        assert_eq!(db.get_class_prop::<f64, _>("Motor", "Limit").unwrap(), 10.0);
        assert_eq!(db.get_dev_prop::<f64, _>("test/motor/1", "Limit").unwrap(), 45.0);

        db.set_dev_attr_prop("test/motor/1", ("Position", [("unit", "mm"), ("min_value", "-5")])).unwrap();
        assert_eq!(db.get_dev_attr_prop::<String, _, _>("test/motor/1", "position", "Unit").unwrap(), "mm");

        db.delete_dev_attr_prop("test/motor/1", "Position", ["unit", "min_value"]).unwrap();
        // A property that has no value anymore reads as one holding nothing.
        assert_eq!(db.get_dev_attr_prop::<String, _, _>("test/motor/1", "Position", "unit").unwrap(), "");

    }

    /// Every clone of the proxy reaches the same database, and two databases are two.
    #[test]
    fn clones_share() {
        let ctx = context();
        let db = ctx.database();
        let clone = db.clone();
        clone.add_dev("test/motor/1", "Motor", "Motor/test").unwrap();
        assert_eq!(db.list_server_dev("Motor/test").unwrap().len(), 2);
        let other = context();
        assert!(other.database().list_server_dev("Motor/test").unwrap().is_empty());
        assert_ne!(db, other.database());
    }

}