1use super::client::LinksClient;
33use super::error::{ProtocolError, ProtocolResult};
34use super::links_operations::{
35 parse_changes, parse_count, parse_link_reply, parse_links, parse_name, parse_notification,
36 parse_subscription, Change, LinksNotification, LinksOperation, Part,
37};
38use super::protocols::LinoProtocol;
39use crate::link::Link;
40use crate::link_storage::ChangeObserver;
41use crate::link_storage_doublets::link_storage_constants;
42use crate::named_type_links::NamedTypeLinks;
43use crate::triplets::TripletMarkers;
44use doublets::data::{Flow, LinksConstants, ReadHandler, WriteHandler};
45use doublets::{Doublets, Error, Link as DoubletsLink, Links};
46use links_notation::binary::LinoDocument;
47use std::net::ToSocketAddrs;
48use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
49use std::time::Duration;
50
51#[derive(Debug)]
54pub struct RemoteLinks {
55 client: Mutex<LinksClient>,
56 pub(super) triplet_markers: OnceLock<TripletMarkers>,
58}
59
60impl RemoteLinks {
61 pub fn connect(
63 address: impl ToSocketAddrs,
64 protocol: impl LinoProtocol + 'static,
65 ) -> ProtocolResult<Self> {
66 Ok(Self::new(LinksClient::connect(address, protocol)?))
67 }
68
69 pub fn new(client: LinksClient) -> Self {
71 Self {
72 client: Mutex::new(client),
73 triplet_markers: OnceLock::new(),
74 }
75 }
76
77 pub fn execute(&self, operation: &LinksOperation) -> ProtocolResult<LinoDocument> {
79 self.client().request(&operation.to_document())
80 }
81
82 pub fn subscribe(&self, restriction: &[Part]) -> ProtocolResult<u32> {
86 parse_subscription(&self.execute(&LinksOperation::Subscribe(restriction.to_vec()))?)
87 }
88
89 pub fn unsubscribe(&self, subscription: u32) -> ProtocolResult<()> {
91 self.execute(&LinksOperation::Unsubscribe(subscription))?;
92 Ok(())
93 }
94
95 pub fn receive_notification(
98 &self,
99 timeout: Duration,
100 ) -> ProtocolResult<Option<LinksNotification>> {
101 self.client()
102 .receive_notification(timeout)?
103 .map(|document| parse_notification(&document))
104 .transpose()
105 }
106
107 pub(super) fn client(&self) -> MutexGuard<'_, LinksClient> {
108 self.client.lock().unwrap_or_else(PoisonError::into_inner)
109 }
110
111 pub fn count_matching(&self, restriction: &[Part]) -> ProtocolResult<u32> {
113 parse_count(&self.execute(&LinksOperation::Count(restriction.to_vec()))?)
114 }
115
116 pub fn links_matching(&self, restriction: &[Part]) -> ProtocolResult<Vec<Link>> {
118 parse_links(&self.execute(&LinksOperation::Each(restriction.to_vec()))?)
119 }
120
121 pub fn changes(&self, operation: &LinksOperation) -> ProtocolResult<Vec<Change>> {
123 parse_changes(&self.execute(operation)?)
124 }
125
126 pub fn link(&self, index: u32) -> ProtocolResult<Option<Link>> {
128 Ok(self.links_matching(&[Some(index)])?.pop())
129 }
130
131 fn create_remote(&self, source: u32, target: u32) -> ProtocolResult<Link> {
132 self.changes(&LinksOperation::Create { source, target })?
133 .into_iter()
134 .find_map(|(before, after)| (before.is_null() && !after.is_null()).then_some(after))
135 .ok_or_else(|| ProtocolError::malformed("the create reply holds no created link"))
136 }
137
138 fn observed(
141 &self,
142 operation: &LinksOperation,
143 index: u32,
144 observer: ChangeObserver<'_>,
145 ) -> ProtocolResult<Link> {
146 let changes = self.changes(operation)?;
147 for (before, after) in &changes {
148 observer(*before, *after);
149 }
150 changes
151 .iter()
152 .find(|(before, _)| before.index == index)
153 .map(|(before, _)| *before)
154 .ok_or_else(|| {
155 ProtocolError::malformed(format!("the reply holds no change of {index}"))
156 })
157 }
158
159 fn parts(&self, query: &[u32]) -> Vec<Part> {
160 let any = self.constants().any;
161 query
162 .iter()
163 .map(|&part| (part != any).then_some(part))
164 .collect()
165 }
166}
167
168pub(super) fn connected<T>(result: ProtocolResult<T>) -> T {
171 result.unwrap_or_else(|error| panic!("remote links store failed: {error}"))
172}
173
174fn doublets_link(link: &Link) -> DoubletsLink<u32> {
175 DoubletsLink::new(link.index, link.source, link.target)
176}
177
178fn doublets_error(error: ProtocolError) -> Error<u32> {
179 Error::Other(Box::new(error))
180}
181
182fn replay(changes: &[Change], handler: WriteHandler<'_, u32>) -> Flow {
184 for (before, after) in changes {
185 if handler(doublets_link(before), doublets_link(after)) == Flow::Break {
186 return Flow::Break;
187 }
188 }
189 Flow::Continue
190}
191
192fn part(query: &[u32], index: usize) -> u32 {
193 query.get(index).copied().unwrap_or(0)
194}
195
196impl Links<u32> for RemoteLinks {
197 fn constants(&self) -> &LinksConstants<u32> {
198 link_storage_constants()
199 }
200
201 fn count_links(&self, query: &[u32]) -> u32 {
202 connected(self.count_matching(&self.parts(query)))
203 }
204
205 fn create_links(
207 &mut self,
208 _query: &[u32],
209 handler: WriteHandler<'_, u32>,
210 ) -> Result<Flow, Error<u32>> {
211 let changes = self
212 .changes(&LinksOperation::Create {
213 source: 0,
214 target: 0,
215 })
216 .map_err(doublets_error)?;
217 Ok(replay(&changes, handler))
218 }
219
220 fn each_links(&self, query: &[u32], handler: ReadHandler<'_, u32>) -> Flow {
221 for link in connected(self.links_matching(&self.parts(query))) {
222 if handler(doublets_link(&link)) == Flow::Break {
223 return Flow::Break;
224 }
225 }
226 Flow::Continue
227 }
228
229 fn update_links(
230 &mut self,
231 query: &[u32],
232 change: &[u32],
233 handler: WriteHandler<'_, u32>,
234 ) -> Result<Flow, Error<u32>> {
235 let changes = self
236 .changes(&LinksOperation::Update {
237 index: part(query, 0),
238 source: part(change, 1),
239 target: part(change, 2),
240 })
241 .map_err(doublets_error)?;
242 Ok(replay(&changes, handler))
243 }
244
245 fn delete_links(
246 &mut self,
247 query: &[u32],
248 handler: WriteHandler<'_, u32>,
249 ) -> Result<Flow, Error<u32>> {
250 let changes = self
251 .changes(&LinksOperation::Delete(part(query, 0)))
252 .map_err(doublets_error)?;
253 Ok(replay(&changes, handler))
254 }
255}
256
257impl Doublets<u32> for RemoteLinks {
258 fn get_link(&self, index: u32) -> Option<DoubletsLink<u32>> {
259 connected(self.link(index)).as_ref().map(doublets_link)
260 }
261}
262
263impl NamedTypeLinks for RemoteLinks {
264 fn create(&mut self, source: u32, target: u32) -> u32 {
265 connected(self.create_remote(source, target)).index
266 }
267
268 fn ensure_created(&mut self, id: u32) -> u32 {
271 if id == 0 || self.exists(id) {
272 return id;
273 }
274 let mut passed_over = Vec::new();
275 loop {
276 let created = NamedTypeLinks::create(self, 0, 0);
277 if created == id {
278 break;
279 }
280 passed_over.push(created);
281 }
282 for address in passed_over {
283 connected(self.changes(&LinksOperation::Delete(address)));
284 }
285 id
286 }
287
288 fn get_link(&mut self, id: u32) -> Option<Link> {
289 connected(self.link(id))
290 }
291
292 fn exists(&mut self, id: u32) -> bool {
295 connected(self.count_matching(&[Some(id)])) > 0
296 }
297
298 fn update_observed(
299 &mut self,
300 id: u32,
301 source: u32,
302 target: u32,
303 observer: ChangeObserver<'_>,
304 ) -> anyhow::Result<Link> {
305 let operation = LinksOperation::Update {
306 index: id,
307 source,
308 target,
309 };
310 Ok(self.observed(&operation, id, observer)?)
311 }
312
313 fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> anyhow::Result<Link> {
314 Ok(self.observed(&LinksOperation::Delete(id), id, observer)?)
315 }
316
317 fn all_links(&mut self) -> Vec<Link> {
318 connected(self.links_matching(&[]))
319 }
320
321 fn search(&mut self, source: u32, target: u32) -> Option<u32> {
322 connected(self.links_matching(&[None, Some(source), Some(target)]))
323 .first()
324 .map(|link| link.index)
325 }
326
327 fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
328 match self.search(source, target) {
329 Some(index) => index,
330 None => NamedTypeLinks::create(self, source, target),
331 }
332 }
333
334 fn get_name(&mut self, id: u32) -> anyhow::Result<Option<String>> {
335 Ok(parse_name(&self.execute(&LinksOperation::GetName(id))?)?)
336 }
337
338 fn set_name(&mut self, id: u32, name: &str) -> anyhow::Result<u32> {
339 parse_link_reply(&self.execute(&LinksOperation::SetName(id, name.to_string()))?)?
340 .ok_or_else(|| anyhow::anyhow!("the set-name reply holds no link"))
341 }
342
343 fn get_by_name(&mut self, name: &str) -> anyhow::Result<Option<u32>> {
344 Ok(parse_link_reply(
345 &self.execute(&LinksOperation::GetByName(name.to_string()))?,
346 )?)
347 }
348
349 fn remove_name(&mut self, id: u32) -> anyhow::Result<()> {
350 self.execute(&LinksOperation::RemoveName(id))?;
351 Ok(())
352 }
353
354 fn save(&mut self) -> anyhow::Result<()> {
356 Ok(())
357 }
358}