1mod probe;
4#[cfg(test)]
5pub(crate) mod test_support;
6#[cfg(test)]
7mod tests;
8mod transport;
9
10use crate::types::{RequestId, RunId, SessionId};
11use serde::{Deserialize, Serialize};
12use std::{
13 collections::{BTreeMap, BTreeSet},
14 path::Path,
15 sync::{Arc, Mutex, OnceLock, Weak},
16 time::Duration,
17};
18use tokio::{
19 io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
20 sync::{Notify, broadcast, oneshot},
21 task::JoinSet,
22};
23use tokio_util::sync::CancellationToken;
24use transport::Endpoint;
25
26pub const RECONCILE: Duration = Duration::from_secs(5);
28const RECONNECT: Duration = Duration::from_millis(500);
30const DELIVERY_TIMEOUT: Duration = Duration::from_millis(300);
32const MAX_FRAME_BYTES: usize = 1024;
34const MAX_STATES: usize = 32;
37const MAX_CLIENTS: usize = 64;
39const MAX_BACKLOG: usize = 64;
41const MAX_DIRTY_TRANSCRIPTS: usize = 64;
43const MAX_DIRTY_RUNS: usize = 64;
45const VERSION: u32 = 2;
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub enum Change {
54 StateInvalidated,
57 RunInvalidated(RunId),
60 SessionInvalidated(SessionId),
61 DraftInvalidated(RequestId),
62 Resync,
64}
65
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub enum Changed {
70 #[default]
71 Nothing,
72 Runs(BTreeSet<RunId>),
73 Everything,
74}
75impl Changed {
76 pub fn add(&mut self, change: &Change) {
77 match change {
78 Change::StateInvalidated | Change::Resync => *self = Self::Everything,
79 Change::RunInvalidated(id) if !matches!(self, Self::Everything) => {
80 self.add_run(id.clone());
81 }
82 Change::RunInvalidated(_) => {}
83 Change::SessionInvalidated(_) | Change::DraftInvalidated(_) => {}
84 }
85 }
86 fn add_run(&mut self, id: RunId) {
87 match self {
88 Self::Nothing => *self = Self::Runs(BTreeSet::from([id])),
89 Self::Runs(ids) => {
90 ids.insert(id);
91 if ids.len() > MAX_DIRTY_RUNS {
92 *self = Self::Everything;
93 }
94 }
95 Self::Everything => {}
96 }
97 }
98 fn pop(&mut self) -> Option<Change> {
99 match self {
100 Self::Nothing => None,
101 Self::Runs(ids) => {
102 let change = ids.pop_first().map(Change::RunInvalidated);
103 if ids.is_empty() {
104 *self = Self::Nothing;
105 }
106 change
107 }
108 Self::Everything => {
109 *self = Self::Nothing;
110 Some(Change::StateInvalidated)
111 }
112 }
113 }
114 pub fn merge(&mut self, other: Self) {
116 match other {
117 Self::Nothing => {}
118 Self::Everything => *self = Self::Everything,
119 Self::Runs(ids) => {
120 for id in ids {
121 self.add_run(id);
122 }
123 }
124 }
125 }
126 pub fn or_written(&self, written: bool) -> Self {
129 match self {
130 Self::Nothing if written => Self::Everything,
131 changed => changed.clone(),
132 }
133 }
134 pub fn run(&self, id: &RunId) -> bool {
136 match self {
137 Self::Nothing => false,
138 Self::Runs(ids) => ids.contains(id),
139 Self::Everything => true,
140 }
141 }
142}
143
144enum Dirty {
147 Pending {
148 state: Changed,
149 sessions: BTreeSet<SessionId>,
150 drafts: BTreeSet<RequestId>,
151 },
152 Resync,
153}
154impl Default for Dirty {
155 fn default() -> Self {
156 Self::Pending {
157 state: Changed::Nothing,
158 sessions: BTreeSet::new(),
159 drafts: BTreeSet::new(),
160 }
161 }
162}
163impl Dirty {
164 fn add(&mut self, change: Change) {
165 let Self::Pending {
166 state,
167 sessions,
168 drafts,
169 } = self
170 else {
171 return;
172 };
173 match change {
174 Change::Resync => {
175 *self = Self::Resync;
176 return;
177 }
178 Change::StateInvalidated => *state = Changed::Everything,
179 Change::RunInvalidated(id) => state.add_run(id),
180 Change::SessionInvalidated(id) => {
181 sessions.insert(id);
182 }
183 Change::DraftInvalidated(id) => {
184 drafts.insert(id);
185 }
186 }
187 if sessions.len() + drafts.len() > MAX_DIRTY_TRANSCRIPTS {
188 *self = Self::Resync;
189 }
190 }
191 fn pop(&mut self) -> Option<Change> {
192 match self {
193 Self::Resync => {
194 *self = Self::default();
195 Some(Change::Resync)
196 }
197 Self::Pending {
198 state,
199 sessions,
200 drafts,
201 } => state
202 .pop()
203 .or_else(|| sessions.pop_first().map(Change::SessionInvalidated))
204 .or_else(|| drafts.pop_first().map(Change::DraftInvalidated)),
205 }
206 }
207 fn is_empty(&self) -> bool {
208 matches!(self, Self::Pending { state: Changed::Nothing, sessions, drafts } if sessions.is_empty() && drafts.is_empty())
209 }
210}
211struct Inbox {
212 #[cfg(test)]
213 registration: tokio::sync::watch::Sender<Option<crate::config::HubEpoch>>,
214 #[cfg(test)]
216 received: tokio::sync::watch::Sender<Option<u64>>,
217 dirty: Mutex<Dirty>,
218 wake: Notify,
219}
220impl Default for Inbox {
221 fn default() -> Self {
222 Self {
223 #[cfg(test)]
224 registration: tokio::sync::watch::channel(None).0,
225 #[cfg(test)]
226 received: tokio::sync::watch::channel(None).0,
227 dirty: Mutex::default(),
228 wake: Notify::new(),
229 }
230 }
231}
232impl Inbox {
233 fn add(&self, change: Change) {
234 self.dirty.lock().unwrap().add(change);
235 self.wake.notify_one();
236 }
237 async fn next(&self) -> Change {
238 loop {
239 let wake = self.wake.notified();
241 if let Some(change) = self.dirty.lock().unwrap().pop() {
242 return change;
243 }
244 wake.await;
245 }
246 }
247}
248
249pub fn namespace(state: &Path) -> std::io::Result<std::path::PathBuf> {
252 Endpoint::new(state).map(|endpoint| endpoint.directory().to_owned())
253}
254
255pub struct Subscription {
258 inbox: Arc<Inbox>,
259 cancel: CancellationToken,
260 task: tokio::task::JoinHandle<Result<(), String>>,
261}
262impl Subscription {
263 pub async fn new(state: &Path) -> Self {
264 let mut interval =
265 tokio::time::interval_at(tokio::time::Instant::now() + RECONCILE, RECONCILE);
266 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
267 Self::with_reconciliation(state, Reconciliation::Interval(interval)).await
268 }
269
270 async fn with_reconciliation(state: &Path, reconciliation: Reconciliation) -> Self {
271 let inbox = Arc::new(Inbox::default());
272 let cancel = CancellationToken::new();
273 let (ready, registered) = oneshot::channel();
274 let state = state.to_path_buf();
275 let task = tokio::spawn(watch(
276 state,
277 inbox.clone(),
278 cancel.clone(),
279 ready,
280 reconciliation,
281 ));
282 let subscription = Self {
284 inbox,
285 cancel,
286 task,
287 };
288 let _ = registered.await;
290 subscription
291 }
292 pub async fn close(mut self) -> Result<(), String> {
295 self.cancel.cancel();
296 crate::task::joined((&mut self.task).await).map_err(|error| error.to_string())?
297 }
298 pub async fn next_reconciled(&mut self) -> Change {
301 tokio::time::timeout(RECONCILE, self.next_state())
302 .await
303 .unwrap_or(Change::Resync)
304 }
305 pub async fn next(&mut self) -> Change {
306 self.inbox.next().await
307 }
308 pub async fn next_state(&mut self) -> Change {
311 loop {
312 let change = self.next().await;
313 if !matches!(change, Change::SessionInvalidated(_)) {
314 return change;
315 }
316 }
317 }
318}
319impl Drop for Subscription {
320 fn drop(&mut self) {
321 self.cancel.cancel();
322 }
323}
324
325#[derive(Default)]
326struct Outbox {
327 dirty: Dirty,
328 submitted: u64,
329 delivered: u64,
330}
331struct Publishing {
332 endpoint: Endpoint,
333 pending: Mutex<Outbox>,
334 wake: Notify,
335 drained: Notify,
336 #[cfg(test)]
338 delivery_error: Mutex<Option<String>>,
339}
340#[derive(Clone, Default)]
342pub(crate) struct Publisher(Option<Arc<Publishing>>);
343static PUBLISHERS: OnceLock<Mutex<BTreeMap<crate::config::EndpointId, Weak<Publishing>>>> =
344 OnceLock::new();
345impl Publisher {
346 pub(crate) fn new(state: &Path) -> Self {
347 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
348 return Self::default();
349 };
350 let Ok(endpoint) = Endpoint::new(state) else {
351 return Self::default();
352 };
353 let mut publishers = PUBLISHERS.get_or_init(Default::default).lock().unwrap();
354 publishers.retain(|_, publisher| publisher.strong_count() != 0);
355 if let Some(publisher) = publishers.get(&endpoint.identity).and_then(Weak::upgrade) {
356 return Self(Some(publisher));
357 }
358 if publishers.len() >= MAX_STATES {
359 return Self::default();
360 }
361 let publisher = Arc::new(Publishing {
362 endpoint,
363 pending: Mutex::new(Outbox::default()),
364 wake: Notify::new(),
365 drained: Notify::new(),
366 #[cfg(test)]
367 delivery_error: Mutex::default(),
368 });
369 publishers.insert(
370 publisher.endpoint.identity.clone(),
371 Arc::downgrade(&publisher),
372 );
373 runtime.spawn(publish(publisher.clone()));
374 Self(Some(publisher))
375 }
376 pub(crate) fn notify(&self, change: Change) {
377 if let Some(publisher) = &self.0 {
378 let mut pending = publisher.pending.lock().unwrap();
379 pending.dirty.add(change);
380 pending.submitted = pending.submitted.wrapping_add(1);
381 drop(pending);
382 publisher.wake.notify_one();
383 }
384 }
385}
386
387pub async fn drain() {
389 let publishers: Vec<_> = PUBLISHERS
390 .get()
391 .map(|publishers| {
392 publishers
393 .lock()
394 .unwrap()
395 .values()
396 .filter_map(Weak::upgrade)
397 .collect()
398 })
399 .unwrap_or_default();
400 let wait = async {
401 for publisher in publishers {
402 let target = publisher.pending.lock().unwrap().submitted;
403 loop {
404 let drained = publisher.drained.notified();
405 if publisher.pending.lock().unwrap().delivered >= target {
406 break;
407 }
408 drained.await;
409 }
410 }
411 };
412 let _ = tokio::time::timeout(DELIVERY_TIMEOUT, wait).await;
413}
414
415#[derive(Serialize, Deserialize)]
416enum Frame {
417 Hello {
418 version: u32,
419 identity: crate::config::EndpointId,
420 subscriber: bool,
421 },
422 Registered {
423 epoch: crate::config::HubEpoch,
424 },
425 Publish(Change),
426 Delivered,
427 Hint {
428 epoch: crate::config::HubEpoch,
429 sequence: u64,
430 change: Change,
431 },
432}
433async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Frame> {
434 let bytes = reader.read_u32().await? as usize;
435 if bytes == 0 || bytes > MAX_FRAME_BYTES {
436 return Err(std::io::ErrorKind::InvalidData.into());
437 }
438 let mut data = vec![0; bytes];
439 reader.read_exact(&mut data).await?;
440 serde_json::from_slice(&data).map_err(std::io::Error::other)
441}
442async fn write_frame<W: AsyncWrite + Unpin>(writer: &mut W, frame: &Frame) -> std::io::Result<()> {
443 let data = serde_json::to_vec(frame).map_err(std::io::Error::other)?;
444 if data.len() > MAX_FRAME_BYTES {
445 return Err(std::io::ErrorKind::InvalidData.into());
446 }
447 writer.write_u32(data.len() as u32).await?;
448 writer.write_all(&data).await?;
449 writer.flush().await
450}
451async fn connect(
452 endpoint: &Endpoint,
453 subscriber: bool,
454) -> std::io::Result<(transport::Stream, crate::config::HubEpoch)> {
455 let mut stream = endpoint.connect().await?;
456 write_frame(
457 &mut stream,
458 &Frame::Hello {
459 version: VERSION,
460 identity: endpoint.identity.clone(),
461 subscriber,
462 },
463 )
464 .await?;
465 match read_frame(&mut stream).await? {
466 Frame::Registered { epoch } if epoch.len() <= crate::types::MAX_ID_BYTES => {
467 Ok((stream, epoch))
468 }
469 _ => Err(std::io::ErrorKind::InvalidData.into()),
470 }
471}
472async fn publish(publisher: Arc<Publishing>) {
473 loop {
474 let wake = publisher.wake.notified();
475 if publisher.pending.lock().unwrap().dirty.is_empty() {
476 tokio::select! {
477 _ = wake => {},
478 _ = tokio::time::sleep(RECONNECT) => {
479 if Arc::strong_count(&publisher) == 1 {
481 break;
482 }
483 continue;
484 }
485 }
486 }
487 let (mut dirty, target) = {
488 let mut pending = publisher.pending.lock().unwrap();
489 (std::mem::take(&mut pending.dirty), pending.submitted)
490 };
491 let delivery = async {
493 let (mut stream, _) = connect(&publisher.endpoint, false).await?;
494 while let Some(change) = dirty.pop() {
495 write_frame(&mut stream, &Frame::Publish(change)).await?;
496 if !matches!(read_frame(&mut stream).await?, Frame::Delivered) {
497 return Err(std::io::ErrorKind::InvalidData.into());
498 }
499 }
500 Ok::<_, std::io::Error>(())
501 };
502 let _delivery = tokio::time::timeout(DELIVERY_TIMEOUT, delivery).await;
503 #[cfg(test)]
504 if !matches!(&_delivery, Ok(Ok(()))) {
505 *publisher.delivery_error.lock().unwrap() = Some(format!("{_delivery:?}"));
506 }
507 publisher.pending.lock().unwrap().delivered = target;
508 publisher.drained.notify_one();
509 }
510}
511
512enum Reconciliation {
513 Interval(tokio::time::Interval),
514 #[cfg(test)]
515 Controlled(tokio::sync::mpsc::UnboundedReceiver<()>),
516}
517
518impl Reconciliation {
519 async fn tick(&mut self) {
520 match self {
521 Self::Interval(interval) => {
522 interval.tick().await;
523 }
524 #[cfg(test)]
525 Self::Controlled(ticks) => {
526 if ticks.recv().await.is_none() {
527 std::future::pending::<()>().await;
528 }
529 }
530 }
531 }
532}
533
534async fn watch(
535 state: std::path::PathBuf,
536 inbox: Arc<Inbox>,
537 cancel: CancellationToken,
538 ready: oneshot::Sender<()>,
539 mut reconcile: Reconciliation,
540) -> Result<(), String> {
541 let mut ready = Some(ready);
542 let endpoint = Endpoint::new(&state).ok();
543 let mut hub = None;
544 let mut probe = probe::Probe::new(state);
545 let _ = probe.changed().await;
547 loop {
548 if cancel.is_cancelled() {
549 break;
550 }
551 if let Some(endpoint) = &endpoint {
552 if hub
553 .as_ref()
554 .is_some_and(|task: &tokio::task::JoinHandle<()>| task.is_finished())
555 {
556 hub = None;
557 }
558 if hub.is_none()
559 && let Ok(Some(owner)) = endpoint.elect()
560 && let Ok(listener) = endpoint.listen()
561 {
562 let endpoint = endpoint.clone();
563 let token = cancel.child_token();
564 hub = Some(tokio::spawn(async move {
565 let _ = serve(endpoint, listener, owner, token).await;
566 }));
567 }
568 let connection = tokio::time::timeout(DELIVERY_TIMEOUT, connect(endpoint, true));
569 tokio::select! {
570 _ = cancel.cancelled() => break,
571 result = connection => {
572 if let Ok(Ok((stream, epoch))) = result {
573 inbox.add(Change::Resync);
574 #[cfg(test)]
575 inbox.registration.send_replace(Some(epoch.clone()));
576 if let Some(ready) = ready.take() {
577 let _ = ready.send(());
578 }
579 let receive = receive(stream, epoch, inbox.clone());
580 tokio::pin!(receive);
581 loop {
582 tokio::select! {
583 _ = cancel.cancelled() => break,
584 _ = &mut receive => {
585 #[cfg(test)]
586 inbox.registration.send_replace(None);
587 inbox.add(Change::Resync);
588 break;
589 }
590 _ = reconcile.tick() => match probe.changed().await {
593 probe::Probed::Same => {}
594 probe::Probed::Written => inbox.add(Change::StateInvalidated),
595 probe::Probed::Replaced => inbox.add(Change::Resync),
596 }
597 }
598 }
599 }
600 }
601 }
602 }
603 if let Some(ready) = ready.take() {
604 inbox.add(Change::Resync);
605 let _ = ready.send(());
606 }
607 tokio::select! {
608 _ = cancel.cancelled() => break,
609 _ = reconcile.tick() => {
610 let _ = probe.changed().await;
611 inbox.add(Change::Resync);
614 },
615 _ = tokio::time::sleep(RECONNECT) => {},
616 }
617 }
618 if let Some(task) = hub {
619 let _ = crate::task::joined(task.await);
621 }
622 probe.close().await
623}
624async fn receive(
625 mut stream: transport::Stream,
626 epoch: crate::config::HubEpoch,
627 inbox: Arc<Inbox>,
628) -> std::io::Result<()> {
629 let mut previous = None;
630 loop {
631 match read_frame(&mut stream).await? {
632 Frame::Hint {
633 epoch: incoming,
634 sequence,
635 change,
636 } if incoming == epoch => {
637 if previous.is_some_and(|previous: u64| sequence != previous.wrapping_add(1)) {
638 inbox.add(Change::Resync);
639 }
640 previous = Some(sequence);
641 inbox.add(change);
642 #[cfg(test)]
643 inbox.received.send_replace(Some(sequence));
644 }
645 _ => return Err(std::io::ErrorKind::InvalidData.into()),
646 }
647 }
648}
649
650#[derive(Clone)]
651struct Hint {
652 sequence: u64,
653 change: Change,
654}
655async fn serve(
656 endpoint: Endpoint,
657 mut listener: transport::Listener,
658 _owner: std::fs::File,
659 cancel: CancellationToken,
660) -> std::io::Result<()> {
661 let epoch: crate::config::HubEpoch = crate::agent::uuid()
662 .map_err(std::io::Error::other)?
663 .parse()
664 .expect("UUID hub epoch");
665 let (sender, _) = broadcast::channel(MAX_BACKLOG);
666 let sequence = Arc::new(Mutex::new(0_u64));
667 let mut clients = JoinSet::new();
668 loop {
669 tokio::select! {
670 _ = cancel.cancelled() => break,
671 Some(result) = clients.join_next(), if !clients.is_empty() => {
672 let _ = crate::task::joined(result);
673 },
674 result = listener.accept(), if clients.len() < MAX_CLIENTS => {
675 let stream = result?;
676 let (identity, epoch, sender, sequence) = (
677 endpoint.identity.clone(),
678 epoch.clone(),
679 sender.clone(),
680 sequence.clone(),
681 );
682 clients.spawn(async move {
683 let _ = client(stream, identity, epoch, sender, sequence).await;
684 });
685 }
686 }
687 }
688 clients.abort_all();
689 while let Some(result) = clients.join_next().await {
690 let _ = crate::task::joined(result);
691 }
692 Ok(())
693}
694async fn client(
695 mut stream: transport::Stream,
696 identity: crate::config::EndpointId,
697 epoch: crate::config::HubEpoch,
698 sender: broadcast::Sender<Hint>,
699 sequence: Arc<Mutex<u64>>,
700) -> std::io::Result<()> {
701 transport::validate_peer(&stream)?;
704 let hello = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
705 let Frame::Hello {
706 version: VERSION,
707 identity: incoming,
708 subscriber,
709 } = hello
710 else {
711 return Err(std::io::ErrorKind::InvalidData.into());
712 };
713 if incoming != identity {
714 return Err(std::io::ErrorKind::PermissionDenied.into());
715 }
716 let mut receiver = sender.subscribe();
718 tokio::time::timeout(
719 DELIVERY_TIMEOUT,
720 write_frame(
721 &mut stream,
722 &Frame::Registered {
723 epoch: epoch.clone(),
724 },
725 ),
726 )
727 .await??;
728 if subscriber {
729 let (mut reader, mut writer) = tokio::io::split(stream);
730 let outgoing = async {
731 loop {
732 let hint = match receiver.recv().await {
733 Ok(hint) => hint,
734 Err(broadcast::error::RecvError::Lagged(_)) => Hint {
735 sequence: *sequence.lock().unwrap(),
736 change: Change::Resync,
737 },
738 Err(_) => return Ok::<_, std::io::Error>(()),
739 };
740 tokio::time::timeout(
742 DELIVERY_TIMEOUT,
743 write_frame(
744 &mut writer,
745 &Frame::Hint {
746 epoch: epoch.clone(),
747 sequence: hint.sequence,
748 change: hint.change,
749 },
750 ),
751 )
752 .await??;
753 }
754 };
755 tokio::select! { result = outgoing => result, _ = reader.read_u8() => Ok(()) }
756 } else {
757 loop {
758 let frame = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
759 let Frame::Publish(change) = frame else {
760 return Err(std::io::ErrorKind::InvalidData.into());
761 };
762 {
763 let mut sequence = sequence.lock().unwrap();
765 *sequence = sequence.wrapping_add(1);
766 let _ = sender.send(Hint {
767 sequence: *sequence,
768 change,
769 });
770 }
771 tokio::time::timeout(
772 DELIVERY_TIMEOUT,
773 write_frame(&mut stream, &Frame::Delivered),
774 )
775 .await??;
776 }
777 }
778}