1use crate::selection::filter::Filterable;
2use ankurah_proto::{self as proto, Attested, CollectionId, EntityState};
3use anyhow::anyhow;
4
5use rand::prelude::*;
6use std::{
7 fmt,
8 hash::Hash,
9 ops::Deref,
10 sync::{Arc, Weak},
11};
12use tokio::sync::oneshot;
13
14use crate::{
15 action_error, action_info,
16 changes::EntityChange,
17 collectionset::CollectionSet,
18 connector::{PeerSender, SendError},
19 context::Context,
20 entity::{Entity, WeakEntitySet},
21 error::{MutationError, RequestError, RetrievalError},
22 notice_info,
23 peer_subscription::{SubscriptionHandler, SubscriptionRelay},
24 policy::{AccessDenied, PolicyAgent},
25 reactor::{AbstractEntity, Reactor},
26 retrieval::LocalRetriever,
27 storage::StorageEngine,
28 system::SystemManager,
29 util::{safemap::SafeMap, safeset::SafeSet, Iterable},
30};
31use itertools::Itertools;
32#[cfg(feature = "instrument")]
33use tracing::instrument;
34
35use tracing::{debug, error, warn};
36
37pub struct PeerState {
38 sender: Box<dyn PeerSender>,
39 _durable: bool,
40 subscription_handler: SubscriptionHandler,
41 pending_requests: SafeMap<proto::RequestId, oneshot::Sender<Result<proto::NodeResponseBody, RequestError>>>,
42 pending_updates: SafeMap<proto::UpdateId, oneshot::Sender<Result<proto::NodeResponseBody, RequestError>>>,
43}
44
45impl PeerState {
46 pub fn send_message(&self, message: proto::NodeMessage) -> Result<(), SendError> { self.sender.send_message(message) }
47}
48
49pub struct MatchArgs {
50 pub selection: ankql::ast::Selection,
51 pub cached: bool,
52}
53
54impl TryInto<MatchArgs> for &str {
55 type Error = ankql::error::ParseError;
56 fn try_into(self) -> Result<MatchArgs, Self::Error> { Ok(MatchArgs { selection: ankql::parser::parse_selection(self)?, cached: true }) }
57}
58impl TryInto<MatchArgs> for String {
59 type Error = ankql::error::ParseError;
60 fn try_into(self) -> Result<MatchArgs, Self::Error> {
61 Ok(MatchArgs { selection: ankql::parser::parse_selection(&self)?, cached: true })
62 }
63}
64
65impl From<ankql::ast::Predicate> for MatchArgs {
66 fn from(val: ankql::ast::Predicate) -> Self {
67 MatchArgs { selection: ankql::ast::Selection { predicate: val, order_by: None, limit: None }, cached: true }
68 }
69}
70
71impl From<ankql::ast::Selection> for MatchArgs {
72 fn from(val: ankql::ast::Selection) -> Self { MatchArgs { selection: val, cached: true } }
73}
74
75impl From<ankql::error::ParseError> for RetrievalError {
76 fn from(e: ankql::error::ParseError) -> Self { RetrievalError::ParseError(e) }
77}
78
79pub fn nocache<T: TryInto<ankql::ast::Selection, Error = ankql::error::ParseError>>(s: T) -> Result<MatchArgs, ankql::error::ParseError> {
80 MatchArgs::nocache(s)
81}
82impl MatchArgs {
83 pub fn nocache<T>(s: T) -> Result<Self, ankql::error::ParseError>
84 where T: TryInto<ankql::ast::Selection, Error = ankql::error::ParseError> {
85 Ok(Self { selection: s.try_into()?, cached: false })
86 }
87}
88
89pub struct Node<SE, PA>(pub(crate) Arc<NodeInner<SE, PA>>)
92where PA: PolicyAgent;
93impl<SE, PA> Clone for Node<SE, PA>
94where PA: PolicyAgent
95{
96 fn clone(&self) -> Self { Self(self.0.clone()) }
97}
98
99pub struct WeakNode<SE, PA>(Weak<NodeInner<SE, PA>>)
100where PA: PolicyAgent;
101impl<SE, PA> Clone for WeakNode<SE, PA>
102where PA: PolicyAgent
103{
104 fn clone(&self) -> Self { Self(self.0.clone()) }
105}
106
107impl<SE, PA> WeakNode<SE, PA>
108where PA: PolicyAgent
109{
110 pub fn upgrade(&self) -> Option<Node<SE, PA>> { self.0.upgrade().map(Node) }
111}
112
113impl<SE, PA> Deref for Node<SE, PA>
114where PA: PolicyAgent
115{
116 type Target = Arc<NodeInner<SE, PA>>;
117 fn deref(&self) -> &Self::Target { &self.0 }
118}
119
120pub trait ContextData: Send + Sync + Clone + Hash + Eq + 'static {}
123
124pub struct NodeInner<SE, PA>
125where PA: PolicyAgent
126{
127 pub id: proto::EntityId,
128 pub durable: bool,
129 pub collections: CollectionSet<SE>,
130
131 pub(crate) entities: WeakEntitySet,
132 peer_connections: SafeMap<proto::EntityId, Arc<PeerState>>,
133 durable_peers: SafeSet<proto::EntityId>,
134
135 pub(crate) predicate_context: SafeMap<proto::QueryId, PA::ContextData>,
136
137 pub(crate) reactor: Reactor,
139 pub(crate) policy_agent: PA,
140 pub system: SystemManager<SE, PA>,
141
142 pub(crate) subscription_relay: Option<SubscriptionRelay<PA::ContextData, crate::livequery::WeakEntityLiveQuery>>,
143
144 pub(crate) type_resolver: crate::TypeResolver,
146}
147
148impl<SE, PA> Node<SE, PA>
149where
150 SE: StorageEngine + Send + Sync + 'static,
151 PA: PolicyAgent + Send + Sync + 'static,
152{
153 pub fn new(engine: Arc<SE>, policy_agent: PA) -> Self {
154 let collections = CollectionSet::new(engine.clone());
155 let entityset: WeakEntitySet = Default::default();
156 let id = proto::EntityId::new();
157 let reactor = Reactor::new();
158 notice_info!("Node {id:#} created as ephemeral");
159
160 let system_manager = SystemManager::new(collections.clone(), entityset.clone(), reactor.clone(), false);
161
162 let subscription_relay = Some(SubscriptionRelay::new());
164
165 let node = Node(Arc::new(NodeInner {
166 id,
167 collections,
168 entities: entityset,
169 peer_connections: SafeMap::new(),
170 durable_peers: SafeSet::new(),
171 reactor,
172 durable: false,
173 policy_agent,
174 system: system_manager,
175 predicate_context: SafeMap::new(),
176 subscription_relay,
177 type_resolver: crate::TypeResolver::new(),
178 }));
179
180 if let Some(ref relay) = node.subscription_relay {
182 let weak_node = node.weak();
183 if relay.set_node(Arc::new(weak_node)).is_err() {
184 warn!("Failed to set message sender for subscription relay");
185 }
186 }
187
188 node
189 }
190 pub fn new_durable(engine: Arc<SE>, policy_agent: PA) -> Self {
191 let collections = CollectionSet::new(engine);
192 let entityset: WeakEntitySet = Default::default();
193 let id = proto::EntityId::new();
194 let reactor = Reactor::new();
195 notice_info!("Node {id:#} created as durable");
196
197 let system_manager = SystemManager::new(collections.clone(), entityset.clone(), reactor.clone(), true);
198
199 Node(Arc::new(NodeInner {
200 id,
201 collections,
202 entities: entityset,
203 peer_connections: SafeMap::new(),
204 durable_peers: SafeSet::new(),
205 reactor,
206 durable: true,
207 policy_agent,
208 system: system_manager,
209 predicate_context: SafeMap::new(),
210 subscription_relay: None,
211 type_resolver: crate::TypeResolver::new(),
212 }))
213 }
214 pub fn weak(&self) -> WeakNode<SE, PA> { WeakNode(Arc::downgrade(&self.0)) }
215
216 #[cfg_attr(feature = "instrument", instrument(level = "debug", skip_all, fields(node_id = %presence.node_id.to_base64_short(), durable = %presence.durable)))]
217 pub fn register_peer(&self, presence: proto::Presence, sender: Box<dyn PeerSender>) {
218 action_info!(self, "register_peer", "{}", &presence);
219
220 let subscription_handler = SubscriptionHandler::new(presence.node_id, self);
221 self.peer_connections.insert(
222 presence.node_id,
223 Arc::new(PeerState {
224 sender,
225 _durable: presence.durable,
226 subscription_handler,
227 pending_requests: SafeMap::new(),
228 pending_updates: SafeMap::new(),
229 }),
230 );
231 if presence.durable {
232 self.durable_peers.insert(presence.node_id);
233
234 if let Some(ref relay) = self.subscription_relay {
236 relay.notify_peer_connected(presence.node_id);
237 }
238
239 if !self.durable {
240 if let Some(system_root) = presence.system_root {
241 action_info!(self, "received system root", "{}", &system_root.payload);
242 let me = self.clone();
243 crate::task::spawn(async move {
244 if let Err(e) = me.system.join_system(system_root).await {
245 action_error!(me, "failed to join system", "{}", &e);
246 } else {
247 action_info!(me, "successfully joined system");
248 }
249 });
250 } else {
251 error!("Node({}) durable peer {} has no system root", self.id, presence.node_id);
252 }
253 }
254 }
255 }
257 #[cfg_attr(feature = "instrument", instrument(level = "debug", skip_all, fields(node_id = %node_id.to_base64_short())))]
258 pub fn deregister_peer(&self, node_id: proto::EntityId) {
259 notice_info!("Node({:#}) deregister_peer {:#}", self.id, node_id);
260
261 self.durable_peers.remove(&node_id);
262 if let Some(peer_state) = self.peer_connections.remove(&node_id) {
264 action_info!(self, "unsubscribing", "subscription {} for peer {}", peer_state.subscription_handler.subscription_id(), node_id);
265 }
267
268 if let Some(ref relay) = self.subscription_relay {
270 relay.notify_peer_disconnected(node_id);
271 }
272 }
273 #[cfg_attr(feature = "instrument", instrument(skip_all, fields(node_id = %node_id, request_body = %request_body)))]
274 pub async fn request<'a, C>(
275 &self,
276 node_id: proto::EntityId,
277 cdata: &C,
278 request_body: proto::NodeRequestBody,
279 ) -> Result<proto::NodeResponseBody, RequestError>
280 where
281 C: Iterable<PA::ContextData>,
282 {
283 let (response_tx, response_rx) = oneshot::channel::<Result<proto::NodeResponseBody, RequestError>>();
284 let request_id = proto::RequestId::new();
285
286 let request = proto::NodeRequest { id: request_id.clone(), to: node_id, from: self.id, body: request_body };
287 let auth = self.policy_agent.sign_request(self, cdata, &request)?;
288
289 let connection = self.peer_connections.get(&node_id).ok_or(RequestError::PeerNotConnected)?;
291
292 connection.pending_requests.insert(request_id, response_tx);
293 connection.send_message(proto::NodeMessage::Request { auth, request })?;
294
295 response_rx.await.map_err(|_| RequestError::InternalChannelClosed)?
297 }
298
299 pub fn send_update(&self, node_id: proto::EntityId, notification: proto::NodeUpdateBody) {
301 debug!("{self}.send_update({node_id:#}, {notification})");
303 let (response_tx, _response_rx) = oneshot::channel::<Result<proto::NodeResponseBody, RequestError>>();
304 let id = proto::UpdateId::new();
305
306 let Some(connection) = self.peer_connections.get(&node_id) else {
308 warn!("Failed to send update to peer {}: {}", node_id, RequestError::PeerNotConnected);
309 return;
310 };
311
312 connection.pending_updates.insert(id.clone(), response_tx);
314
315 let notification = proto::NodeMessage::Update(proto::NodeUpdate { id, from: self.id, to: node_id, body: notification });
316
317 match connection.send_message(notification) {
318 Ok(_) => {}
319 Err(e) => {
320 warn!("Failed to send update to peer {}: {}", node_id, e);
321 }
322 };
323
324 }
326
327 #[cfg_attr(feature = "instrument", instrument(level = "debug", skip_all, fields(message = %message)))]
331 pub async fn handle_message(&self, message: proto::NodeMessage) -> anyhow::Result<()> {
332 match message {
333 proto::NodeMessage::Update(update) => {
334 debug!("Node({}) received update {}", self.id, update);
335
336 if let Some(sender) = { self.peer_connections.get(&update.from).map(|c| c.sender.cloned()) } {
337 let _from = update.from;
338 let _id = update.id.clone();
339 if update.to != self.id {
340 warn!("{} received message from {} but is not the intended recipient", self.id, update.from);
341 return Ok(());
342 }
343
344 let id = update.id.clone();
346 let to = update.from;
347 let from = self.id;
348
349 let body = match self.handle_update(update).await {
351 Ok(_) => proto::NodeUpdateAckBody::Success,
352 Err(e) => proto::NodeUpdateAckBody::Error(e.to_string()),
353 };
354
355 sender.send_message(proto::NodeMessage::UpdateAck(proto::NodeUpdateAck { id, from, to, body }))?;
356 }
357 }
358 proto::NodeMessage::UpdateAck(ack) => {
359 debug!("Node({}) received ack notification {} {}", self.id, ack.id, ack.body);
360 }
365 proto::NodeMessage::Request { auth, request } => {
366 debug!("Node({}) received request {}", self.id, request);
367 let cdata = self.policy_agent.check_request(self, &auth, &request).await?;
373
374 if let Some(sender) = { self.peer_connections.get(&request.from).map(|c| c.sender.cloned()) } {
376 let from = request.from;
377 let request_id = request.id.clone();
378 if request.to != self.id {
379 warn!("{} received message from {} but is not the intended recipient", self.id, request.from);
380 return Ok(());
381 }
382
383 let body = match self.handle_request(&cdata, request).await {
384 Ok(result) => result,
385 Err(e) => proto::NodeResponseBody::Error(e.to_string()),
386 };
387 let _result = sender.send_message(proto::NodeMessage::Response(proto::NodeResponse {
388 request_id,
389 from: self.id,
390 to: from,
391 body,
392 }));
393 }
394 }
395 proto::NodeMessage::Response(response) => {
396 debug!("Node {} received response {}", self.id, response);
397 let connection = self.peer_connections.get(&response.from).ok_or(RequestError::PeerNotConnected)?;
398 if let Some(tx) = connection.pending_requests.remove(&response.request_id) {
399 tx.send(Ok(response.body)).map_err(|e| anyhow!("Failed to send response: {:?}", e))?;
400 }
401 }
402 proto::NodeMessage::UnsubscribeQuery { from, query_id } => {
403 if let Some(peer_state) = self.peer_connections.get(&from) {
405 peer_state.subscription_handler.remove_predicate(query_id)?;
406 }
407 }
408 }
409 Ok(())
410 }
411
412 #[cfg_attr(feature = "instrument", instrument(level = "debug", skip_all, fields(request = %request)))]
413 async fn handle_request<C>(&self, cdata: &C, request: proto::NodeRequest) -> anyhow::Result<proto::NodeResponseBody>
414 where C: Iterable<PA::ContextData> {
415 match request.body {
416 proto::NodeRequestBody::CommitTransaction { id, events } => {
417 let cdata = cdata.iterable().exactly_one().map_err(|_| anyhow!("Only one cdata is permitted for CommitTransaction"))?;
421 match self.commit_remote_transaction(cdata, id.clone(), events).await {
422 Ok(_) => Ok(proto::NodeResponseBody::CommitComplete { id }),
423 Err(e) => Ok(proto::NodeResponseBody::Error(e.to_string())),
424 }
425 }
426 proto::NodeRequestBody::Fetch { collection, mut selection, known_matches } => {
427 self.policy_agent.can_access_collection(cdata, &collection)?;
428 let storage_collection = self.collections.get(&collection).await?;
429 selection.predicate = self.policy_agent.filter_predicate(cdata, &collection, selection.predicate)?;
430
431 let expanded_states = crate::util::expand_states::expand_states(
433 storage_collection.fetch_states(&selection).await?,
434 known_matches.iter().map(|k| k.entity_id).collect::<Vec<_>>(),
435 &storage_collection,
436 )
437 .await?;
438
439 let known_map: std::collections::HashMap<_, _> = known_matches.into_iter().map(|k| (k.entity_id, k.head)).collect();
440
441 let mut deltas = Vec::new();
442 for state in expanded_states {
443 if self.policy_agent.check_read(cdata, &state.payload.entity_id, &collection, &state.payload.state).is_err() {
444 continue;
445 }
446
447 if let Some(delta) = self.generate_entity_delta(&known_map, state, &storage_collection).await? {
450 deltas.push(delta);
451 }
452 }
453 Ok(proto::NodeResponseBody::Fetch(deltas))
454 }
455 proto::NodeRequestBody::Get { collection, ids } => {
456 self.policy_agent.can_access_collection(cdata, &collection)?;
457 let storage_collection = self.collections.get(&collection).await?;
458
459 let mut states = Vec::new();
461 for state in storage_collection.get_states(ids).await? {
462 match self.policy_agent.check_read(cdata, &state.payload.entity_id, &collection, &state.payload.state) {
463 Ok(_) => states.push(state),
464 Err(AccessDenied::ByPolicy(_)) => {}
465 Err(e) => return Err(anyhow!("Error from peer get: {}", e)),
467 }
468 }
469
470 Ok(proto::NodeResponseBody::Get(states))
471 }
472 proto::NodeRequestBody::GetEvents { collection, event_ids } => {
473 self.policy_agent.can_access_collection(cdata, &collection)?;
474 let storage_collection = self.collections.get(&collection).await?;
475
476 let mut events = Vec::new();
478 for event in storage_collection.get_events(event_ids).await? {
479 match self.policy_agent.check_read_event(cdata, &event) {
480 Ok(_) => events.push(event),
481 Err(AccessDenied::ByPolicy(_)) => {}
482 Err(e) => return Err(anyhow!("Error from peer subscription: {}", e)),
484 }
485 }
486
487 Ok(proto::NodeResponseBody::GetEvents(events))
488 }
489 proto::NodeRequestBody::SubscribeQuery { query_id, collection, selection, version, known_matches } => {
490 let peer_state = self.peer_connections.get(&request.from).ok_or_else(|| anyhow!("Peer {} not connected", request.from))?;
491 use itertools::Itertools;
493 let cdata = cdata.iterable().exactly_one().map_err(|_| anyhow!("Only one cdata is permitted for SubscribePredicate"))?;
494 peer_state.subscription_handler.subscribe_query(self, query_id, collection, selection, cdata, version, known_matches).await
495 }
496 }
497 }
498
499 async fn handle_update(&self, notification: proto::NodeUpdate) -> anyhow::Result<()> {
500 let Some(_connection) = self.peer_connections.get(¬ification.from) else {
501 return Err(anyhow!("Rejected notification from unknown node {}", notification.from));
502 };
503
504 match notification.body {
505 proto::NodeUpdateBody::SubscriptionUpdate { items } => {
506 tracing::debug!("Node({}) received subscription update from peer {}", self.id, notification.from);
507 crate::node_applier::NodeApplier::apply_updates(self, ¬ification.from, items).await?;
508 Ok(())
509 }
510 }
511 }
512
513 pub(crate) async fn relay_to_required_peers(
514 &self,
515 cdata: &PA::ContextData,
516 id: proto::TransactionId,
517 events: &[Attested<proto::Event>],
518 ) -> Result<(), MutationError> {
519 for peer_id in self.get_durable_peers() {
522 match self.request(peer_id, cdata, proto::NodeRequestBody::CommitTransaction { id: id.clone(), events: events.to_vec() }).await
523 {
524 Ok(proto::NodeResponseBody::CommitComplete { .. }) => (),
525 Ok(proto::NodeResponseBody::Error(e)) => {
526 return Err(MutationError::General(Box::new(std::io::Error::other(format!("Peer {} rejected: {}", peer_id, e)))));
527 }
528 _ => {
529 return Err(MutationError::General(Box::new(std::io::Error::other(format!(
530 "Peer {} returned unexpected response",
531 peer_id
532 )))));
533 }
534 }
535 }
536 Ok(())
537 }
538
539 pub async fn commit_remote_transaction(
541 &self,
542 cdata: &PA::ContextData,
543 id: proto::TransactionId,
544 mut events: Vec<Attested<proto::Event>>,
545 ) -> Result<(), MutationError> {
546 debug!("{self} commiting transaction {id} with {} events", events.len());
547 let mut changes = Vec::new();
548
549 for event in events.iter_mut() {
550 let collection = self.collections.get(&event.payload.collection).await?;
551
552 let retriever = LocalRetriever::new(collection.clone());
554 let entity = self.entities.get_retrieve_or_create(&retriever, &event.payload.collection, &event.payload.entity_id).await?;
555
556 let (entity_before, entity_after, already_applied) = if event.payload.is_entity_create() && entity.head().is_empty() {
558 entity.apply_event(&retriever, &event.payload).await?;
560 (entity.clone(), entity.clone(), true)
561 } else {
562 use std::sync::atomic::AtomicBool;
564 let trx_alive = Arc::new(AtomicBool::new(true));
565 let forked = entity.snapshot(trx_alive);
566 forked.apply_event(&retriever, &event.payload).await?;
567 (entity.clone(), forked, false)
568 };
569
570 if let Some(attestation) = self.policy_agent.check_event(self, cdata, &entity_before, &entity_after, &event.payload)? {
572 event.attestations.push(attestation);
573 }
574
575 let applied = if already_applied { true } else { entity.apply_event(&retriever, &event.payload).await? };
577
578 if applied {
579 let state = entity.to_state()?;
580 let entity_state = EntityState { entity_id: entity.id(), collection: entity.collection().clone(), state };
581 let attestation = self.policy_agent.attest_state(self, &entity_state);
582 let attested = Attested::opt(entity_state, attestation);
583 collection.add_event(event).await?;
584 collection.set_state(attested).await?;
585 changes.push(EntityChange::new(entity.clone(), vec![event.clone()])?);
586 }
587 }
588
589 self.reactor.notify_change(changes).await;
590
591 Ok(())
592 }
593
594 pub(crate) async fn generate_entity_delta(
597 &self,
598 known_map: &std::collections::HashMap<proto::EntityId, proto::Clock>,
599 entity_state: proto::Attested<proto::EntityState>,
600 storage_collection: &crate::storage::StorageCollectionWrapper,
601 ) -> anyhow::Result<Option<proto::EntityDelta>>
602 where
603 SE: StorageEngine + Send + Sync + 'static,
604 PA: PolicyAgent + Send + Sync + 'static,
605 {
606 let proto::Attested { payload: proto::EntityState { entity_id, collection, state }, attestations } = entity_state;
608 let current_head = &state.head;
609
610 if let Some(known_head) = known_map.get(&entity_id) {
612 if known_head == current_head {
614 return Ok(None);
615 }
616
617 match self.collect_event_bridge(storage_collection, known_head, current_head).await {
619 Ok(attested_events) if !attested_events.is_empty() => {
620 let event_fragments: Vec<proto::EventFragment> = attested_events.into_iter().map(|e| e.into()).collect();
622
623 return Ok(Some(proto::EntityDelta {
624 entity_id,
625 collection,
626 content: proto::DeltaContent::EventBridge { events: event_fragments },
627 }));
628 }
629 _ => {
630 }
632 }
633 }
634
635 let state_fragment = proto::StateFragment { state, attestations };
637 Ok(Some(proto::EntityDelta { entity_id, collection, content: proto::DeltaContent::StateSnapshot { state: state_fragment } }))
638 }
639
640 pub(crate) async fn collect_event_bridge(
642 &self,
643 storage_collection: &crate::storage::StorageCollectionWrapper,
644 known_head: &proto::Clock,
645 current_head: &proto::Clock,
646 ) -> anyhow::Result<Vec<proto::Attested<proto::Event>>>
647 where
648 SE: StorageEngine + Send + Sync + 'static,
649 PA: PolicyAgent + Send + Sync + 'static,
650 {
651 use crate::lineage::{EventAccumulator, Ordering};
652 use crate::retrieval::LocalRetriever;
653
654 let retriever = LocalRetriever::new(storage_collection.clone());
655 let accumulator = EventAccumulator::new(None); let mut comparison = crate::lineage::Comparison::new_with_accumulator(
657 &retriever,
658 current_head,
659 known_head,
660 100000, Some(accumulator),
662 );
663
664 loop {
666 match comparison.step().await? {
667 Some(Ordering::Descends) => {
668 break;
670 }
671 Some(Ordering::Equal) => {
672 break;
674 }
675 Some(_) => {
676 return Ok(vec![]);
678 }
679 None => {
680 }
682 }
683 }
684
685 Ok(comparison.take_accumulated_events().unwrap_or_default())
687 }
688
689 pub fn next_entity_id(&self) -> proto::EntityId { proto::EntityId::new() }
690
691 pub fn context(&self, data: PA::ContextData) -> Result<Context, anyhow::Error> {
692 if !self.system.is_system_ready() {
693 return Err(anyhow!("System is not ready"));
694 }
695 Ok(Context::new(Node::clone(self), data))
696 }
697
698 pub async fn context_async(&self, data: PA::ContextData) -> Context {
699 self.system.wait_system_ready().await;
700 Context::new(Node::clone(self), data)
701 }
702
703 pub(crate) async fn get_from_peer(
704 &self,
705 collection_id: &CollectionId,
706 ids: Vec<proto::EntityId>,
707 cdata: &PA::ContextData,
708 ) -> Result<(), RetrievalError> {
709 let peer_id = self.get_durable_peer_random().ok_or(RetrievalError::NoDurablePeers)?;
710
711 match self
712 .request(peer_id, cdata, proto::NodeRequestBody::Get { collection: collection_id.clone(), ids })
713 .await
714 .map_err(|e| RetrievalError::Other(format!("{:?}", e)))?
715 {
716 proto::NodeResponseBody::Get(states) => {
717 let collection = self.collections.get(collection_id).await?;
718
719 for state in states {
722 self.policy_agent.validate_received_state(self, &peer_id, &state)?;
723 collection.set_state(state).await.map_err(|e| RetrievalError::Other(format!("{:?}", e)))?;
724 }
725 Ok(())
726 }
727 proto::NodeResponseBody::Error(e) => {
728 debug!("Error from peer fetch: {}", e);
729 Err(RetrievalError::Other(format!("{:?}", e)))
730 }
731 _ => {
732 debug!("Unexpected response type from peer get");
733 Err(RetrievalError::Other("Unexpected response type".to_string()))
734 }
735 }
736 }
737
738 pub fn get_durable_peer_random(&self) -> Option<proto::EntityId> {
740 let mut rng = rand::thread_rng();
741 let peers: Vec<_> = self.durable_peers.to_vec();
743 peers.choose(&mut rng).copied()
744 }
745
746 pub fn get_durable_peers(&self) -> Vec<proto::EntityId> { self.durable_peers.to_vec() }
748}
749
750impl<SE, PA> NodeInner<SE, PA>
751where
752 SE: StorageEngine + Send + Sync + 'static,
753 PA: PolicyAgent + Send + Sync + 'static,
754{
755 pub async fn request_remote_unsubscribe(&self, query_id: proto::QueryId, peers: Vec<proto::EntityId>) -> anyhow::Result<()> {
756 for (peer_id, item) in self.peer_connections.get_list(peers) {
757 if let Some(connection) = item {
758 connection.send_message(proto::NodeMessage::UnsubscribeQuery { from: peer_id, query_id })?;
759 } else {
760 warn!("Peer {} not connected", peer_id);
761 }
762 }
763
764 Ok(())
765 }
766}
767
768impl<SE, PA> Drop for NodeInner<SE, PA>
769where PA: PolicyAgent
770{
771 fn drop(&mut self) {
772 notice_info!("Node({}) dropped", self.id);
773 }
774}
775
776impl<SE, PA> Node<SE, PA>
777where
778 SE: StorageEngine + Send + Sync + 'static,
779 PA: PolicyAgent + Send + Sync + 'static,
780{
781 pub(crate) fn subscribe_remote_query(
782 &self,
783 query_id: proto::QueryId,
784 collection_id: CollectionId,
785 selection: ankql::ast::Selection,
786 cdata: PA::ContextData,
787 version: u32,
788 livequery: crate::livequery::WeakEntityLiveQuery,
789 ) {
790 if let Some(ref relay) = self.subscription_relay {
791 let selection = self.type_resolver.resolve_selection_types(selection);
793 self.predicate_context.insert(query_id, cdata.clone());
794 relay.subscribe_query(query_id, collection_id, selection, cdata, version, livequery);
795 }
796 }
797
798 pub async fn fetch_entities_from_local(
799 &self,
800 collection_id: &CollectionId,
801 selection: &ankql::ast::Selection,
802 ) -> Result<Vec<Entity>, RetrievalError> {
803 let storage_collection = self.collections.get(collection_id).await?;
804 let initial_states = storage_collection.fetch_states(selection).await?;
805 let retriever = crate::retrieval::LocalRetriever::new(storage_collection);
806 let mut entities = Vec::with_capacity(initial_states.len());
807 for state in initial_states {
808 let (_, entity) =
809 self.entities.with_state(&retriever, state.payload.entity_id, collection_id.clone(), state.payload.state).await?;
810 entities.push(entity);
811 }
812 Ok(entities)
813 }
814}
815#[async_trait::async_trait]
816pub trait TNodeErased<E: AbstractEntity + Filterable + Send + 'static = Entity>: Send + Sync + 'static {
817 fn unsubscribe_remote_predicate(&self, query_id: proto::QueryId);
818 fn update_remote_query(&self, query_id: proto::QueryId, selection: ankql::ast::Selection, version: u32) -> Result<(), anyhow::Error>;
819 async fn fetch_entities_from_local(
820 &self,
821 collection_id: &CollectionId,
822 selection: &ankql::ast::Selection,
823 ) -> Result<Vec<E>, RetrievalError>;
824 fn reactor(&self) -> &Reactor<E>;
825 fn has_subscription_relay(&self) -> bool;
826}
827
828#[async_trait::async_trait]
829impl<SE, PA> TNodeErased<Entity> for Node<SE, PA>
830where
831 SE: StorageEngine + Send + Sync + 'static,
832 PA: PolicyAgent + Send + Sync + 'static,
833{
834 fn unsubscribe_remote_predicate(&self, query_id: proto::QueryId) {
835 self.predicate_context.remove(&query_id);
837
838 if let Some(ref relay) = self.subscription_relay {
840 relay.unsubscribe_predicate(query_id);
841 }
842 }
843
844 fn update_remote_query(&self, query_id: proto::QueryId, selection: ankql::ast::Selection, version: u32) -> Result<(), anyhow::Error> {
845 if let Some(ref relay) = self.subscription_relay {
846 let selection = self.type_resolver.resolve_selection_types(selection);
848 relay.update_query(query_id, selection, version)?;
849 }
850 Ok(())
851 }
852
853 async fn fetch_entities_from_local(
854 &self,
855 collection_id: &CollectionId,
856 selection: &ankql::ast::Selection,
857 ) -> Result<Vec<Entity>, RetrievalError> {
858 Node::fetch_entities_from_local(self, collection_id, selection).await
859 }
860
861 fn reactor(&self) -> &Reactor<Entity> { &self.0.reactor }
862
863 fn has_subscription_relay(&self) -> bool { self.subscription_relay.is_some() }
864}
865
866impl<SE, PA> fmt::Display for Node<SE, PA>
867where PA: PolicyAgent
868{
869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870 write!(f, "\x1b[1;34mnode\x1b[2m[\x1b[1;34m{}\x1b[2m]\x1b[0m", self.id.to_base64_short())
872 }
873}