ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! The poll intake: a node's own clock, one per declared upstream, and the entry a tick invokes.
//!
//! The third listen mode. [`Channel`](super::Listen::Channel) and [`Changes`](super::Listen::Changes)
//! are both PASSIVE — something upstream produces and the node is fed — and a maintenance node is
//! neither: a reaper, a compactor and a stuck-watermark healer all ACT on a schedule, over stores
//! nobody is writing to at that moment. This is what makes them ordinary declared nodes rather than
//! a side channel beside the graph.
//!
//! # The schedule is PER ENTRY, and the entry is the node's own word
//!
//! `poll(orphans, every = "10m", light, async(inline))` beside `subscribe(…)`, one entry per
//! clock, so one node reaps one store fast and compacts another on the hour. [`Schedule`] is that
//! list at run time, in declaration order, and a [`PollUpstream`] is a position in it — the identity
//! a tick carries, which the emitted `<Node>Due` maps back to the entry that authored it.
//!
//! # TWO cadences, ONE next-due core
//!
//! An entry recurs on an INTERVAL (`every = "…"`) or on a CALENDAR (`cron = "…"`), and
//! [`Recurrence`] is the pair. Every clock in this crate — the thread engine's arithmetic, the
//! sweeper's wheel, the runtime's After timers — asks the same question of it and none of them
//! knows which arm answered: [`Recurrence::until_next`] is *how long from now*, and that is the
//! whole of what a clock needs. The calendar arm lives behind [`calendar`], the swappable seam the
//! cron ruling asked for.
//!
//! # The two engines, again
//!
//! The sweep's own asymmetry, applied to a clock that now has several hands. A resident THREAD
//! self-times, so its ticks are arithmetic: [`Clock`] holds the next-due instant per upstream and the
//! loop parks until the nearest one. An async task is RUNG, so its ticks are messages: one
//! [`Ticker`] per upstream puts a [`Ticked`] carrying that upstream's identity on the same inbox, and one
//! clock built from [`Cadence`]s serves every one of them — the app's own runtime through
//! [`AfterClock`](super::AfterClock) where a deployment named one, and a [`Sweeper`](super::Sweeper)
//! thread where it did not. Either way it is ONE clock for the arrangement and never a timer per
//! node.
//!
//! # Coalescing is PER SOURCE, and that is not the inbox's capacity
//!
//! A burst of one upstream's ticks is one look — each says *look at this store again*, and one look
//! answers all of them. What that must not become is one upstream's burst filling the shared inbox
//! and evicting another upstream's tick, which would let a fast reaper starve a slow compactor
//! indefinitely. So the cell is the SOURCE's: a [`Ticker`] holds a capacity-one flag of its own,
//! sets it when it queues a tick and frees it when the resident takes that tick out of the inbox.
//! The thread engine spells the same posture as arithmetic — a upstream that came due is rescheduled
//! one interval from NOW rather than from its own missed deadline, so a pass that ran long is one
//! look and never a burst of catch-up ticks.
//!
//! # State lives in the node, capabilities live in the clock's own context
//!
//! [`Seats`] is the seam, and it takes the upstream's identity and the operator. The node struct holds
//! only its own state; the handles a sweep deletes or compacts through are lent to it per invocation
//! by the resident, which is what makes the DECLARATION the single authority on what a sweep can
//! reach: a context is emitted from a node's own words, so a capability it was never granted is a
//! BOUND NOTHING SATISFIES rather than a check somebody has to run.
//!
//! Which words grant which handles is settled: `write = "…"` INSIDE a `poll(…)` entry grants that
//! CLOCK's ticks a store, so a node's clocks are lent different contexts and a tick reaching for a
//! sibling clock's store is refused by the compiler at the line that reached. This layer never
//! learns what is inside a context — it is a type parameter, and the emitted per-clock contexts are
//! the declaration's business.

use core::{future::Future, time::Duration};

use std::{
  sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
  },
  time::Instant,
};

use super::{
  Rings,
  channel::{Outbox, Wake},
  policy::{Missed, Ticks},
};

pub use calendar::{Calendar, CalendarError};

mod calendar;

/// WHICH poll upstream a tick came from — a position in the node's [`Schedule`].
///
/// An index rather than a name, for [`NodeId`](crate::NodeId)'s reason: the set of a node's poll
/// upstreams is a compile-time fact, so the emitted wrapper maps this back to the upstream it authored
/// and a hand-wired arrangement spells the position directly. Nothing in this layer can name a
/// declared node, and an index is what does not pretend to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display("poll#{_0}")]
pub struct PollUpstream(usize);

impl PollUpstream {
  /// The upstream at `index` in declaration order.
  #[inline]
  #[must_use]
  pub const fn new(index: usize) -> Self {
    Self(index)
  }

  /// Its position in declaration order.
  #[inline]
  #[must_use]
  pub const fn index(&self) -> usize {
    self.0
  }
}

/// How ONE poll entry recurs: on a fixed interval, or on a calendar.
///
/// An enum and not a trait, and the framework-open rule is why rather than an exception to it: this
/// vocabulary is the GRAMMAR's, closed by the ruling that wrote it — an entry carries exactly one of
/// `every = "…"` and `cron = "…"`, and a third arm would arrive with the third word that declares
/// one. What IS open is the calendar's implementation, and that is a seam of its own ([`calendar`]),
/// which is where the openness this axis needs actually lives.
#[derive(Debug, Clone)]
pub enum Recurrence {
  /// `every = "…"` — a fixed interval, measured from each fire.
  Every(Duration),
  /// `cron = "…"` — a calendar expression, in the zone it was read in.
  Calendar(Calendar),
}

impl Recurrence {
  /// THE NEXT-DUE CORE: how long from NOW until this entry is due, or `None` where it never is
  /// again.
  ///
  /// One function, three clocks. The thread engine folds it into a park timeout, the sweeper's
  /// wheel adds it to an instant, and the runtime's After family arms a timer with it — and none of
  /// them branches on which arm answered, which is the whole reason the two cadences cost the
  /// engines nothing.
  ///
  /// The interval arm answers its interval, measured from NOW rather than from a deadline it may
  /// have missed: a pass that ran long is ONE look and never a burst of catch-up ticks. That is the
  /// same posture [`Ticker`]'s cell spells about the inbox, said about the clock.
  #[must_use]
  pub fn until_next(&self) -> Option<Duration> {
    match self {
      Self::Every(interval) => Some(*interval),
      Self::Calendar(calendar) => calendar.until_next(),
    }
  }

  /// HOW MANY of this entry's ticks are owed at `now`, given that one came due at `due` — the
  /// count a [`TickPolicy`](crate::TickPolicy) caps on.
  ///
  /// It counts the one due at `due`, so an entry that fired on time owes exactly `1` and nothing
  /// was missed.
  ///
  /// The INTERVAL arm is the only one that can count. A calendar's occurrences are not a series
  /// with a step — the next one is computed forward from now and there is no arithmetic that walks
  /// backwards over the ones a sleeping machine went past — so a calendar entry always answers `1`
  /// and keeps today's coalescing posture whatever the policy would have said. A calendar makeup
  /// arrives with a calendar seam that can enumerate backwards.
  ///
  /// A zero interval answers `1` for the same reason a divisor of zero has no quotient. The grammar
  /// refuses a zero duration; the hand-wired door does not, and this is what keeps that door from
  /// asking for infinitely many ticks.
  #[must_use]
  pub fn owed(&self, due: Instant, now: Instant) -> u32 {
    let Self::Every(interval) = self else {
      return 1;
    };
    if interval.is_zero() {
      return 1;
    }
    let elapsed = now.saturating_duration_since(due);
    let passed = elapsed.as_nanos() / interval.as_nanos();
    // Saturating, and the ceiling is the honest answer rather than a cap chosen here: a machine
    // that slept for a year owes more ticks than a `u32` holds, and what a policy does with a very
    // large number is the policy's business — it is the party that was given the count so that it
    // could refuse one.
    1u32.saturating_add(u32::try_from(passed).unwrap_or(u32::MAX))
  }

  /// When the `owed`th tick after `due` falls — the SERIES' own next instant.
  ///
  /// `None` where this entry has no next occurrence, which is [`until_next`](Self::until_next)'s
  /// own answer for a calendar that has run out.
  #[must_use]
  pub fn after(&self, due: Instant, owed: u32) -> Option<Instant> {
    let Self::Every(interval) = self else {
      return self.until_next().map(|wait| due + wait);
    };
    interval
      .checked_mul(owed)
      .and_then(|elapsed| due.checked_add(elapsed))
  }
}

/// A node's poll entries and the clock each one keeps, in declaration order.
///
/// Nothing schedule-shaped exists at node level: the cadence rides the entry's own word, so a
/// reaper that walks one store every ten minutes and compacts another at three in the morning is
/// ONE node with two entries here. An empty schedule is a node with no poll entry, which is most of
/// them.
#[derive(Debug, Clone, Default)]
pub struct Schedule {
  entries: Vec<Recurrence>,
}

impl Schedule {
  /// No poll entries.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      entries: Vec::new(),
    }
  }

  /// Add one poll entry, ticking every `interval`.
  ///
  /// Appends, so the position an entry lands at is the order it was declared in — which is what
  /// makes a [`PollUpstream`] mean the same thing to the wiring and to the node.
  #[inline]
  #[must_use]
  pub fn every(mut self, interval: Duration) -> Self {
    self.entries.push(Recurrence::Every(interval));
    self
  }

  /// Add one poll entry on a calendar expression, in the SYSTEM's zone.
  ///
  /// # Errors
  /// [`CalendarError`] where the expression is not one — the same refusal the derive makes at
  /// expansion, made again here because this door is also reachable by hand.
  pub fn cron(self, expression: &str) -> Result<Self, CalendarError> {
    Ok(self.recurring(Recurrence::Calendar(Calendar::parse(expression)?)))
  }

  /// Add one poll entry on a calendar expression, in `zone` — an IANA name.
  ///
  /// # Errors
  /// [`CalendarError`] where the expression is not one, or where this machine's time zone database
  /// does not have `zone`.
  pub fn cron_in(self, expression: &str, zone: &str) -> Result<Self, CalendarError> {
    Ok(self.recurring(Recurrence::Calendar(Calendar::parse_in(expression, zone)?)))
  }

  /// Add one poll entry on a recurrence already read.
  ///
  /// The door an emitted schedule uses, both arms through one call.
  #[inline]
  #[must_use]
  pub fn recurring(mut self, recurrence: Recurrence) -> Self {
    self.entries.push(recurrence);
    self
  }

  /// How many poll entries this node has.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.entries.len()
  }

  /// Whether it has none.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.entries.is_empty()
  }

  /// How `upstream` recurs, or `None` where this schedule has no such entry.
  #[inline]
  #[must_use]
  pub fn recurrence(&self, upstream: PollUpstream) -> Option<&Recurrence> {
    self.entries.get(upstream.index())
  }

  /// How often `upstream` ticks, where it ticks on an INTERVAL.
  ///
  /// `None` says one of two things — this schedule has no such entry, or that entry keeps a
  /// calendar and has no fixed interval to report. [`recurrence`](Self::recurrence) is what tells
  /// them apart; this is the narrowing a caller reaches for when it already knows which it has.
  #[inline]
  #[must_use]
  pub fn interval(&self, upstream: PollUpstream) -> Option<Duration> {
    match self.entries.get(upstream.index()) {
      Some(Recurrence::Every(interval)) => Some(*interval),
      _ => None,
    }
  }

  /// One [`Cadence`] per poll upstream, each ringing `outbox`'s consumer under that upstream's
  /// identity — the ASYNC engine's whole wiring, ready for whichever clock the ignition door chose.
  ///
  /// It is written here rather than left to each caller because the pairing is the fact that must
  /// not drift: a ticker minted for one position and given another position's interval would run a
  /// upstream at a cadence its declaration never asked for, and nothing downstream could notice.
  #[must_use]
  pub fn cadences<K, T>(&self, outbox: &Outbox<K, T>) -> Vec<Cadence>
  where
    K: Send + 'static,
    T: Send + 'static,
  {
    self
      .entries
      .iter()
      .enumerate()
      .map(|(index, recurrence)| {
        Cadence::recurring(
          recurrence.clone(),
          Box::new(outbox.ticker(PollUpstream::new(index))),
        )
      })
      .collect()
  }
}

/// What a node's LENDING does when one of its clocks comes due: SEAT the operator at that clock,
/// and run the entry seated there.
///
/// # The receiver is the CONTEXT, and that is forced rather than chosen
///
/// A grant is seated in the `poll(…)` entry that spends it, so a node's clocks are lent DIFFERENT
/// contexts and something has to route a tick's position to the right one. That router is emitted,
/// because only the declaration knows how many clocks there are — and the derive sits on the RECORD
/// while the operator is another type entirely, so the router cannot name the operator. Written as a
/// blanket over it, `impl<O> Seats<…> for O` is `E0210`: an uncovered type parameter standing before
/// the first local type. Written this way round the self type is the emitted lending, which is
/// local, and the impl is legal.
///
/// So the subject here is the value that HOLDS the capabilities and the argument is the value that
/// SPENDS them, which is also the honest reading: a lending seats an operator, one clock at a time.
///
/// # The tick carries an identity and the seat carries the capabilities
///
/// A poll edge moves no messages — the ruling is explicit that a tick is a wake and the node reads
/// through what it holds — so the two arguments are the whole of what a seating is given. `upstream`
/// says which of the node's declared clocks came due; `operator` is the node value, whose own state
/// reaches its entry through `&mut self` there.
///
/// EVERY declared polling node gets an emitted lending, whatever it granted — the threshold the
/// mode words widened, because a clock now says WHERE it runs and something has to route that. What
/// varies is what the lending holds: a node granted nothing and mounting nothing lends a sealed
/// empty struct. The HAND-WRITTEN road stays open beside it, and a hand-written lending is what
/// still reads `upstream` itself — the surviving consumer of `<Node>Due`'s translation.
///
/// # Why the borrow of the operator is EXCLUSIVE
///
/// Because an entry is a method on it. And why the CONTEXT the entry is handed is exclusive too: so
/// that a granted capability is CALLABLE. The framework's own write socket is
/// [`AsyncLands::land`](super::AsyncLands), it takes `&mut self` for a reason argued at its own signature — a
/// keyed replace over a batch is not atomic across two callers — and a context lent by shared
/// reference could not reach it. A `write` grant therefore becomes a `AsyncLands<Granted>` BOUND on the
/// clock's context rather than an accessor that hands a handle out, which is the same shape the read
/// lane already has: [`Serves`](super::Serves) is a capability an arm holds and calls, not a value
/// it borrows out of a shelf.
///
/// It costs nothing that was not already spent. The resident owns both values, one sweep runs at a
/// time, and a clock with several capabilities holds one context that satisfies several bounds — so
/// the exclusive borrows serialise nothing that could have overlapped.
///
/// # Why it is async, and why both engines still drive it
///
/// [`AsyncLands::land`](super::AsyncLands)'s reason verbatim: every store face this crate carries hands
/// back a future, so a sweep that deletes rows is async whether or not this seam is. The thread
/// engine blocks on it exactly where it blocks on its own write, and the async engine awaits it.
///
/// # The LENDING is not a bound on the node
///
/// A node with no poll upstream carries [`Unpolled`], which seats nothing — so a resident is generic
/// over its lending the way it is generic over its lane, and a node that declared no poll upstream
/// writes nothing for the one it does not have. Nothing about an operator's own type says whether it
/// is swept: the seam is stated from the lending's side, so a node that gains a clock gains a lending
/// and changes nothing else.
///
/// # TWO ROADS to a handle this node does not own, and they are deliberately separate
///
/// This one is PER-CLOCK and LEAST-PRIVILEGE: a sweep's context holds exactly the capabilities its
/// own `poll(…)` entry was [granted](crate::Grant), the set is a fact about the DECLARATION, and a
/// clock reaching past its grants does not compile. What it buys is an audit — the whole permission
/// surface of a deployment is readable from its declarations, with no deployment running.
///
/// The other is [`Context::shared`](crate::Context::shared), which every face of this crate carries:
/// DEPLOYMENT-WIDE, reached BY TYPE, answered at the moment of asking, refused with a runtime `Err`
/// where nothing built the thing. That is the door for the need a declaration cannot enumerate.
///
/// They do not overlap and neither is the other's fallback. A grant widened by a runtime lookup
/// would stop being least-privilege; a window narrowed to a declared list would stop serving the
/// case it exists for. See [`Grant`](crate::Grant), which carries the same paragraph from the
/// permission side.
pub trait Seats<O> {
  /// What one sweep has to say about itself — the info the observation it becomes carries, which is
  /// where *deleted 412 rows* is actually said.
  ///
  /// Bound-free here, as [`Operator::Error`](crate::Operator) is: the erasure a tap needs costs
  /// `Any + Send + Sync`, and the driver asks for it at its own call site rather than making every
  /// node pay for it whether or not a tap is registered.
  type Info;

  /// What a sweep can fail with. Bound-free for [`Info`](Self::Info)'s reason.
  type Error;

  /// Seat `operator` at the clock `upstream` names, and run the entry seated there.
  fn seat(
    &mut self,
    operator: &mut O,
    upstream: PollUpstream,
  ) -> impl Future<Output = Result<Swept<Self::Info>, Self::Error>> + Send;
}

/// WHAT BECAME OF ONE TICK, as the seat answers it.
///
/// Three answers rather than one, because a poll entry now says WHERE it runs and only one of the
/// five words runs the body here. Each arm is a different thing for the driver to say, and none of
/// them is derivable from another:
///
///   * [`Ran`](Self::Ran) — the body ran on this seating and answered. The inline modes (`block`,
///     `async(inline)`) and every hand-written lending. Its info reaches the taps.
///   * [`Dispatched`](Self::Dispatched) — the body was handed to an executor and is running
///     elsewhere. The detached modes (`spawn`, `rayon`, `async(spawn)`). Nothing is claimed about
///     it, because nothing is known yet and the party that will know holds no tap.
///   * [`Lapped`](Self::Lapped) — a previous tick of this clock is STILL RUNNING, so this one was
///     skipped. The at-most-one-in-flight default of the sync-detached family, and the resident
///     turns it into [`Observation::Lapped`](super::Observation) at INFO.
///
/// # Why it is not `Option<Info>`
///
/// Because *nothing to report yet* and *nothing happened* are different facts and a deployment
/// watches them differently: a stream of laps says the cadence is faster than the work, which is a
/// configuration to change, while a dispatch says the work left. An option would fold the two into
/// one absent value, and the tap that wanted to alarm on the first could not find it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Swept<I> {
  /// The body ran HERE, and this is what it said.
  Ran(I),
  /// The body was handed to an executor; its answer reaches no tap.
  Dispatched,
  /// The previous tick of this clock is still in flight, so this one was skipped.
  Lapped,
}

/// The absence of a poll arm, as a type.
///
/// [`AsyncLands for ()`](super::AsyncLands)' face for a lending rather than for a lane, and it is a marker
/// of this crate's own rather than `()` for one reason: `()` is a perfectly good context for a poll
/// node that needs no handles at all — a watchdog whose whole output is what a tap sees — and the
/// impl below would make that spelling unwritable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Unpolled;

/// The absent lending seats every operator at nothing.
///
/// The impl is what lets [`Resident`](super::Resident)'s loop be written once: the sweep arm is a
/// call whose bounds a non-polling node satisfies for free, rather than a branch on whether the
/// node had one. Its body is never reached, because a resident with no schedule and no ticker is a
/// resident nothing ever ticks.
///
/// It is stated over `O` and not the other way round — one impl here rather than a blanket over
/// every operator in the program — which is the same E0210 fact read from the side where it costs
/// nothing.
impl<O> Seats<O> for Unpolled {
  type Error = core::convert::Infallible;
  type Info = ();

  #[inline(always)]
  fn seat(
    &mut self,
    _operator: &mut O,
    _source: PollUpstream,
  ) -> impl Future<Output = Result<Swept<()>, Self::Error>> + Send {
    core::future::ready(Ok(Swept::Ran(())))
  }
}

/// One tick as the inbox carries it: WHICH upstream rang, and the capacity-one cell that ring
/// occupied.
///
/// The cell travels WITH the tick, which is what makes the coalescing per upstream without the inbox
/// having to know how many upstreams a node has: the party that consumes a tick is the party that
/// frees the cell, so the upstream may ring again from the moment its tick is taken and not before.
///
/// Named for the past tense because the present one is the CITIZEN: [`AsyncTick`](super::AsyncTick) is the
/// trait a mounted handler implements, and one word could not be both the message and the body it
/// wakes.
#[derive(Debug)]
pub struct Ticked {
  upstream: PollUpstream,
  queued: Arc<AtomicBool>,
}

impl Ticked {
  /// Which upstream came due.
  #[inline]
  #[must_use]
  pub const fn upstream(&self) -> PollUpstream {
    self.upstream
  }
}

impl Drop for Ticked {
  /// Free this upstream's cell.
  ///
  /// In `Drop` rather than at the one call site that reads a tick, because the invariant is about
  /// every path a tick can end on: a tick the inbox refused for want of room, and a tick left in an
  /// inbox that is being torn down, both have to leave the cell as they found it. A cell nobody
  /// freed is a upstream that never ticks again.
  #[inline]
  fn drop(&mut self) {
    self.queued.store(false, Ordering::Release);
  }
}

/// One poll upstream's ringer — the ASYNC engine's half of the clock.
///
/// [`Nudge`](super::Nudge)'s sibling and a strict widening of it: a nudge says *look again* and
/// this says *look at THIS upstream again*, which is the whole difference between a liveness floor
/// and a schedule.
///
/// It holds a full sender, so — like a nudge — it keeps the consumer's channel alive. That is
/// load-bearing here rather than a side effect: a node whose only upstreams are poll upstreams has no
/// data producer at all, so its tickers and whatever [`Outbox`] the arrangement kept are the only
/// things standing between it and an immediate shutdown-by-disconnect.
#[derive(Debug)]
pub struct Ticker<K, T> {
  upstream: PollUpstream,
  tx: flume::Sender<Wake<K, T>>,
  queued: Arc<AtomicBool>,
}

impl<K, T> Ticker<K, T> {
  /// A ringer for `upstream` over `tx`, with a fresh cell of its own.
  #[inline]
  pub(super) fn new(upstream: PollUpstream, tx: flume::Sender<Wake<K, T>>) -> Self {
    Self {
      upstream,
      tx,
      queued: Arc::new(AtomicBool::new(false)),
    }
  }

  /// Which upstream this ringer speaks for.
  #[inline]
  #[must_use]
  pub const fn upstream(&self) -> PollUpstream {
    self.upstream
  }
}

// Hand-written so `K`/`T` need not be `Clone`, as [`Outbox`]'s own is — and it shares the CELL,
// because two handles to one upstream are one upstream: cloning a ticker must not double the ticks the
// node sees.
impl<K, T> Clone for Ticker<K, T> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      upstream: self.upstream,
      tx: self.tx.clone(),
      queued: self.queued.clone(),
    }
  }
}

impl<K, T> Rings for Ticker<K, T>
where
  K: Send,
  T: Send,
{
  fn ring(&self) -> bool {
    // THE per-upstream capacity-one cell. A second ring while this upstream's tick is still unread says
    // exactly what the first says, so it coalesces HERE — in a cell this upstream owns — rather than
    // in the shared inbox, where a fast upstream's burst would fill the buffer and a slow upstream's
    // tick would be the one dropped.
    if self.queued.swap(true, Ordering::AcqRel) {
      return !self.tx.is_disconnected();
    }
    match self.tx.try_send(Wake::Tick(Ticked {
      upstream: self.upstream,
      queued: self.queued.clone(),
    })) {
      Ok(()) => true,
      Err(flume::TrySendError::Full(unsent)) => {
        // No room, so this tick is not queued and its cell must not stay claimed — dropping the
        // unsent message is what frees it (see [`Ticked`]'s `Drop`), and the next interval rings
        // again. Nothing is lost by waiting: an inbox with no room is an inbox with work in it, so
        // the consumer is about to be awake anyway.
        drop(unsent);
        true
      }
      Err(flume::TrySendError::Disconnected(unsent)) => {
        drop(unsent);
        false
      }
    }
  }
}

/// One registered ringer and the interval it rings on — what
/// [`Sweeper::ticking`](super::Sweeper::ticking) takes.
///
/// The pairing is the type because the two facts are useless apart: a clock serving several upstreams
/// has to know which interval belongs to which ringer, and a pair of parallel `Vec`s is a way for
/// them to stop belonging to each other.
pub struct Cadence {
  recurrence: Recurrence,
  ringer: Box<dyn Rings>,
}

impl Cadence {
  /// Ring `ringer` every `every` — the INTERVAL door, and the one the sweep floor takes.
  ///
  /// It keeps the plainest signature because the plainest cadence is what most callers have: a
  /// liveness sweep, a nudge, an entry that wrote `every = "…"`. The calendar arm arrives through
  /// [`recurring`](Self::recurring), which is what an emitted schedule and this module's own
  /// [`Schedule::cadences`] use.
  #[inline]
  #[must_use]
  pub fn new(every: Duration, ringer: Box<dyn Rings>) -> Self {
    Self::recurring(Recurrence::Every(every), ringer)
  }

  /// Ring `ringer` on `recurrence`, whichever arm it is.
  #[inline]
  #[must_use]
  pub fn recurring(recurrence: Recurrence, ringer: Box<dyn Rings>) -> Self {
    Self { recurrence, ringer }
  }

  /// How it recurs.
  #[inline]
  #[must_use]
  pub const fn recurrence(&self) -> &Recurrence {
    &self.recurrence
  }

  /// How long from NOW until it next rings — [`Recurrence::until_next`], through the pairing.
  #[inline]
  #[must_use]
  pub fn until_next(&self) -> Option<Duration> {
    self.recurrence.until_next()
  }

  /// Ring it.
  #[inline]
  pub(super) fn ring(&self) -> bool {
    self.ringer.ring()
  }

  /// Its two halves, taken apart.
  ///
  /// The [`AfterClock`](super::AfterClock)'s one door onto a cadence, and the pairing is undone
  /// rather than broken: that clock holds the interval in the timer it arms and the ringer behind a
  /// latch its own drop can open, so the two facts genuinely live in different places once a runtime
  /// is driving them. Everything BEFORE that — the wiring walk that mints them, the sweeper that
  /// rings them — keeps the pair, which is why it is the type.
  #[inline]
  pub(super) fn into_parts(self) -> (Recurrence, Box<dyn Rings>) {
    (self.recurrence, self.ringer)
  }
}

impl core::fmt::Debug for Cadence {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    // A ringer is a trait object with no `Debug` supertrait — asking for one would bound every
    // app's ringer for the benefit of this line — so a cadence reports its recurrence, which is what
    // a reader of a sweeper's debug output is actually after. [`Taps`](super::Taps)' own `Debug`
    // makes the same trade.
    f.debug_struct("Cadence")
      .field("recurrence", &self.recurrence)
      .finish_non_exhaustive()
  }
}

/// One poll entry's own clock inside a [`Clock`].
///
/// `due` is an OPTION because a calendar can run out: an expression whose next occurrence is past
/// what an instant holds is due never, and a clock told never stops asking rather than waking on a
/// schedule that will not fire.
#[derive(Debug)]
struct Ticking {
  recurrence: Recurrence,
  due: Option<Instant>,
}

/// The THREAD engine's poll clock: when each of a node's poll upstreams is next due.
///
/// It exists for the reason [`Inbox::park`](super::Inbox::park) takes a timeout at all — a resident
/// thread can time itself, so a tick it produces needs no message and no second thread. The async
/// engine's twin is whichever clock the ignition door chose, over this schedule's [`Cadence`]s,
/// which is the same table expressed in the engine that is running.
#[derive(Debug)]
pub(super) struct Clock {
  upstreams: Vec<Ticking>,
}

impl Clock {
  /// The clock for `schedule`, started at `now`.
  ///
  /// The FIRST tick falls one interval after launch, which is what a [`Sweeper`](super::Sweeper)
  /// does for the async engine — the two engines differ in how a tick arrives and never in when.
  pub(super) fn start(schedule: &Schedule, now: Instant) -> Self {
    Self {
      upstreams: schedule
        .entries
        .iter()
        .map(|recurrence| Ticking {
          due: recurrence.until_next().map(|wait| now + wait),
          recurrence: recurrence.clone(),
        })
        .collect(),
    }
  }

  /// How long to park: `sweep`, or less where a upstream comes due sooner.
  ///
  /// The minimum across every upstream AND the sweep, because both are floors on how long the loop
  /// may sleep and the shorter one wins. A node with no poll upstream gets its sweep back unchanged,
  /// which is what makes this fold the whole of the poll arm's effect on an ordinary resident.
  pub(super) fn park_for(&self, sweep: Duration, now: Instant) -> Duration {
    self
      .upstreams
      .iter()
      .filter_map(|upstream| upstream.due)
      .map(|due| due.saturating_duration_since(now))
      .fold(sweep, Duration::min)
  }

  /// Every upstream due at `now`, appended to `ticked` and rescheduled — with `ticks` answering for
  /// the ones that ran late.
  ///
  /// # The policy is asked only where the fork has ARISEN
  ///
  /// A upstream that fires on time missed nothing, so nothing is consulted and a deployment at the
  /// shipped default runs the line it always ran. What reaches [`Ticks::on_missed`] is a upstream
  /// whose deadline went by two or more intervals ago, which is the only case where *coalesce* and
  /// *catch up* differ at all.
  ///
  /// # The two answers, as arithmetic
  ///
  /// [`Coalesce`](crate::TickDecision::Coalesce) pushes ONE position and reschedules from NOW —
  /// today's line, unchanged. [`CatchUp`](crate::TickDecision::CatchUp) pushes one per owed
  /// interval and reschedules on the SERIES rather than from now, because a bucketing pass whose
  /// makeup ticks drifted off the grid would fill the holes at the wrong instants.
  pub(super) fn take_due(&mut self, now: Instant, ticked: &mut Vec<PollUpstream>, ticks: &Ticks) {
    for (index, upstream) in self.upstreams.iter_mut().enumerate() {
      let Some(due) = upstream.due.filter(|due| *due <= now) else {
        continue;
      };
      let position = PollUpstream::new(index);
      let owed = upstream.recurrence.owed(due, now);
      if owed > 1 && ticks.on_missed(Missed::new(position, owed)).is_catch_up() {
        // The SERIES, not the clock: the first owed tick was due at `due` and the rest follow it by
        // whole intervals, so the next one is due where the series says and not where this pass
        // happened to end.
        upstream.due = upstream.recurrence.after(due, owed);
        ticked.extend(core::iter::repeat_n(position, owed as usize));
        continue;
      }
      // Measured from NOW, and never from the deadline that was missed: a pass that ran longer
      // than an interval is ONE look and not a burst of catch-up ticks. That is the thread
      // engine's spelling of the same per-upstream capacity-one posture [`Ticker`] spells with a
      // cell — and it is the ONE next-due core, so a calendar entry is rescheduled by exactly the
      // same line an interval one is.
      upstream.due = upstream.recurrence.until_next().map(|wait| now + wait);
      ticked.push(position);
    }
  }
}

#[cfg(test)]
mod tests;