Skip to main content

lean_ctx_cloud/
receipts.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `POST /v1/receipts` (receipts v2, C0 2.5 K2 M3): the Engine receipts of
3//! this machine's Cloud vaults.
4//!
5//! The tool path only notes a receipt: [`note_engine_receipt`] checks one
6//! marker file and, when uploads are on, turns the local v1 receipt into a
7//! closed `leanctx.instance-receipt/v2` document and queues it in the durable
8//! outbox. No lease, network or config work happens in a tool call. The
9//! scheduler keeps the marker in step with what allows receipts — the
10//! release switch, `[cloud] receipts_upload`, the lease's `receipts.upload`
11//! right (Enterprise), the workspace's `org_settings.receipts_upload` and no
12//! `upload_disabled` answer under the current lease — and sends the queue
13//! in signed batches (`leanctx.cloud.receipts/v2`, instance key).
14//!
15//! What leaves the engine (aggregates and opaque values only):
16//! - input and output digests as HMAC-SHA256 under an engine-local key
17//!   (`receipts.hmac-key`, created here, never uploaded): Cloud cannot test
18//!   a guess against them, the engine can re-derive them from its receipt;
19//! - the invocation and receipt ids as HMAC-derived hex, never the local id;
20//! - source references as a count; failure recovery references dropped;
21//! - the session the app names (`LEAN_CTX_SESSION_ID`, V9) only as an
22//!   HMAC under the same key (`session_ref`), never the id; absent outside
23//!   a session and while the enrolled Cloud does not announce `session_ref`
24//!   (`crate::session_ref`);
25//! - measurements with a contract name and unit only;
26//! - no policy reference: the Cloud policy digest is not bound to a local
27//!   invocation, so `policy_digest` is `null`.
28//!
29//! The checkout path stays on this machine: it only selects the Cloud
30//! vault, and a receipt of a checkout Cloud does not know is dropped.
31
32use std::path::Path;
33
34use ed25519_dalek::Signer as _;
35use lean_ctx_time::UtcDateTime;
36use serde_json::{Value, json};
37use sha2::Sha256;
38
39use super::auth::Session;
40use super::config::CloudConfig;
41use super::instance_key::InstanceKeys;
42use super::metrics_v2::gate::Sharing;
43use super::outbox::{CHANNEL_RECEIPTS, Outbox, OutboxItem};
44use super::state::{InstanceRecord, write_private};
45use super::vault::VaultMap;
46use super::{CloudError, CloudStore};
47use lean_ctx_protocol::cloud::CloudUploadKind;
48use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, CloudRight};
49use lean_ctx_protocol::cloud::metrics_v2::{KeyId, SignatureHex, TimeStamp, VaultId};
50use lean_ctx_protocol::cloud::receipts_v2::{
51    AdmissionDecision, CapabilityIdConst, Classification, EngineIdConst, EngineReceiptSchema,
52    EngineReceiptV2, FailureCode, FailureV2, HMAC_PREFIX, InvocationIdV2, MAX_MEASUREMENTS,
53    MAX_RECEIPTS_BODY_BYTES, MAX_RECEIPTS_V2, MAX_SOURCE_COUNT, MeasurementName, MeasurementUnit,
54    MeasurementV2, ObservationStatus, PolicyAdmissionV2, RECEIPTS_ROUTE, ReceiptEngineV2,
55    ReceiptHmac, ReceiptIdV2, ReceiptInvocationV2, ReceiptItemV2, ReceiptObservationV2,
56    ReceiptOperationV2, ReceiptSemver, ReceiptsAckV2, ReceiptsBodyV2, ReceiptsRequestV2,
57    ReceiptsSchema, SchemaVersionOne,
58};
59use lean_ctx_protocol::{
60    EngineFailureCodeV1, EngineInvocationV1, EngineObservationStatusV1, EngineObservationV1,
61    EnginePolicyDecisionV1, EngineValueClassificationV1,
62};
63
64const ENABLED_FILE: &str = "receipts.enabled";
65const DISABLED_FILE: &str = "receipts.disabled-lease";
66/// The engine-local receipt HMAC key (32 random bytes, hex). Never uploaded.
67// Only the unix permission check in the tests reads it.
68#[cfg(all(test, unix))]
69const KEY_FILE: &str = "receipts.hmac-key";
70
71/// The engine-local key that makes input/output values opaque to Cloud. The
72/// same key keys the digests of audit entries v2.
73#[derive(Clone)]
74pub(crate) struct ReceiptKey([u8; 32]);
75
76impl ReceiptKey {
77    /// The key in `cloud_data`, created on first use.
78    pub(crate) fn load_or_create(cloud_data: &Path) -> Option<Self> {
79        lean_ctx::core::audit_trail::load_or_create_hmac_key(cloud_data).map(Self)
80    }
81
82    #[cfg(test)]
83    pub(crate) fn from_bytes(bytes: [u8; 32]) -> Self {
84        Self(bytes)
85    }
86
87    /// HMAC-SHA256(key, `label` ‖ `\n` ‖ `data`), lowercase hex.
88    pub(crate) fn mac_hex(&self, label: &str, data: &str) -> String {
89        lean_ctx::core::audit_trail::hmac_hex(&self.0, label, data.as_bytes())
90    }
91
92    fn hmac(&self, label: &str, data: &str) -> Option<ReceiptHmac> {
93        ReceiptHmac::new(&format!("{HMAC_PREFIX}{}", self.mac_hex(label, data)))
94    }
95}
96
97fn unit_of(unit: &str) -> Option<MeasurementUnit> {
98    // The local receipt says `token`; the contract `tokens`.
99    MeasurementUnit::of(if unit == "token" { "tokens" } else { unit })
100}
101
102fn count(n: usize, floor: u16) -> u16 {
103    u16::try_from(n)
104        .unwrap_or(MAX_SOURCE_COUNT)
105        .clamp(floor, MAX_SOURCE_COUNT)
106}
107
108/// The v2 receipt id and document of a local receipt, or `None` when it
109/// cannot be expressed in the closed contract (it is then not sent).
110/// `session` is the local session id (V9): it leaves only as its HMAC.
111pub(crate) fn to_v2(
112    key: &ReceiptKey,
113    receipt_id: &str,
114    invocation: &EngineInvocationV1,
115    observation: &EngineObservationV1,
116    session: Option<&str>,
117) -> Option<(ReceiptIdV2, EngineReceiptV2)> {
118    let rcpt = ReceiptIdV2::new(&format!(
119        "rcpt_{}",
120        &key.mac_hex("receipt", receipt_id)[..32]
121    ))?;
122    let invocation_id =
123        InvocationIdV2::new(&key.mac_hex("invocation", invocation.invocation_id.as_str())[..32])?;
124    let measurements = observation
125        .measurements
126        .iter()
127        .filter_map(|m| {
128            Some(MeasurementV2 {
129                name: MeasurementName::new(&m.name)?,
130                unit: unit_of(&m.unit)?,
131                classification: match m.classification {
132                    EngineValueClassificationV1::Measured => Classification::Measured,
133                    EngineValueClassificationV1::Estimated => Classification::Estimated,
134                    EngineValueClassificationV1::Unavailable => Classification::Unavailable,
135                },
136                value: m.value,
137            })
138        })
139        .take(MAX_MEASUREMENTS)
140        .collect();
141    let document = EngineReceiptV2 {
142        schema: EngineReceiptSchema,
143        invocation: ReceiptInvocationV2 {
144            schema_version: SchemaVersionOne,
145            invocation_id: invocation_id.clone(),
146            instance: ReceiptEngineV2 {
147                instance_id: EngineIdConst,
148                instance_version: ReceiptSemver::new(invocation.engine.engine_version.as_str())?,
149            },
150            operation: ReceiptOperationV2 {
151                capability_id: (invocation.operation.capability_id.as_str()
152                    == lean_ctx_protocol::cloud::receipts_v2::RECEIPT_CAPABILITY_ID)
153                    .then_some(CapabilityIdConst)?,
154                capability_version: ReceiptSemver::new(
155                    invocation.operation.capability_version.as_str(),
156                )?,
157            },
158            input_hmac: key.hmac("input", invocation.input_digest.as_str())?,
159            source_count: count(invocation.source_refs.len(), 1),
160            session_ref: match session {
161                Some(id) => Some(key.hmac("session", id)?),
162                None => None,
163            },
164            policy_admission: PolicyAdmissionV2 {
165                decision: match invocation.policy_admission.decision {
166                    EnginePolicyDecisionV1::Admitted => AdmissionDecision::Admitted,
167                    EnginePolicyDecisionV1::Rejected => AdmissionDecision::Rejected,
168                },
169                policy_digest: None,
170            },
171        },
172        observation: ReceiptObservationV2 {
173            schema_version: SchemaVersionOne,
174            invocation_id,
175            status: match observation.status {
176                EngineObservationStatusV1::Succeeded => ObservationStatus::Succeeded,
177                EngineObservationStatusV1::Degraded => ObservationStatus::Degraded,
178                EngineObservationStatusV1::Rejected => ObservationStatus::Rejected,
179                EngineObservationStatusV1::Failed => ObservationStatus::Failed,
180            },
181            output_hmac: match &observation.output_digest {
182                Some(digest) => Some(key.hmac("output", digest.as_str())?),
183                None => None,
184            },
185            source_count: count(observation.source_lineage.len(), 0),
186            measurements,
187            failure: observation.failure.as_ref().map(|f| FailureV2 {
188                code: match f.code {
189                    EngineFailureCodeV1::PolicyRejected => FailureCode::PolicyRejected,
190                    EngineFailureCodeV1::SourceUnavailable => FailureCode::SourceUnavailable,
191                    EngineFailureCodeV1::SourceIntegrityMismatch => {
192                        FailureCode::SourceIntegrityMismatch
193                    }
194                    EngineFailureCodeV1::ResourceLimit => FailureCode::ResourceLimit,
195                    EngineFailureCodeV1::UnsupportedOperation => FailureCode::UnsupportedOperation,
196                    EngineFailureCodeV1::Internal => FailureCode::Internal,
197                },
198                retryable_by_host: f.retryable_by_host,
199            }),
200        },
201    };
202    document.validate().ok()?;
203    Some((rcpt, document))
204}
205
206/// Queue an Engine receipt for Cloud, if receipt uploads are on. Cheap and
207/// silent: a failure here never fails the Engine call that produced it.
208pub fn note_engine_receipt(
209    root: &Path,
210    receipt_id: &str,
211    invocation: &EngineInvocationV1,
212    observation: &EngineObservationV1,
213    now: UtcDateTime,
214) {
215    let Ok(store) = CloudStore::open() else {
216        return;
217    };
218    // N1: never while disconnected or revoked, whatever a stale marker says.
219    // NEW-3: nor with the [cloud] switches off or a lapsed lease.
220    if !store.data_dir().join(ENABLED_FILE).is_file() || !store.may_record() {
221        return;
222    }
223    let config = lean_ctx::core::config::Config::load().cloud.clone();
224    if !config.receipts_upload || !store.recording_allowed(&config) {
225        return;
226    }
227    let Some(key) = ReceiptKey::load_or_create(store.data_dir()) else {
228        return;
229    };
230    // V9: only a Cloud that announced `session_ref` hears the session; an
231    // older one would refuse the whole batch for good.
232    let session = crate::session_ref::announced(&store, crate::session_ref::FEATURE_SESSION_REF)
233        .then(super::policy_sessions::current_session)
234        .flatten();
235    let Some((rcpt, document)) = to_v2(
236        &key,
237        receipt_id,
238        invocation,
239        observation,
240        session.as_deref(),
241    ) else {
242        return;
243    };
244    let Ok(document) = serde_json::to_value(&document) else {
245        return;
246    };
247    // `root` stays in the local outbox: it only selects the vault.
248    let payload = json!({
249        "receipt_id": rcpt.as_str(),
250        "root": root.to_string_lossy(),
251        "created_at": now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
252        "document": document,
253    });
254    let _ = Outbox::at(store.data_dir()).enqueue(CHANNEL_RECEIPTS, payload, now);
255}
256
257/// Why receipts are not sent, or `None` when everything allows them.
258pub(crate) fn blocked_by(
259    released: bool,
260    config: &CloudConfig,
261    lease: &CloudLeaseV1,
262    disabled_under_lease: Option<&str>,
263) -> Option<&'static str> {
264    if !config.receipts_upload {
265        Some("switched off on this instance ([cloud] receipts_upload = false)")
266    } else if !lease.grants(CloudRight::ReceiptsUpload) {
267        Some("the lease does not include receipts.upload (Enterprise)")
268    } else if !lease.org_allows_receipts_upload() {
269        Some("switched off by the workspace")
270    } else if disabled_under_lease == Some(lease.lease_id.as_str()) {
271        Some("switched off by the workspace (LeanCTX Cloud refused the upload)")
272    } else if !released {
273        Some(NOT_RELEASED)
274    } else {
275        None
276    }
277}
278
279/// Receipts v2 follow the engine-metrics release switch (owner go).
280pub(crate) const NOT_RELEASED: &str = "receipts v2 wait for the instance telemetry release";
281
282fn released(origin: &str) -> bool {
283    super::metrics_v2::upload::released(origin)
284}
285
286fn disabled_lease(store: &CloudStore) -> Option<String> {
287    std::fs::read_to_string(store.data_dir().join(DISABLED_FILE))
288        .ok()
289        .map(|text| text.trim().to_string())
290        .filter(|text| !text.is_empty())
291}
292
293/// Owner decision (K2 review 2, N2): receipts fall under the same rule as
294/// engine metrics, "Share instance metrics" — policy off, not confirmed
295/// (Personal), no valid bundle in force or revoked: nothing is
296/// collected or sent.
297pub(crate) const SHARING_OFF: &str =
298    "off under the workspace rule \"Share instance metrics\" (see Instance metrics)";
299
300fn sharing(
301    store: &CloudStore,
302    config: &CloudConfig,
303    instance: &InstanceRecord,
304    lease: &CloudLeaseV1,
305    now: UtcDateTime,
306) -> Sharing {
307    super::metrics_v2::gate::decide(store, config, instance, lease, now)
308}
309
310/// Why receipts are not sent now, for `cloud status` (local only).
311pub fn status(
312    store: &CloudStore,
313    config: &CloudConfig,
314    instance: &InstanceRecord,
315    lease: &CloudLeaseV1,
316) -> Option<&'static str> {
317    // The receipts switches, then the shared rule, then the release.
318    blocked_by(true, config, lease, disabled_lease(store).as_deref())
319        .or_else(|| {
320            (!sharing(store, config, instance, lease, UtcDateTime::now()).is_on())
321                .then_some(SHARING_OFF)
322        })
323        .or_else(|| (!released(&instance.url)).then_some(NOT_RELEASED))
324}
325
326/// Stop everything this engine records for Cloud on this machine (K2
327/// review 2, N1): the engine-metrics buffer, state and switches (secret
328/// hits and K10/K12/K13 signals) and the receipts marker and queue. Called
329/// when the engine disconnects, is revoked, its scheduler stops or Cloud is
330/// disabled; the next connected pass turns recording on again only when
331/// every gate allows it.
332pub(crate) fn stop_local_recording(cloud_data: &Path) {
333    super::metrics_v2::buffer::forget(cloud_data);
334    super::metrics_v2::buffer::note_local_off(cloud_data);
335    stop_receipts(cloud_data);
336}
337
338/// The receipts half: the marker and every queued receipt.
339fn stop_receipts(cloud_data: &Path) {
340    let _ = std::fs::remove_file(cloud_data.join(ENABLED_FILE));
341    let outbox = Outbox::at(cloud_data);
342    for item in outbox.list(CHANNEL_RECEIPTS) {
343        let _ = outbox.remove(&item);
344    }
345}
346
347/// K2 review 3 (NEW-2): `config set` of an `[cloud]` off switch applies at
348/// once. `enabled = false` and `metrics_upload = false` stop everything
349/// (receipts follow the metrics rule, N2); `receipts_upload = false` stops
350/// receipts.
351pub(crate) fn apply_off_switches(config: &CloudConfig) {
352    let Ok(store) = CloudStore::open() else {
353        return;
354    };
355    apply_off_switches_in(store.data_dir(), config);
356}
357
358fn apply_off_switches_in(cloud_data: &Path, config: &CloudConfig) {
359    if config.enabled == Some(false) || !config.metrics_upload {
360        stop_local_recording(cloud_data);
361    } else if !config.receipts_upload {
362        stop_receipts(cloud_data);
363    }
364}
365
366/// Turn queueing on or off to match what allows receipts now; when off,
367/// whatever is queued is dropped (it would never be sent).
368fn set_enabled(store: &CloudStore, outbox: &Outbox, on: bool) -> Result<(), CloudError> {
369    let marker = store.data_dir().join(ENABLED_FILE);
370    if on {
371        if !marker.is_file() {
372            write_private(store.data_dir(), ENABLED_FILE, b"1")?;
373        }
374    } else {
375        let _ = std::fs::remove_file(&marker);
376        for item in outbox.list(CHANNEL_RECEIPTS) {
377            outbox.remove(&item)?;
378        }
379    }
380    Ok(())
381}
382
383/// The Cloud vault id of a checkout Cloud resolved on this machine.
384fn vault_of(map: &VaultMap, root: &str) -> Option<VaultId> {
385    map.vaults
386        .values()
387        .find(|record| record.roots.iter().any(|known| known == root))
388        .and_then(|record| VaultId::new(&record.vault_id))
389}
390
391/// The wire item of a queued receipt, or `None` when it cannot be sent (a
392/// checkout Cloud does not know, or a v1 item queued by an older engine).
393fn wire_item(map: &VaultMap, item: &OutboxItem) -> Option<ReceiptItemV2> {
394    let payload = &item.payload;
395    let document: EngineReceiptV2 = serde_json::from_value(payload["document"].clone()).ok()?;
396    ReceiptItemV2::new(
397        ReceiptIdV2::new(payload["receipt_id"].as_str()?)?,
398        vault_of(map, payload["root"].as_str()?)?,
399        TimeStamp::new(payload["created_at"].as_str()?)?,
400        document,
401    )
402    .ok()
403}
404
405/// Sign a batch with the instance key (as engine metrics).
406pub(crate) fn sign(
407    keys: &InstanceKeys,
408    body: ReceiptsBodyV2,
409) -> Result<ReceiptsRequestV2, CloudError> {
410    let signer = keys.signing_key();
411    let key_id = KeyId::new(&super::workers::key_id(signer))
412        .ok_or_else(|| CloudError::Local("instance key id".into()))?;
413    let input = body
414        .signing_input(&key_id)
415        .map_err(|e| CloudError::Local(e.to_string()))?;
416    let signature = SignatureHex::new(&hex::encode(signer.sign(&input).to_bytes()))
417        .ok_or_else(|| CloudError::Local("signature".into()))?;
418    Ok(body.signed(key_id, signature))
419}
420
421/// Batches of at most 256 items and 1 MiB (signature included).
422fn batches(items: Vec<(ReceiptItemV2, OutboxItem)>) -> Vec<Vec<(ReceiptItemV2, OutboxItem)>> {
423    // `key_id` and `signature` with their JSON framing.
424    const SIGNED_EXTRA: usize = 200;
425    let mut out = Vec::new();
426    let mut current: Vec<(ReceiptItemV2, OutboxItem)> = Vec::new();
427    let mut size = 64usize;
428    for (wire, item) in items {
429        let len = serde_json::to_vec(&wire).map_or(usize::MAX, |v| v.len() + 1);
430        if !current.is_empty()
431            && (current.len() >= MAX_RECEIPTS_V2
432                || size.saturating_add(len) + SIGNED_EXTRA > MAX_RECEIPTS_BODY_BYTES)
433        {
434            out.push(std::mem::take(&mut current));
435            size = 64;
436        }
437        size = size.saturating_add(len);
438        current.push((wire, item));
439    }
440    if !current.is_empty() {
441        out.push(current);
442    }
443    out
444}
445
446/// The same batch always carries the same key, so a retry is idempotent.
447fn idempotency_key(bytes: &[u8]) -> String {
448    use sha2::Digest as _;
449    hex::encode(&Sha256::digest(bytes)[..16])
450}
451
452/// What a receipts run did.
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub enum ReceiptsRun {
455    Off(&'static str),
456    Sent {
457        accepted: u64,
458        duplicates: u64,
459        dropped: u64,
460    },
461}
462
463/// Bring the marker in step with the gates and send what is queued.
464pub fn run(
465    session: &Session,
466    config: &CloudConfig,
467    now: UtcDateTime,
468) -> Result<ReceiptsRun, CloudError> {
469    let store = &session.store;
470    let lease = &session.lease.lease;
471    let outbox = Outbox::at(store.data_dir());
472    let mut refused = disabled_lease(store);
473    // A newer lease that allows receipts lifts an earlier refusal.
474    if refused
475        .as_deref()
476        .is_some_and(|id| id != lease.lease_id && lease.org_allows_receipts_upload())
477    {
478        let _ = std::fs::remove_file(store.data_dir().join(DISABLED_FILE));
479        refused = None;
480    }
481    if let Some(reason) = blocked_by(true, config, lease, refused.as_deref()) {
482        set_enabled(store, &outbox, false)?;
483        return Ok(ReceiptsRun::Off(reason));
484    }
485    let Sharing::On {
486        vaults_off, since, ..
487    } = sharing(store, config, &session.instance, lease, now)
488    else {
489        set_enabled(store, &outbox, false)?;
490        return Ok(ReceiptsRun::Off(SHARING_OFF));
491    };
492    if !released(&session.instance.url) {
493        set_enabled(store, &outbox, false)?;
494        return Ok(ReceiptsRun::Off(NOT_RELEASED));
495    }
496    set_enabled(store, &outbox, true)?;
497    let map = VaultMap::load(store.data_dir());
498    let (mut accepted, mut duplicates, mut dropped) = (0u64, 0u64, 0u64);
499    let mut ready = Vec::new();
500    for item in outbox
501        .list(CHANNEL_RECEIPTS)
502        .into_iter()
503        .filter(|item| item.due(now))
504    {
505        // Nothing from before the sharing period, nothing of a vault whose
506        // own policy turns the rule off.
507        let allowed = |wire: &ReceiptItemV2| {
508            since.is_none_or(|since| wire.created_at.at() >= since)
509                && !vaults_off.contains(wire.vault_id.as_str())
510        };
511        if let Some(wire) = wire_item(&map, &item).filter(allowed) {
512            ready.push((wire, item));
513        } else {
514            outbox.remove(&item)?;
515            dropped += 1;
516        }
517    }
518    if ready.is_empty() {
519        return Ok(ReceiptsRun::Sent {
520            accepted,
521            duplicates,
522            dropped,
523        });
524    }
525    let keys = InstanceKeys::load(store)?;
526    for batch in batches(ready) {
527        let (wires, sent): (Vec<ReceiptItemV2>, Vec<OutboxItem>) = batch.into_iter().unzip();
528        let body = ReceiptsBodyV2 {
529            schema: ReceiptsSchema,
530            receipts: wires,
531        };
532        if body.validate().is_err() {
533            // Malformed (a duplicate id): Cloud would refuse the batch as a
534            // whole, so it is dropped rather than retried forever.
535            for item in &sent {
536                outbox.remove(item)?;
537                dropped += 1;
538            }
539            continue;
540        }
541        let request = sign(&keys, body)?;
542        let bytes = serde_json::to_vec(&request).map_err(|e| CloudError::Local(e.to_string()))?;
543        let wire: Value =
544            serde_json::from_slice(&bytes).map_err(|e| CloudError::Local(e.to_string()))?;
545        let key = idempotency_key(&bytes);
546        match session.with_client(|client| client.post_idempotent(RECEIPTS_ROUTE, &wire, &key)) {
547            Ok(answer) => {
548                let ack: ReceiptsAckV2 = serde_json::from_value(answer)
549                    .map_err(|e| CloudError::Protocol(format!("receipts ack: {e}")))?;
550                accepted += u64::from(ack.accepted);
551                duplicates += u64::from(ack.duplicates);
552                for item in &sent {
553                    outbox.remove(item)?;
554                }
555            }
556            Err(CloudError::UploadDisabled(
557                CloudUploadKind::Receipts | CloudUploadKind::Unknown,
558            )) => {
559                write_private(store.data_dir(), DISABLED_FILE, lease.lease_id.as_bytes())?;
560                set_enabled(store, &outbox, false)?;
561                return Ok(ReceiptsRun::Off(
562                    "switched off by the workspace (LeanCTX Cloud refused the upload)",
563                ));
564            }
565            Err(error) if error.is_transient() => {
566                // 429: Retry-After / retry_after_s, or a quota's reset_at.
567                let retry_after = error.retry_after_at(lean_ctx_time::UtcDateTime::now());
568                for item in &sent {
569                    let mut item = item.clone();
570                    outbox.retry_later(&mut item, &error.to_string(), retry_after, now)?;
571                }
572                return Err(error);
573            }
574            Err(error) => {
575                for item in &sent {
576                    let mut item = item.clone();
577                    outbox.fail(&mut item, &error.to_string())?;
578                }
579                return Err(error);
580            }
581        }
582    }
583    Ok(ReceiptsRun::Sent {
584        accepted,
585        duplicates,
586        dropped,
587    })
588}
589
590#[cfg(test)]
591#[path = "receipts_tests.rs"]
592mod tests;