Skip to main content

link_cli/
union_links.rs

1//! Many links networks seen as one (issue #149): the joining layer of a
2//! client's links with a server's, of a cache with its source, of the networks
3//! of several services.
4//!
5//! The members are in order, and the link at an address is the one of the
6//! first member that has it: a member shadows the ones after it, as a local
7//! overlay of minimongo or minilinks shadows the documents of the server.
8//! Reads see the links of every member that are not shadowed. Members whose
9//! addresses do not overlap (a [`RemapLinks`](crate::RemapLinks) with an
10//! [`OffsetAddressMap`](crate::OffsetAddressMap) moves one out of the way of
11//! another) shadow nothing.
12//!
13//! A new link is created in the first member, the primary one. An update, a
14//! delete and naming go to the member that has the link, so a link stays where
15//! it lives; the store of that member resolves the write, merges and cascades
16//! included, which keep to that member: a doublet is unique within its member,
17//! not across them. A link created at a given address
18//! ([`ensure_created`](NamedTypeLinks::ensure_created), the undo of a delete)
19//! is created in the first member that [claims](NamedTypeLinks::claims) the
20//! address, as a remap claims the addresses of its map, and in the primary
21//! member when none does.
22//!
23//! A link may refer to links of other members: a link of the client typed by
24//! a type of the server holds the address of the server's type. Names are
25//! found in the members in order, so a name of the primary member wins.
26//!
27//! The union depends on no other layer. A
28//! [`PermissionsDecorator`](crate::PermissionsDecorator) over it restricts
29//! every member at once, its rules and types coming from any of them, and one
30//! under it restricts a single member. The C# twin is
31//! `UnionLinksDecorator<TLinkAddress>`, the JavaScript one `UnionLinks` of
32//! `@link-foundation/link-cli-client`.
33
34use anyhow::{bail, Result};
35
36use crate::error::LinkError;
37use crate::link::Link;
38use crate::link_storage::ChangeObserver;
39use crate::named_type_links::NamedTypeLinks;
40
41/// A member of a union: any store, owned or borrowed.
42pub type UnionMember<'a> = Box<dyn NamedTypeLinks + 'a>;
43
44/// Networks seen as one; see the [module documentation](self).
45pub struct UnionLinks<'a> {
46    members: Vec<UnionMember<'a>>,
47}
48
49impl<'a> UnionLinks<'a> {
50    /// The networks `members`, the primary one first.
51    pub fn new(members: Vec<UnionMember<'a>>) -> Result<Self> {
52        if members.is_empty() {
53            bail!("A union needs at least one network.");
54        }
55        Ok(Self { members })
56    }
57
58    /// The networks, the primary one first.
59    pub fn members(&self) -> &[UnionMember<'a>] {
60        &self.members
61    }
62
63    /// The networks, the primary one first.
64    pub fn members_mut(&mut self) -> &mut [UnionMember<'a>] {
65        &mut self.members
66    }
67
68    /// The member new links are created in.
69    pub fn primary(&mut self) -> &mut (dyn NamedTypeLinks + 'a) {
70        &mut *self.members[0]
71    }
72
73    /// The position of the member that has the link at `index`, `None` when
74    /// none has it.
75    pub fn owner_of(&mut self, index: u32) -> Option<usize> {
76        if index == 0 {
77            return None;
78        }
79        self.members
80            .iter_mut()
81            .position(|member| member.exists(index))
82    }
83
84    /// Whether a member before the one at `member` has a link at `index`.
85    fn shadowed(&mut self, member: usize, index: u32) -> bool {
86        self.members[..member]
87            .iter_mut()
88            .any(|before| before.exists(index))
89    }
90
91    /// The member that has the link at `index`; an error when none has it.
92    fn owner(&mut self, index: u32) -> Result<&mut (dyn NamedTypeLinks + 'a)> {
93        match self.owner_of(index) {
94            Some(owner) => Ok(&mut *self.members[owner]),
95            None => Err(LinkError::not_found(index).into()),
96        }
97    }
98
99    /// The member that has the link at `index`, the primary one when none has it.
100    fn owner_or_primary(&mut self, index: u32) -> &mut (dyn NamedTypeLinks + 'a) {
101        let owner = self.owner_of(index).unwrap_or(0);
102        &mut *self.members[owner]
103    }
104
105    /// The position of the member a new link at `index` is created in: the
106    /// first that claims it, the primary one when none does.
107    fn place_of(&mut self, index: u32) -> usize {
108        self.members
109            .iter_mut()
110            .position(|member| member.claims(index) == Some(true))
111            .unwrap_or(0)
112    }
113
114    /// The links of every member that match, the shadowed ones left out.
115    fn unshadowed(
116        &mut self,
117        mut read: impl FnMut(&mut dyn NamedTypeLinks) -> Vec<Link>,
118    ) -> Vec<Link> {
119        let mut all = Vec::new();
120        for member in 0..self.members.len() {
121            let links = read(&mut *self.members[member]);
122            for link in links {
123                if !self.shadowed(member, link.index) {
124                    all.push(link);
125                }
126            }
127        }
128        all.sort_unstable_by_key(|link| link.index);
129        all
130    }
131}
132
133impl NamedTypeLinks for UnionLinks<'_> {
134    fn create(&mut self, source: u32, target: u32) -> u32 {
135        self.primary().create(source, target)
136    }
137
138    fn ensure_created(&mut self, id: u32) -> u32 {
139        self.try_ensure_created(id)
140            .unwrap_or_else(|error| panic!("{error}"))
141    }
142
143    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
144        if id != 0 && self.owner_of(id).is_some() {
145            return Ok(id);
146        }
147        let place = self.place_of(id);
148        self.members[place].try_ensure_created(id)
149    }
150
151    fn get_link(&mut self, id: u32) -> Option<Link> {
152        let owner = self.owner_of(id)?;
153        self.members[owner].get_link(id)
154    }
155
156    fn exists(&mut self, id: u32) -> bool {
157        self.owner_of(id).is_some()
158    }
159
160    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
161        self.primary().try_create(source, target)
162    }
163
164    fn reference_exists(&mut self, id: u32) -> bool {
165        self.members
166            .iter_mut()
167            .any(|member| member.reference_exists(id))
168    }
169
170    /// A plain member has every address; a composed one those it claims.
171    fn claims(&mut self, id: u32) -> Option<bool> {
172        Some(
173            self.members
174                .iter_mut()
175                .any(|member| member.claims(id) != Some(false)),
176        )
177    }
178
179    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
180        self.primary().next_created_addresses(count)
181    }
182
183    fn update_observed(
184        &mut self,
185        id: u32,
186        source: u32,
187        target: u32,
188        observer: ChangeObserver<'_>,
189    ) -> Result<Link> {
190        self.owner(id)?
191            .update_observed(id, source, target, observer)
192    }
193
194    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
195        self.owner(id)?.delete_observed(id, observer)
196    }
197
198    fn all_links(&mut self) -> Vec<Link> {
199        self.unshadowed(|member| member.all_links())
200    }
201
202    fn query_links(
203        &mut self,
204        index: Option<u32>,
205        source: Option<u32>,
206        target: Option<u32>,
207    ) -> Vec<Link> {
208        self.unshadowed(|member| member.query_links(index, source, target))
209    }
210
211    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
212        for member in 0..self.members.len() {
213            if let Some(found) = self.members[member].search(source, target) {
214                if !self.shadowed(member, found) {
215                    return Some(found);
216                }
217            }
218        }
219        None
220    }
221
222    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
223        match self.search(source, target) {
224            Some(found) => found,
225            None => self.create(source, target),
226        }
227    }
228
229    /// The name of `id` in the member that has it, else in the first member
230    /// that names it.
231    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
232        if let Some(owner) = self.owner_of(id) {
233            return self.members[owner].get_name(id);
234        }
235        for member in self.members.iter_mut() {
236            if let Some(name) = member.get_name(id)? {
237                return Ok(Some(name));
238            }
239        }
240        Ok(None)
241    }
242
243    /// Names `id` in the member that has it, the primary one when none does.
244    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
245        self.owner_or_primary(id).set_name(id, name)
246    }
247
248    /// The link of `name` in the first member that has a link of that name
249    /// it does not shadow.
250    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
251        for member in 0..self.members.len() {
252            if let Some(found) = self.members[member].get_by_name(name)? {
253                if found != 0 && !self.shadowed(member, found) {
254                    return Ok(Some(found));
255                }
256            }
257        }
258        Ok(None)
259    }
260
261    /// Unnames `id` in the member that has it, the primary one when none does.
262    fn remove_name(&mut self, id: u32) -> Result<()> {
263        self.owner_or_primary(id).remove_name(id)
264    }
265
266    fn save(&mut self) -> Result<()> {
267        for member in self.members.iter_mut() {
268            member.save()?;
269        }
270        Ok(())
271    }
272
273    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
274        if let Some(id) = self.get_by_name(name)? {
275            return Ok(id);
276        }
277        let id = self.try_create(0, 0)?;
278        self.set_name(id, name)?;
279        self.update(id, id, id)?;
280        Ok(id)
281    }
282}