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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! THE POLICY SEAM: the runtime behaviours a deployment may change, as four hook families.
//!
//! Everything this layer does at a fork today it does because a default said so, and until now
//! every one of those defaults was welded shut. A poll that fires while the previous pass is still
//! running is COALESCED; a failed item is held and never retried by the framework; a full edge
//! BLOCKS its sender; a query waits for as long as it takes. Each of those is a decision, each is
//! right for most deployments, and each is wrong for some — a time-bucketed reaper wants its missed
//! interval MADE UP rather than dropped, an audit deployment refuses to shed at all, a laptop
//! waking after eight hours owes forty-eight ticks somebody has to have an opinion about.
//!
//! # The four concerns, and nothing else in v1
//!
//! [`TickPolicy`] (the missed-tick posture), [`RetryPolicy`] (what a failed item earns),
//! [`OverflowPolicy`] (a full bounded edge), [`DeadlinePolicy`] (a door's ambient budget). The
//! inventory is closed for this round on purpose: a fifth concern arrives with the deployment that
//! names it, and each of the four already has a seat the runtime was going to reach anyway.
//!
//! # The hook law, which this module is the first citizen of
//!
//! 1. **Dyn-compatible.** Hooks are ASSEMBLED at launch — chosen from a deployment's own words —
//!    and a static parameter cannot express a runtime choice without putting one more type variable
//!    on every drive type that carries it. The calls are cold (per tick, per failure, per overflow
//!    event), so the vtable costs nothing that could be measured. [`Taps`](super::Taps) is the same
//!    shape and the precedent.
//! 2. **Fallible**, through [`BoxedError`](crate::BoxedError) — the layer is threaded, so an error
//!    crosses threads and is `Send + Sync`.
//! 3. **Hooks decide, the framework executes.** Every method here is SYNC and returns a decision.
//!    A backoff is a NUMBER the hook answers with and a sleep the framework performs; no hook can
//!    park the loop that consulted it, and none does IO.
//! 4. **A failed decision falls back to the shipped default and is REPORTED** — see below.
//!
//! # 叉 A: what a mad advisor gets
//!
//! A policy that answers `Err` is recorded through the tap seam as
//! [`Observation::PolicyFailed`](super::Observation::PolicyFailed) and the framework takes the
//! SHIPPED DEFAULT decision. A mad advisor must not stop the factory: *advice failed* is not *data
//! failed*, so nothing is skipped, nothing is dropped, and the
//! [`SkipReason`](crate::SkipReason) vocabulary — which is about CONTENT — is not conscripted to
//! describe a configuration mistake. The record is the whole diagnostic surface, which is why it
//! keeps the error's type.
//!
//! # 叉 B: explicit beats ambient
//!
//! A call site that states its own budget wins over the policy that would have supplied one. The
//! policy answers where the call site is silent, and never over it — see [`Deadlines::resolve`].
//!
//! # Policies are TYPES
//!
//! Never an enum. The three shipped [`OverflowPolicy`] impls are the whole of what the framework
//! itself needs, and they are ordinary types beside anybody else's: a deployment that wants to shed
//! only above a watermark, retry with jitter, or cap a catch-up at ten writes a type and hands it
//! over. What IS an enum here is the DECISION vocabulary — [`TickDecision`], [`RetryDecision`],
//! [`OverflowDecision`] — because those are the framework's own instruction set, and a fourth arm
//! would be a thing the framework does not know how to perform.
//!
//! # What is not here yet
//!
//! The declaration word (`policy(…)`) and config-driven selection: those ride the subscribe and
//! launch rounds. What a deployment writes today is code — [`Policies`] assembled and handed to a
//! [`Plan`](super::Plan) — and the shipped set reproduces today's behaviour exactly, so a
//! deployment that says nothing changes in no way at all.

use core::any::Any;

use std::sync::Arc;

use jiff::SignedDuration;
use smol_bytes::Utf8Bytes;

use crate::BoxedError;

use super::PollUpstream;

mod gate;

pub use gate::{Deadlines, Handover, Retries, Sheds, Ticks};

#[cfg(test)]
mod tests;

/// WHICH policy advised — the four v1 concerns, as a report names them.
///
/// A closed vocabulary and therefore an enum: it is the framework's own list of seats, not a place
/// anybody plugs into. `#[non_exhaustive]` because a fifth seat is a widening, and a reader
/// matching on it should not break when one arrives.
#[derive(
  Debug,
  Clone,
  Copy,
  PartialEq,
  Eq,
  PartialOrd,
  Ord,
  Hash,
  derive_more::Display,
  derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
#[non_exhaustive]
pub enum Concern {
  /// [`TickPolicy`].
  Tick,
  /// [`RetryPolicy`].
  Retry,
  /// [`OverflowPolicy`].
  Overflow,
  /// [`DeadlinePolicy`].
  Deadline,
}

impl Concern {
  /// A stable name for a tap, a log line and a metric label.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Tick => "tick",
      Self::Retry => "retry",
      Self::Overflow => "overflow",
      Self::Deadline => "deadline",
    }
  }
}

/// WHAT A MISSED TICK LOOKS LIKE from inside: which upstream, and how many of its intervals went by
/// unfired.
///
/// The count is what a custom policy caps on — the laptop that slept eight hours owes forty-eight
/// ticks of a ten-minute cadence, and *make them all up* is an answer only the deployment can give.
/// The upstream rides along because a node may declare several poll entries and they need not share a
/// posture: a reaper that may skip and a bucketing pass that may not are one node with two entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Missed {
  upstream: PollUpstream,
  missed: u32,
}

impl Missed {
  /// `missed` whole intervals of `upstream` went by with no tick.
  ///
  /// The count INCLUDES the one that is due now, so the smallest value a policy is ever shown is
  /// `2`: nothing was missed when a tick fires on time, and the framework does not ask about a fork
  /// that has not arisen.
  #[inline]
  #[must_use]
  pub const fn new(upstream: PollUpstream, missed: u32) -> Self {
    Self { upstream, missed }
  }

  /// Which of the node's declared poll upstreams.
  #[inline]
  #[must_use]
  pub const fn upstream(&self) -> PollUpstream {
    self.upstream
  }

  /// How many of its intervals are owed, the one due now included.
  #[inline]
  #[must_use]
  pub const fn missed(&self) -> u32 {
    self.missed
  }
}

/// WHAT TO DO ABOUT MISSED TICKS.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::IsVariant)]
pub enum TickDecision {
  /// One look answers them all — today's behaviour, and the right one whenever a tick means *go and
  /// see*.
  Coalesce,
  /// Fire every owed tick. What time-bucketed work needs: a missed interval there is a HOLE in a
  /// series, and no later look fills it.
  CatchUp,
}

/// THE MISSED-TICK POSTURE: what a node does when its clock ran late.
///
/// # The shipped default
///
/// [`Coalesce`], which is what both engines already do — the thread clock reschedules from NOW
/// rather than from the deadline it missed, and a [`Ticker`](super::Ticker)'s capacity-one cell
/// swallows a second ring. A deployment that says nothing keeps exactly that.
///
/// # On failure
///
/// [`TickDecision::Coalesce`] — the shipped default, which is also the safe one: a policy that
/// cannot answer must not be able to turn one late pass into a burst.
pub trait TickPolicy: Send + Sync {
  /// `missed` intervals of one poll upstream went by unfired. What now?
  ///
  /// # Errors
  ///
  /// Anything the policy cannot decide. It is recorded and the shipped default is taken — see the
  /// module note on 叉 A.
  fn on_missed(&self, missed: Missed) -> Result<TickDecision, BoxedError>;
}

/// ONE LOOK ANSWERS THEM ALL — the shipped [`TickPolicy`], and today's behaviour as a type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Coalesce;

impl TickPolicy for Coalesce {
  #[inline]
  fn on_missed(&self, _missed: Missed) -> Result<TickDecision, BoxedError> {
    Ok(TickDecision::Coalesce)
  }
}

/// EVERY OWED TICK FIRES — the counter-case [`Coalesce`] exists against, shipped so a deployment
/// that needs it names a type rather than writing one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct CatchUp;

impl TickPolicy for CatchUp {
  #[inline]
  fn on_missed(&self, _missed: Missed) -> Result<TickDecision, BoxedError> {
    Ok(TickDecision::CatchUp)
  }
}

/// WHAT A FAILED ITEM EARNS.
///
/// The backoff is a DECISION and the sleeping is the framework's: a hook that could wait would be a
/// hook that could stop the loop consulting it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::IsVariant)]
pub enum RetryDecision {
  /// Try it again, after `after` — `None` being *at once*.
  Retry {
    /// The backoff the policy computed.
    after: Option<SignedDuration>,
  },
  /// Stop. The framework schedules nothing; what happens to the item is the ack law's, which holds
  /// a failed item and lets its sender re-deliver.
  GiveUp,
}

/// WHAT A FAILED ITEM EARNS — attached at [`Station::is_settled`](super::Station::is_settled), which
/// is where the runtime already asks whether an item is done.
///
/// # The shipped default
///
/// [`NoRetry`], which is today's behaviour exactly: the framework schedules nothing, the failed
/// item is named in no released set, and its sender re-delivers it. Attempt counters, backoff and
/// dead-lettering are what a deployment adds by writing a type.
///
/// # On failure
///
/// [`RetryDecision::GiveUp`] — the shipped default. A policy that cannot answer must not be able to
/// schedule work.
pub trait RetryPolicy: Send + Sync {
  /// Attempt `attempt` failed with `error`. Again, or not?
  ///
  /// `attempt` counts from `1`, so the first failure is attempt one. The error crosses as
  /// `&dyn Error` for the reason [`Failure`](super::Failure) does: one policy serves every node in
  /// an arrangement, and each node's error is its own type.
  ///
  /// # Errors
  ///
  /// Anything the policy cannot decide — recorded, and the shipped default taken.
  fn on_failure(
    &self,
    attempt: u32,
    error: &(dyn core::error::Error + 'static),
  ) -> Result<RetryDecision, BoxedError>;
}

/// THE FRAMEWORK SCHEDULES NOTHING — the shipped [`RetryPolicy`], and today's behaviour as a type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct NoRetry;

impl RetryPolicy for NoRetry {
  #[inline]
  fn on_failure(
    &self,
    _attempt: u32,
    _error: &(dyn core::error::Error + 'static),
  ) -> Result<RetryDecision, BoxedError> {
    Ok(RetryDecision::GiveUp)
  }
}

/// HOW FULL AN EDGE WAS when its policy was asked.
///
/// The capacity is an OPTION because the question is askable of an unbounded edge too — a policy
/// consulted about one is being consulted about a queue that can never be full, which is the
/// contradiction the launch walk refuses before it can happen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Occupancy {
  queued: usize,
  capacity: Option<usize>,
}

impl Occupancy {
  /// `queued` messages sit in an edge bounded at `capacity`.
  #[inline]
  #[must_use]
  pub const fn bounded(queued: usize, capacity: usize) -> Self {
    Self {
      queued,
      capacity: Some(capacity),
    }
  }

  /// `queued` messages sit in an edge nothing bounds.
  #[inline]
  #[must_use]
  pub const fn unbounded(queued: usize) -> Self {
    Self {
      queued,
      capacity: None,
    }
  }

  /// How many messages are in it — DELIVERIES, as a channel's depth is counted.
  #[inline]
  #[must_use]
  pub const fn queued(&self) -> usize {
    self.queued
  }

  /// What bounds it, or `None` where nothing does.
  #[inline]
  #[must_use]
  pub const fn capacity(&self) -> Option<usize> {
    self.capacity
  }

  /// Whether it has no room left.
  #[inline]
  #[must_use]
  pub const fn is_full(&self) -> bool {
    match self.capacity {
      Some(capacity) => self.queued >= capacity,
      None => false,
    }
  }
}

/// WHAT TO DO ABOUT A FULL EDGE.
#[derive(
  Debug,
  Clone,
  Copy,
  PartialEq,
  Eq,
  PartialOrd,
  Ord,
  Hash,
  derive_more::Display,
  derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
pub enum OverflowDecision {
  /// Wait for room — today's behaviour, and the reason data on a channel edge is never lost.
  Block,
  /// Take the OLDEST queued message out to make room for this one. What a live-value feed wants:
  /// the stale reading is the one worth losing.
  DropOldest,
  /// Refuse this one and leave the queue alone. What a sampling intake wants: what is already in
  /// flight is worth more than what has just arrived.
  DropNewest,
}

impl OverflowDecision {
  /// A stable name for a tap and a log line.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Block => "block",
      Self::DropOldest => "drop_oldest",
      Self::DropNewest => "drop_newest",
    }
  }

  /// Whether taking this decision loses an item.
  #[inline]
  #[must_use]
  pub const fn is_shed(&self) -> bool {
    matches!(self, Self::DropOldest | Self::DropNewest)
  }
}

/// A FULL BOUNDED EDGE: block, or shed.
///
/// # The shipped default
///
/// [`Backpressure`], which is [`Outbox::deliver`](super::Outbox::deliver)'s whole posture and the
/// reason a data edge loses nothing: a slow consumer becomes backpressure on its producer. A
/// deployment that says nothing keeps exactly that.
///
/// # Every shed is RECORDED
///
/// A dropped item leaves an obituary through the tap seam —
/// [`Observation::Shed`](super::Observation::Shed) — carrying the item's COMPLETE key. Shedding is
/// legitimate and silence about it is not.
///
/// # On failure
///
/// [`OverflowDecision::Block`] — the shipped default, and the one that cannot lose data.
pub trait OverflowPolicy: Send + Sync {
  /// The edge is full at `occupancy`. Wait, or shed?
  ///
  /// # Errors
  ///
  /// Anything the policy cannot decide — recorded, and the shipped default taken.
  fn on_full(&self, occupancy: Occupancy) -> Result<OverflowDecision, BoxedError>;

  /// Whether this policy can EVER answer a drop — what the launch walk's contradiction row reads.
  ///
  /// An unbounded edge under a shedding policy is a deployment asking for two things that cannot
  /// both be true: nothing overflows a queue nothing bounds, so the shed would never happen and the
  /// word that asked for it would be silently inert. The launch walk refuses that pair by name —
  /// and to do so it has to know the answer BEFORE any edge is full, which no `on_full` call can
  /// give it.
  ///
  /// The default is `true`, which is the conservative half: a policy that says nothing about itself
  /// is assumed to be able to shed, so the contradiction is caught rather than missed. [`Backpressure`]
  /// overrides it, being the one shipped policy that provably never drops.
  #[inline]
  fn sheds(&self) -> bool {
    true
  }
}

/// WAIT FOR ROOM — the shipped [`OverflowPolicy`], and today's behaviour as a type.
///
/// Named for the effect rather than for the verb because the verb is spoken for: `Block` is the
/// BLOCKING MODE at the compute seam ([`Block`](crate::Block)), and one crate root cannot export the
/// word twice. The decision this policy answers keeps the verb — [`OverflowDecision::Block`] — so
/// the wire spelling a tap reads is unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Backpressure;

impl OverflowPolicy for Backpressure {
  #[inline]
  fn on_full(&self, _occupancy: Occupancy) -> Result<OverflowDecision, BoxedError> {
    Ok(OverflowDecision::Block)
  }

  /// The one shipped policy that can say `false` and mean it.
  #[inline]
  fn sheds(&self) -> bool {
    false
  }
}

/// MAKE ROOM BY LOSING THE OLDEST — the shipped shedding [`OverflowPolicy`] for a live-value feed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct DropOldest;

impl OverflowPolicy for DropOldest {
  #[inline]
  fn on_full(&self, _occupancy: Occupancy) -> Result<OverflowDecision, BoxedError> {
    Ok(OverflowDecision::DropOldest)
  }
}

/// REFUSE THE NEWEST — the shipped shedding [`OverflowPolicy`] for a sampling intake.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct DropNewest;

impl OverflowPolicy for DropNewest {
  #[inline]
  fn on_full(&self, _occupancy: Occupancy) -> Result<OverflowDecision, BoxedError> {
    Ok(OverflowDecision::DropNewest)
  }
}

/// A DOOR'S AMBIENT BUDGET: how long a question may take when its asker did not say.
///
/// # The shipped default
///
/// [`NoDeadline`], which is today's behaviour: [`Awaiting::take`](super::Awaiting::take) waits for
/// as long as the chain takes, and [`take_within`](super::Awaiting::take_within) is the only budget
/// there has ever been. A deployment that says nothing keeps exactly that.
///
/// # EXPLICIT BEATS AMBIENT
///
/// A call site that named its own budget is not overridden — see [`Deadlines::resolve`]. The policy
/// answers the silent caller and nobody else.
///
/// # On failure
///
/// `None` — no ambient budget, which is the shipped default and the one that cannot turn a
/// misconfigured policy into a storm of timeouts.
pub trait DeadlinePolicy: Send + Sync {
  /// How long a silent caller may wait, or `None` for as long as it takes.
  ///
  /// It takes no argument, which is the shape of the fact: an ambient deadline belongs to the DOOR
  /// rather than to one question, and a policy that wanted to answer per question would be asking
  /// for a knob the call site already has.
  ///
  /// # Errors
  ///
  /// Anything the policy cannot decide — recorded, and the shipped default taken.
  fn deadline(&self) -> Result<Option<SignedDuration>, BoxedError>;
}

/// AS LONG AS IT TAKES — the shipped [`DeadlinePolicy`], and today's behaviour as a type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct NoDeadline;

impl DeadlinePolicy for NoDeadline {
  #[inline]
  fn deadline(&self) -> Result<Option<SignedDuration>, BoxedError> {
    Ok(None)
  }
}

/// A FIXED AMBIENT BUDGET on a query door — `take_within`'s knob, said once for every silent
/// caller.
///
/// # The WIRE side of the same number lives on the search road
///
/// This one answers an in-process caller and is *explicit beats ambient*; a request arriving over a
/// wire composes the other way round, and the arithmetic for it is
/// [`tightened_budget`](crate::tightened_budget) — shelved beside
/// [`route_depth`](crate::route_depth), which is the preference half of the same law, and spent at
/// [`walk_within`](crate::walk_within). The two rules are the trust boundary written as arithmetic
/// at each side of it, and they are stated apart because they are answered apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QueryDeadline(SignedDuration);

impl QueryDeadline {
  /// Give every silent caller `budget`.
  #[inline]
  #[must_use]
  pub const fn of(budget: SignedDuration) -> Self {
    Self(budget)
  }

  /// The budget it hands out.
  #[inline]
  #[must_use]
  pub const fn budget(&self) -> SignedDuration {
    self.0
  }
}

impl DeadlinePolicy for QueryDeadline {
  #[inline]
  fn deadline(&self) -> Result<Option<SignedDuration>, BoxedError> {
    Ok(Some(self.0))
  }
}

/// THE COMPLETE ITEM KEY of a shed item, as a tap sees it.
///
/// # Why COMPLETE, and never the root alone
///
/// A root may own many items — a media file's segments, a document's pages — and *segment 41 of
/// this file was dropped* and *something belonging to this file was dropped* are different
/// sentences. Only the first can be counted, alarmed on, or re-derived. So the obituary carries the
/// key the NODE addresses its items by, whatever shape that is.
///
/// # Erased, and rendered
///
/// One tap observes every node in an arrangement and each node's key is its own type, so the key
/// crosses as `Any` — [`key`](Self::key) is the downcast for a tap that knows, exactly as
/// [`Arrival::info`](super::Arrival::info) is. The RENDERING is taken at the same moment and kept
/// beside it, because the tap that does not know the type is the one writing the log line, and it
/// has nowhere else to get a name from.
///
/// # ONE THIN POINTER, and the reason is the ack path
///
/// The two halves live behind a single `Arc` rather than beside each other, so this value is eight
/// bytes. That is the same trade [`Arrival`](super::Arrival) already makes with its boxed
/// [`Skip`](crate::Skip), argued at the same place: an [`Observation`](super::Observation) is as big
/// as its widest arm and one of its arms travels inside EVERY ack, so a shed's own payload is paid
/// for on the shed path — which is the uncommon one — instead of on all of them.
#[derive(Clone)]
pub struct ShedKey {
  named: Arc<Named>,
}

/// The two halves of a [`ShedKey`], behind its one pointer.
struct Named {
  key: Box<dyn Any + Send + Sync>,
  rendered: Utf8Bytes,
}

impl ShedKey {
  /// Erase `key`, keeping its rendering.
  #[inline]
  #[must_use]
  pub fn new<K>(key: K) -> Self
  where
    K: Any + core::fmt::Display + Send + Sync,
  {
    let rendered = Utf8Bytes::from(key.to_string());
    Self {
      named: Arc::new(Named {
        key: Box::new(key),
        rendered,
      }),
    }
  }

  /// The key as `K` — `None` where `K` is not what the node addressed its items by.
  #[inline]
  #[must_use]
  pub fn key<K: Any>(&self) -> Option<&K> {
    self.named.key.downcast_ref()
  }

  /// What it renders as, for a tap that does not know the type.
  #[inline]
  #[must_use]
  pub fn rendered(&self) -> &str {
    self.named.rendered.as_str()
  }
}

impl core::fmt::Debug for ShedKey {
  /// The rendering, which is the whole of what it can print: the key is erased and `Any` carries no
  /// [`Debug`](core::fmt::Debug), so demanding one would bound every node's key for this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_tuple("ShedKey").field(&self.rendered()).finish()
  }
}

impl core::fmt::Display for ShedKey {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(self.rendered())
  }
}

/// THE ASSEMBLED SET: one policy per concern, chosen once and spent everywhere.
///
/// # What a deployment writes
///
/// ```
/// use std::sync::Arc;
///
/// use ingraph::{CatchUp, Policies};
///
/// // Everything at the shipped default but the clock, which must not lose an interval.
/// let policies = Policies::new().with_tick_policy(Box::new(CatchUp));
/// assert!(policies.tick_policy().on_missed(ingraph::Missed::new(ingraph::PollUpstream::new(0), 4))
///   .expect("the shipped catch-up never fails")
///   .is_catch_up());
/// # let _ = Arc::new(());
/// ```
///
/// # `Box` at the door, `Arc` inside
///
/// A caller hands a `Box<dyn …>` because that is what building one produces. What the set HOLDS is
/// an `Arc`, because a gate is minted per node out of the same policy — [`Taps`](super::Taps)'
/// arrangement, for its reason: one value, many observers, no clone of the thing itself.
#[derive(Clone)]
pub struct Policies {
  tick: Arc<dyn TickPolicy>,
  retry: Arc<dyn RetryPolicy>,
  overflow: Arc<dyn OverflowPolicy>,
  deadline: Arc<dyn DeadlinePolicy>,
}

impl Policies {
  /// THE SHIPPED SET: [`Coalesce`], [`NoRetry`], [`Backpressure`], [`NoDeadline`] — today's behaviour,
  /// spelled out.
  ///
  /// It is written rather than left implicit, and that is the whole of what makes the seam a pure
  /// widening: an unconfigured deployment runs these four, and these four do what the welded
  /// defaults did.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      tick: Arc::new(Coalesce),
      retry: Arc::new(NoRetry),
      overflow: Arc::new(Backpressure),
      deadline: Arc::new(NoDeadline),
    }
  }

  /// Decide missed ticks with `policy`.
  #[inline]
  #[must_use]
  pub fn with_tick_policy(mut self, policy: Box<dyn TickPolicy>) -> Self {
    self.tick = Arc::from(policy);
    self
  }

  /// Decide failures with `policy`.
  #[inline]
  #[must_use]
  pub fn with_retry_policy(mut self, policy: Box<dyn RetryPolicy>) -> Self {
    self.retry = Arc::from(policy);
    self
  }

  /// Decide full edges with `policy`.
  #[inline]
  #[must_use]
  pub fn with_overflow_policy(mut self, policy: Box<dyn OverflowPolicy>) -> Self {
    self.overflow = Arc::from(policy);
    self
  }

  /// Decide ambient budgets with `policy`.
  #[inline]
  #[must_use]
  pub fn with_deadline_policy(mut self, policy: Box<dyn DeadlinePolicy>) -> Self {
    self.deadline = Arc::from(policy);
    self
  }

  /// The tick policy in force.
  #[inline]
  #[must_use]
  pub fn tick_policy(&self) -> &dyn TickPolicy {
    &*self.tick
  }

  /// The retry policy in force.
  #[inline]
  #[must_use]
  pub fn retry_policy(&self) -> &dyn RetryPolicy {
    &*self.retry
  }

  /// The overflow policy in force.
  #[inline]
  #[must_use]
  pub fn overflow_policy(&self) -> &dyn OverflowPolicy {
    &*self.overflow
  }

  /// The deadline policy in force.
  #[inline]
  #[must_use]
  pub fn deadline_policy(&self) -> &dyn DeadlinePolicy {
    &*self.deadline
  }

  /// The tick gate for the node called `node`, reporting through `taps`.
  #[inline]
  #[must_use]
  pub fn ticks(&self, node: impl Into<Utf8Bytes>, taps: super::Taps) -> Ticks {
    Ticks::new(Arc::clone(&self.tick), node.into(), taps)
  }

  /// The retry gate for the node called `node`, reporting through `taps`.
  #[inline]
  #[must_use]
  pub fn retries(&self, node: impl Into<Utf8Bytes>, taps: super::Taps) -> Retries {
    Retries::new(Arc::clone(&self.retry), node.into(), taps)
  }

  /// The overflow gate for the node called `node`, reporting through `taps`.
  #[inline]
  #[must_use]
  pub fn sheds(&self, node: impl Into<Utf8Bytes>, taps: super::Taps) -> Sheds {
    Sheds::new(Arc::clone(&self.overflow), node.into(), taps)
  }

  /// The deadline gate for the node called `node`, reporting through `taps`.
  #[inline]
  #[must_use]
  pub fn deadlines(&self, node: impl Into<Utf8Bytes>, taps: super::Taps) -> Deadlines {
    Deadlines::new(Arc::clone(&self.deadline), node.into(), taps)
  }
}

impl Default for Policies {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl core::fmt::Debug for Policies {
  /// The four concerns and whether each is still the shipped one — [`Taps`](super::Taps)' trade:
  /// a policy is a trait object with no [`Debug`](core::fmt::Debug) supertrait, so asking for one
  /// would bound every deployment's policy for the benefit of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Policies")
      .field("overflow_sheds", &self.overflow.sheds())
      .finish_non_exhaustive()
  }
}