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