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
//! Pluggable storage backends for dedup and reconciliation.
//!
//! This module provides trait-based abstractions for idempotency key tracking
//! and reconciliation request queuing, enabling production deployments to use
//! distributed backends (Redis, PostgreSQL, etc.) while maintaining simple
//! in-memory implementations for development and testing.
//!
use crateReconciliationRequest;
use Future;
use Pin;
use Poll;
/// A conformance suite an embedder runs against its own backend, to establish
/// the durability and atomicity that `is_durable()`, `cluster_safe()` and
/// `DurableAuditSink::durability()` only *declare*.
///
/// Covers all three storage traits: [`DedupStorage`], [`ReconciliationStorage`]
/// and [`crate::observability::audit_sink::DurableAuditSink`].
/// `dyn`-safe boxed async future for storage trait methods.
///
/// This is the return type of every [`DedupStorage`] and
/// [`ReconciliationStorage`] method. Implementations box their async body
/// with `Box::pin(async move { ... })`.
pub type BoxFuture<'a, T> = ;
/// Core implementation of the drive-a-future-from-sync-code pattern.
///
/// Both [`drive_dedup_future`] and [`drive_reconciliation_future`] delegate here,
/// so the two-step logic below is maintained in one place while each keeps its
/// own diagnostic.
///
/// Two steps, in this order:
///
/// 1. **Poll once with a no-op waker.** Every in-tree backend is in-memory and
/// resolves immediately, so the common case never touches the runtime and
/// costs nothing. It also means the pure-sync entry points keep working with
/// no Tokio runtime present at all.
/// 2. **If it is genuinely pending, hand it to the runtime.** A network-backed
/// store — Redis, PostgreSQL, DynamoDB — yields at least once, which is
/// exactly what `cluster_safe()` implies and what the strict production gate
/// requires. Polling such a future once and giving up turned the trait's own
/// recommended backends into a panic on the first inbound message. This is
/// the same bridge `fetch_ocsp_responses_with_cache_provider_scoped` uses.
///
/// Re-polling a future that returned `Pending` is part of the `Future`
/// contract — an executor may poll with a different waker, and implementations
/// re-register on each poll.
/// Drive a `BoxFuture` to completion synchronously.
///
/// This is provided for **sync receive paths** that cannot `.await` a future:
/// - `receive_push_sync` (dedup)
/// - `receive_with_mdn_with_reliability` and internal AS4 helpers (reconciliation)
///
/// All in-memory storage implementations return a `Poll::Ready` future immediately
/// and this function resolves them in O(1).
///
/// # Panics
/// Panics with a clear message if the future returns `Poll::Pending`, which
/// indicates an async backend being called from the sync path. For dedup, switch
/// to `receive_push`. For reconciliation sync callers, ensure
/// only in-memory backends are used on sync paths.
/// Drive a [`ReconciliationStorage`] `BoxFuture` to completion synchronously.
///
/// Provided for sync receive paths (`receive_with_mdn_with_reliability`, internal
/// AS4 pull/push helpers) that hold a `&dyn ReconciliationStorage` and cannot `.await`.
/// In-memory backends resolve immediately (`Poll::Ready`); network-backed backends must
/// not be used from sync paths — this function will panic with a diagnostic if they do.
///
/// # Panics
/// Panics if the future returns `Poll::Pending` (async backend on a sync path).
pub
/// Verdict returned by [`DedupStorage::claim`].
///
/// Deduplication is **two-phase**: a claim is taken before the message is
/// processed and settled once its fate is known. The single-call
/// check-and-record shape this replaces could not express "seen, but not yet
/// known to be handled", so a message that failed after the check had already
/// spent its replay protection — the retransmission was answered as a
/// duplicate and the message was lost (D59).
/// Trait for distributed dedup state storage.
///
/// # Two-phase protocol
///
/// | Step | Method | Meaning |
/// |---|---|---|
/// | 1 | [`claim`](Self::claim) | Atomically take the key, or report `Duplicate` / `InFlight` |
/// | 2a | [`accept`](Self::accept) | The message was handled durably — settle the key so replays are rejected for the TTL window |
/// | 2b | [`abandon`](Self::abandon) | The message was **not** handled — release the key so a retransmission is processed |
///
/// Splitting the two is what makes replay protection safe to spend: nothing is
/// permanently deduplicated until someone has taken durable responsibility for
/// it.
///
/// # Claim leases
///
/// An unsettled claim must **expire**. A process that crashes between `claim`
/// and `accept` would otherwise wedge that `eb:MessageId` forever, and no
/// retransmission could ever be processed. Implementations therefore record a
/// claim with a lease and treat an expired claim as absent, so a later
/// [`claim`](Self::claim) on the same key returns
/// [`Claimed`](DedupVerdict::Claimed) rather than
/// [`InFlight`](DedupVerdict::InFlight).
///
/// Size the lease above the longest plausible processing time and below the
/// sender's retransmission interval. [`TtlDedupStorage`] defaults to 5 minutes
/// ([`TtlDedupStorage::with_claim_lease`] overrides it).
///
/// # Async by default
///
/// Every method is **async** via a `BoxFuture` return so that production
/// backends on Redis, PostgreSQL, DynamoDB or SlateDB implement them natively
/// without `block_in_place` / `Handle::current().block_on(…)` boilerplate.
/// In-memory implementations wrap synchronous logic in
/// `Box::pin(async move { … })` and resolve on the first `.await`.
///
/// Infrastructure failures must **fail closed** — return `Err`, never a verdict
/// that lets an unverified message through.
///
/// # Implementing it
///
/// A process-local backend wraps synchronous logic; the future resolves on the
/// first `.await`.
///
/// ```
/// use asx_rs::storage::{BoxFuture, DedupStorage, DedupVerdict};
/// use std::collections::HashMap;
/// use std::sync::Mutex;
/// use std::time::{Duration, Instant};
///
/// #[derive(Debug, PartialEq)]
/// enum State {
/// /// Claimed but not settled; the lease expires at this instant.
/// InFlight(Instant),
/// Accepted,
/// }
///
/// #[derive(Debug, Default)]
/// struct MyMemoryStore {
/// entries: Mutex<HashMap<String, State>>,
/// }
///
/// impl DedupStorage for MyMemoryStore {
/// fn is_durable(&self) -> bool {
/// false // forgets everything on restart
/// }
///
/// fn claim<'a>(&'a self, key: &'a str) -> BoxFuture<'a, asx_rs::Result<DedupVerdict>> {
/// Box::pin(async move {
/// // A poisoned lock must fail closed, never report "not seen".
/// let mut entries = self.entries.lock().map_err(|_| {
/// asx_rs::AsxError::new(
/// asx_rs::ErrorCode::ReliabilityFailure,
/// "dedup mutex poisoned",
/// asx_rs::ErrorContext::new("my_memory_store"),
/// )
/// })?;
/// let now = Instant::now();
/// match entries.get(key) {
/// Some(State::Accepted) => return Ok(DedupVerdict::Duplicate),
/// // An unexpired claim is held by a concurrent attempt.
/// Some(State::InFlight(until)) if now < *until => {
/// return Ok(DedupVerdict::InFlight);
/// }
/// // Absent, or an expired lease we are free to take over.
/// _ => {}
/// }
/// entries.insert(key.to_string(), State::InFlight(now + Duration::from_secs(300)));
/// Ok(DedupVerdict::Claimed)
/// })
/// }
///
/// fn accept<'a>(&'a self, key: &'a str) -> BoxFuture<'a, asx_rs::Result<()>> {
/// Box::pin(async move {
/// let mut entries = self.entries.lock().unwrap();
/// entries.insert(key.to_string(), State::Accepted);
/// Ok(())
/// })
/// }
///
/// fn abandon<'a>(&'a self, key: &'a str) -> BoxFuture<'a, asx_rs::Result<()>> {
/// Box::pin(async move {
/// let mut entries = self.entries.lock().unwrap();
/// // Only drop our own unsettled claim — never an accepted key.
/// if matches!(entries.get(key), Some(State::InFlight(_))) {
/// entries.remove(key);
/// }
/// Ok(())
/// })
/// }
/// }
///
/// # fn main() {
/// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
/// let store = MyMemoryStore::default();
/// rt.block_on(async {
/// assert_eq!(store.claim("msg-1").await.unwrap(), DedupVerdict::Claimed);
/// assert_eq!(store.claim("msg-1").await.unwrap(), DedupVerdict::InFlight);
/// // Processing failed: release the key so the retransmission is processed.
/// store.abandon("msg-1").await.unwrap();
/// assert_eq!(store.claim("msg-1").await.unwrap(), DedupVerdict::Claimed);
/// store.accept("msg-1").await.unwrap();
/// assert_eq!(store.claim("msg-1").await.unwrap(), DedupVerdict::Duplicate);
/// });
/// # }
/// ```
///
/// A durable, cluster-safe backend declares both properties and does the work
/// in the returned future — one round trip, no `block_on`. The
/// [persistence guide](https://hupe1980.github.io/asx-rs/docs/persistence/)
/// has a Redis implementation, and `tests/interop_redis_storage_conformance.rs`
/// runs it against a real server.
/// Trait for distributed reconciliation request queuing.
/// Implementations must preserve order and prevent duplicate reconciliation attempts.
///
/// # Stability
///
/// `ReconciliationStorage` is part of the public API and is accepted by
/// several functions in [`crate::presets`] and [`crate::reliability`], but its
/// **trait shape — method signatures, return types, and error variants — is
/// subject to breaking change** while this crate is at `0.x`.
///
/// If you implement this trait in downstream code, pin to an exact `asx-rs`
/// version in your `Cargo.toml` to avoid unexpected breakage:
///
/// ```toml
/// [dependencies]
/// asx-rs = "=0.13.0" # exact-version pin — ReconciliationStorage is not yet stable
/// ```
///
/// The sealed-trait pattern is intentionally not used here so that downstream
/// crates can provide production-grade backends (PostgreSQL, Redis, etc.) before
/// this crate reaches `1.0`. Once the trait stabilises the exact-pin
/// requirement will be lifted and a crate-level migration notice will be
/// published.
/// An unsettled deduplication claim, handed to the caller with a first-seen
/// message.
///
/// Holding one means the key is **spent but not committed**: replays are held
/// off, and nothing is permanently deduplicated yet. Settle it once the
/// message's fate is durable —
///
/// * [`accept`](Self::accept) — persisted, queued or dead-lettered. Later
/// retransmissions of this `eb:MessageId` are answered as duplicates.
/// * [`abandon`](Self::abandon) — not handled. The next retransmission is
/// processed as first-seen, which is what turns `ReceptionAwareness` into a
/// recovery path.
///
/// Dropping a claim without settling it is not corruption, only a delay: the
/// backend's claim lease expires and a retransmission re-claims the key. It is
/// still a bug, so the drop is logged and the type is `#[must_use]`.
///
/// # Example
///
/// ```no_run
/// use asx_rs::storage::{DedupClaim, DedupStorage, DedupVerdict};
/// use std::sync::Arc;
///
/// # async fn example(
/// # backend: Arc<dyn DedupStorage>,
/// # key: &str,
/// # ) -> asx_rs::Result<()> {
/// # fn persist_and_dispatch() -> asx_rs::Result<()> { Ok(()) }
/// # fn dead_lettered(_: &asx_rs::AsxError) -> bool { false }
/// # let claim: DedupClaim = match backend.claim(key).await? {
/// # DedupVerdict::Claimed => unimplemented!("the receive pipeline mints this"),
/// # _ => return Ok(()),
/// # };
/// match persist_and_dispatch() {
/// Ok(()) => claim.accept().await?,
/// // The message is ours now — a duplicate must not replay it.
/// Err(e) if dead_lettered(&e) => claim.accept().await?,
/// // We could not take responsibility: let the sender retransmit.
/// Err(e) => {
/// claim.abandon().await?;
/// return Err(e);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub use ;
pub use DurableInMemoryDedupBackend;