1use super::{map_err, SqlNoteStore};
3use crate::pool::ConnectionPool;
4use khive_storage::{SqlStatement, SqlValue, StorageCapability, StorageError, StorageResult};
5use rusqlite::{params, OptionalExtension};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::sync::Arc;
9use uuid::Uuid;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct EnvelopeKey {
13 pub logical_message_id: Uuid,
14 pub recipient_device_id: Uuid,
15 pub recipient_key_epoch: u64,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21pub struct SenderEnvelope {
22 pub namespace: String,
23 pub logical_message_id: Uuid,
24 pub outbound_note_id: Uuid,
25 pub kind: String,
26 pub slug: String,
27 pub credential_ref: String,
28 pub recipient_address: String,
29 pub protocol_version: u32,
30 pub sender_agent_id: String,
31 pub sender_assurance: SenderAssurance,
32 pub recipient_agent_id: String,
33 pub recipient_device_id: Uuid,
34 pub recipient_key_epoch: u64,
35 pub contact_generation: u64,
36 pub sender_key_epoch: u64,
37 pub recipient_key_fingerprint: String,
38 pub enc: Vec<u8>,
39 pub ciphertext: Vec<u8>,
40}
41impl SenderEnvelope {
42 pub fn key(&self) -> EnvelopeKey {
43 EnvelopeKey {
44 logical_message_id: self.logical_message_id,
45 recipient_device_id: self.recipient_device_id,
46 recipient_key_epoch: self.recipient_key_epoch,
47 }
48 }
49 pub fn validate(&self) -> StorageResult<()> {
50 for id in [&self.sender_agent_id, &self.recipient_agent_id] {
51 if Uuid::parse_str(id).ok().map(|id| id.to_string()).as_deref() != Some(id.as_str()) {
52 return Err(invalid("agent id must be a canonical UUID"));
53 }
54 }
55 if self.enc.len() != 32 || self.ciphertext.len() > 65_536 {
56 return Err(invalid("invalid envelope byte lengths"));
57 }
58 if [
59 self.recipient_key_epoch,
60 self.sender_key_epoch,
61 self.contact_generation,
62 ]
63 .iter()
64 .any(|n| *n == 0 || *n > u32::MAX as u64)
65 {
66 return Err(invalid("epoch/generation outside supported range"));
67 }
68 if self.protocol_version != 1
69 || self.kind.is_empty()
70 || self.slug.is_empty()
71 || self.credential_ref.is_empty()
72 {
73 return Err(invalid("invalid transport identity"));
74 }
75 if self.recipient_key_fingerprint.len() != 64
76 || !khive_types::is_lowercase_hex(&self.recipient_key_fingerprint)
77 {
78 return Err(invalid("fingerprint must be 32 lowercase hex bytes"));
79 }
80 Ok(())
81 }
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum SenderAssurance {
88 Claimed,
89 DaemonBearer,
90 ActorSignature,
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "snake_case")]
95pub enum TransportState {
96 Pending,
97 RecipientStored,
98 RecipientQuarantined,
99 Failed,
100}
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum FailureClass {
104 Transient,
105 Authentication,
106 Permanent,
107}
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum HoldReason {
111 InsufficientCredit,
112 RecipientKeyChanged,
113 PolicyDenied {
115 mode: PolicyMode,
116 revision: u64,
117 },
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "snake_case")]
123pub enum PolicyMode {
124 Off,
125 Shadow,
126 Enforce,
127}
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct SenderRecord {
130 pub envelope: SenderEnvelope,
131 pub state: TransportState,
132 pub attempt_count: u64,
133 pub envelope_seq: u64,
134 pub next_retry_at: Option<i64>,
135 pub last_failure_class: Option<FailureClass>,
136 pub hold_reason: Option<HoldReason>,
137 pub receipt: Option<Value>,
138 pub created_at: i64,
139 pub updated_at: i64,
140 pub admitted_at: Option<i64>,
141}
142
143fn invalid(message: &str) -> StorageError {
144 StorageError::InvalidInput {
145 capability: StorageCapability::Notes,
146 operation: "sender_transport".into(),
147 message: message.into(),
148 }
149}
150trait StorageSpelling {
151 fn storage_spelling(&self) -> &'static str;
152}
153impl StorageSpelling for SenderAssurance {
154 fn storage_spelling(&self) -> &'static str {
155 match self {
156 Self::Claimed => "claimed",
157 Self::DaemonBearer => "daemon_bearer",
158 Self::ActorSignature => "actor_signature",
159 }
160 }
161}
162impl StorageSpelling for TransportState {
163 fn storage_spelling(&self) -> &'static str {
164 match self {
165 Self::Pending => "pending",
166 Self::RecipientStored => "recipient_stored",
167 Self::RecipientQuarantined => "recipient_quarantined",
168 Self::Failed => "failed",
169 }
170 }
171}
172impl StorageSpelling for FailureClass {
173 fn storage_spelling(&self) -> &'static str {
174 match self {
175 Self::Transient => "transient",
176 Self::Authentication => "authentication",
177 Self::Permanent => "permanent",
178 }
179 }
180}
181impl StorageSpelling for HoldReason {
182 fn storage_spelling(&self) -> &'static str {
183 match self {
184 Self::InsufficientCredit => "insufficient_credit",
185 Self::RecipientKeyChanged => "recipient_key_changed",
186 Self::PolicyDenied { .. } => "policy_denied",
187 }
188 }
189}
190impl StorageSpelling for PolicyMode {
191 fn storage_spelling(&self) -> &'static str {
192 match self {
193 Self::Off => "off",
194 Self::Shadow => "shadow",
195 Self::Enforce => "enforce",
196 }
197 }
198}
199fn encode(value: &impl StorageSpelling) -> &'static str {
200 value.storage_spelling()
201}
202fn decode<T: serde::de::DeserializeOwned>(value: String) -> rusqlite::Result<T> {
203 serde_json::from_value(Value::String(value)).map_err(|e| {
204 rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e))
205 })
206}
207fn uuid(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
208 Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|e| {
209 rusqlite::Error::FromSqlConversionFailure(index, rusqlite::types::Type::Text, Box::new(e))
210 })
211}
212const COLUMNS: &str = concat!(
213 "namespace, logical_message_id, outbound_note_id, kind, slug, credential_ref, ",
214 "recipient_address, protocol_version, sender_agent_id, recipient_agent_id, ",
215 "recipient_device_id, recipient_key_epoch, contact_generation, sender_key_epoch, ",
216 "recipient_key_fingerprint, enc, ciphertext, state, attempt_count, next_retry_at, ",
217 "last_failure_class, hold_reason, receipt, created_at, updated_at, envelope_seq, ",
218 "policy_mode, policy_revision, sender_assurance, admitted_at",
219);
220fn unsigned_column(value: i64, index: usize) -> rusqlite::Result<u64> {
221 u64::try_from(value).map_err(|error| {
222 rusqlite::Error::FromSqlConversionFailure(
223 index,
224 rusqlite::types::Type::Integer,
225 Box::new(error),
226 )
227 })
228}
229fn read_unsigned(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<u64> {
230 unsigned_column(row.get(index)?, index)
231}
232fn read_optional_unsigned(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<Option<u64>> {
233 row.get::<_, Option<i64>>(index)?
234 .map(|value| unsigned_column(value, index))
235 .transpose()
236}
237fn sql_integer(value: u64) -> StorageResult<i64> {
238 i64::try_from(value)
239 .map_err(|_| invalid("unsigned transport value exceeds SQLite integer range"))
240}
241pub const SENDER_TRANSPORT_INSERT_LABEL: &str = "sender-transport-insert";
244
245pub fn sender_envelope_insert_statement(envelope: &SenderEnvelope) -> StorageResult<SqlStatement> {
252 envelope.validate()?;
253 let now = chrono::Utc::now().timestamp_micros();
254 Ok(SqlStatement::new(
255 INSERT_SQL,
256 vec![
257 SqlValue::Text(envelope.namespace.clone()),
258 SqlValue::Text(envelope.logical_message_id.to_string()),
259 SqlValue::Text(envelope.outbound_note_id.to_string()),
260 SqlValue::Text(envelope.kind.clone()),
261 SqlValue::Text(envelope.slug.clone()),
262 SqlValue::Text(envelope.credential_ref.clone()),
263 SqlValue::Text(envelope.recipient_address.clone()),
264 SqlValue::Integer(i64::from(envelope.protocol_version)),
265 SqlValue::Text(envelope.sender_agent_id.clone()),
266 SqlValue::Text(envelope.recipient_agent_id.clone()),
267 SqlValue::Text(envelope.recipient_device_id.to_string()),
268 SqlValue::Integer(sql_integer(envelope.recipient_key_epoch)?),
269 SqlValue::Integer(sql_integer(envelope.contact_generation)?),
270 SqlValue::Integer(sql_integer(envelope.sender_key_epoch)?),
271 SqlValue::Text(envelope.recipient_key_fingerprint.clone()),
272 SqlValue::Blob(envelope.enc.clone()),
273 SqlValue::Blob(envelope.ciphertext.clone()),
274 SqlValue::Integer(now),
275 SqlValue::Integer(1),
276 SqlValue::Text(encode(&envelope.sender_assurance).to_string()),
277 ],
278 )
279 .labelled(SENDER_TRANSPORT_INSERT_LABEL))
280}
281fn read_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SenderRecord> {
282 Ok(SenderRecord {
283 envelope: SenderEnvelope {
284 namespace: row.get(0)?,
285 logical_message_id: uuid(row, 1)?,
286 outbound_note_id: uuid(row, 2)?,
287 kind: row.get(3)?,
288 slug: row.get(4)?,
289 credential_ref: row.get(5)?,
290 recipient_address: row.get(6)?,
291 protocol_version: row.get(7)?,
292 sender_agent_id: row.get(8)?,
293 sender_assurance: decode(row.get(28)?)?,
294 recipient_agent_id: row.get(9)?,
295 recipient_device_id: uuid(row, 10)?,
296 recipient_key_epoch: read_unsigned(row, 11)?,
297 contact_generation: read_unsigned(row, 12)?,
298 sender_key_epoch: read_unsigned(row, 13)?,
299 recipient_key_fingerprint: row.get(14)?,
300 enc: row.get(15)?,
301 ciphertext: row.get(16)?,
302 },
303 state: decode(row.get(17)?)?,
304 attempt_count: read_unsigned(row, 18)?,
305 next_retry_at: row.get(19)?,
306 last_failure_class: row.get::<_, Option<String>>(20)?.map(decode).transpose()?,
307 hold_reason: match row.get::<_, Option<String>>(21)?.as_deref() {
308 Some("policy_denied") => Some(HoldReason::PolicyDenied {
309 mode: decode(row.get(26)?)?,
310 revision: read_unsigned(row, 27)?,
311 }),
312 reason => reason.map(|r| decode(r.to_owned())).transpose()?,
313 },
314 receipt: row
315 .get::<_, Option<String>>(22)?
316 .map(|s| {
317 serde_json::from_str(&s).map_err(|e| {
318 rusqlite::Error::FromSqlConversionFailure(
319 22,
320 rusqlite::types::Type::Text,
321 Box::new(e),
322 )
323 })
324 })
325 .transpose()?,
326 envelope_seq: read_unsigned(row, 25)?,
327 created_at: row.get(23)?,
328 updated_at: row.get(24)?,
329 admitted_at: row.get(29)?,
330 })
331}
332fn load(conn: &rusqlite::Connection, key: EnvelopeKey) -> rusqlite::Result<Option<SenderRecord>> {
333 let epoch = i64::try_from(key.recipient_key_epoch)
334 .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
335 conn.query_row(
336 &LOAD_SQL.replace("{COLUMNS}", COLUMNS),
337 params![
338 key.logical_message_id.to_string(),
339 key.recipient_device_id.to_string(),
340 epoch
341 ],
342 read_row,
343 )
344 .optional()
345}
346
347const LOAD_SQL: &str = concat!(
348 "SELECT {COLUMNS} FROM comm_sender_transport WHERE logical_message_id=?1 AND ",
349 "recipient_device_id=?2 AND recipient_key_epoch=?3",
350);
351
352const TERMINAL_SQL: &str = include_str!("../../../../sql/comm-sender-receipt-exists.sql");
353
354const PRIOR_SQL: &str = concat!(
355 "SELECT {COLUMNS} FROM comm_sender_transport WHERE logical_message_id=?1 ORDER BY ",
356 "envelope_seq DESC LIMIT 1",
357);
358
359const DEVICE_EPOCH_SQL: &str =
360 include_str!("../../../../sql/comm-sender-device-key-epoch-max-select.sql");
361
362const INSERT_SQL: &str = include_str!("../../../../sql/comm-sender-envelope-insert.sql");
363
364const PENDING_SQL: &str = concat!(
365 "SELECT {COLUMNS} FROM comm_sender_transport AS t WHERE namespace=?1 AND kind=?2 ",
366 "AND slug=?3 AND state='pending' AND hold_reason IS NULL AND (next_retry_at IS ",
367 "NULL OR next_retry_at<=?4) AND NOT EXISTS(SELECT 1 FROM comm_sender_transport AS ",
368 "done WHERE done.logical_message_id=t.logical_message_id AND done.receipt IS NOT ",
369 "NULL) AND envelope_seq=(SELECT MAX(envelope_seq) FROM comm_sender_transport ",
370 "WHERE logical_message_id=t.logical_message_id) ORDER BY ",
371 "created_at,logical_message_id LIMIT ?5",
372);
373
374const FAILURE_SQL: &str = include_str!("../../../../sql/comm-sender-failure-update.sql");
375
376const ADMISSION_SQL: &str = include_str!("../../../../sql/comm-sender-admission-update.sql");
377
378const HOLD_SQL: &str = include_str!("../../../../sql/comm-sender-hold-update.sql");
379
380const RECEIPT_SQL: &str = include_str!("../../../../sql/comm-sender-receipt-update.sql");
381
382pub struct SenderTransportStore {
384 notes: SqlNoteStore,
385}
386impl SenderTransportStore {
387 pub fn new(pool: Arc<ConnectionPool>) -> Self {
388 Self {
389 notes: SqlNoteStore::new(pool, false),
390 }
391 }
392 pub async fn get(&self, key: EnvelopeKey) -> StorageResult<Option<SenderRecord>> {
393 self.notes
394 .with_reader("sender_transport_get", move |conn| load(conn, key))
395 .await
396 }
397 pub async fn get_by_outbound_note_id(
400 &self,
401 namespace: &str,
402 outbound_note_id: Uuid,
403 ) -> StorageResult<Option<SenderRecord>> {
404 let namespace = namespace.to_owned();
405 self.notes
406 .with_reader("sender_transport_status", move |conn| {
407 conn.query_row(
408 &format!(
409 "SELECT {COLUMNS} FROM comm_sender_transport \
410 WHERE namespace = ?1 AND outbound_note_id = ?2 \
411 ORDER BY (receipt IS NOT NULL) DESC, envelope_seq DESC LIMIT 1"
412 ),
413 params![namespace, outbound_note_id.to_string()],
414 read_row,
415 )
416 .optional()
417 })
418 .await
419 }
420 pub async fn current_by_logical_id(
424 &self,
425 namespace: &str,
426 kind: &str,
427 slug: &str,
428 logical_id: Uuid,
429 ) -> StorageResult<Option<SenderRecord>> {
430 let namespace = namespace.to_owned();
431 let kind = kind.to_owned();
432 let slug = slug.to_owned();
433 self.notes
434 .with_reader("sender_transport_current", move |conn| {
435 conn.query_row(
436 &format!(
437 "SELECT {COLUMNS} FROM comm_sender_transport \
438 WHERE namespace = ?1 AND kind = ?2 AND slug = ?3 \
439 AND logical_message_id = ?4 \
440 ORDER BY envelope_seq DESC LIMIT 1"
441 ),
442 params![namespace, kind, slug, logical_id.to_string()],
443 read_row,
444 )
445 .optional()
446 })
447 .await
448 }
449 pub async fn create(
452 &self,
453 envelope: SenderEnvelope,
454 confirmed_key_change: bool,
455 ) -> StorageResult<SenderRecord> {
456 envelope.validate()?;
457 self.notes
458 .with_writer_tx_storage("sender_transport_create", move |conn| {
459 let op = "sender_transport_create";
460 if let Some(existing) = load(conn, envelope.key()).map_err(|e| map_err(e, op))? {
461 if confirmed_key_change {
462 return Err(invalid(
463 "confirmed re-encryption requires a new key identity",
464 ));
465 }
466 if existing.envelope != envelope {
467 return Err(invalid("envelope_conflict"));
468 }
469 return Ok(existing);
470 }
471 let terminal: bool = conn
472 .query_row(
473 TERMINAL_SQL,
474 [envelope.logical_message_id.to_string()],
475 |row| row.get(0),
476 )
477 .map_err(|e| map_err(e, op))?;
478 if terminal {
479 return Err(invalid("logical message already has a recipient receipt"));
480 }
481 let prior = conn
482 .query_row(
483 &PRIOR_SQL.replace("{COLUMNS}", COLUMNS),
484 [envelope.logical_message_id.to_string()],
485 read_row,
486 )
487 .optional()
488 .map_err(|e| map_err(e, op))?;
489 let envelope_seq = if let Some(prior) = prior {
490 if !confirmed_key_change
491 || prior.state != TransportState::Pending
492 || prior.hold_reason != Some(HoldReason::RecipientKeyChanged)
493 {
494 return Err(invalid(
495 "new envelope requires confirmed recipient key change",
496 ));
497 }
498 let previous_epoch: Option<u64> = conn
499 .query_row(
500 DEVICE_EPOCH_SQL,
501 params![
502 envelope.logical_message_id.to_string(),
503 envelope.recipient_device_id.to_string()
504 ],
505 |row| read_optional_unsigned(row, 0),
506 )
507 .map_err(|e| map_err(e, op))?;
508 if previous_epoch.is_some_and(|epoch| envelope.recipient_key_epoch <= epoch) {
509 return Err(invalid("same device key epoch must increase"));
510 }
511 let a = &prior.envelope;
512 let b = &envelope;
513 if a.sender_assurance != b.sender_assurance {
514 return Err(invalid("sender_assurance_conflict"));
515 }
516 if a.namespace != b.namespace
517 || a.outbound_note_id != b.outbound_note_id
518 || a.kind != b.kind
519 || a.slug != b.slug
520 || a.sender_agent_id != b.sender_agent_id
521 || a.sender_key_epoch != b.sender_key_epoch
522 || a.recipient_agent_id != b.recipient_agent_id
523 || a.recipient_address != b.recipient_address
524 {
525 return Err(invalid("logical message identity cannot change"));
526 }
527 prior
528 .envelope_seq
529 .checked_add(1)
530 .filter(|seq| *seq <= i64::MAX as u64)
531 .ok_or_else(|| invalid("envelope sequence exhausted"))?
532 } else {
533 if confirmed_key_change {
534 return Err(invalid("no prior envelope to re-encrypt"));
535 }
536 1
537 };
538 let now = chrono::Utc::now().timestamp_micros();
539 conn.execute(
540 INSERT_SQL,
541 params![
542 envelope.namespace,
543 envelope.logical_message_id.to_string(),
544 envelope.outbound_note_id.to_string(),
545 envelope.kind,
546 envelope.slug,
547 envelope.credential_ref,
548 envelope.recipient_address,
549 envelope.protocol_version,
550 envelope.sender_agent_id,
551 envelope.recipient_agent_id,
552 envelope.recipient_device_id.to_string(),
553 sql_integer(envelope.recipient_key_epoch)?,
554 sql_integer(envelope.contact_generation)?,
555 sql_integer(envelope.sender_key_epoch)?,
556 envelope.recipient_key_fingerprint,
557 envelope.enc,
558 envelope.ciphertext,
559 now,
560 sql_integer(envelope_seq)?,
561 encode(&envelope.sender_assurance)
562 ],
563 )
564 .map_err(|e| map_err(e, op))?;
565 load(conn, envelope.key())
566 .map_err(|e| map_err(e, op))?
567 .ok_or_else(|| invalid("inserted record disappeared"))
568 })
569 .await
570 }
571 pub async fn list_pending(
574 &self,
575 namespace: &str,
576 kind: &str,
577 slug: &str,
578 now: i64,
579 limit: u32,
580 ) -> StorageResult<Vec<SenderRecord>> {
581 let (namespace, kind, slug) = (namespace.to_owned(), kind.to_owned(), slug.to_owned());
582 self.notes
583 .with_reader("sender_transport_pending", move |conn| {
584 let mut stmt = conn.prepare(&PENDING_SQL.replace("{COLUMNS}", COLUMNS))?;
585 let rows = stmt
586 .query_map(
587 params![namespace, kind, slug, now, limit.min(1000)],
588 read_row,
589 )?
590 .collect();
591 rows
592 })
593 .await
594 }
595 pub async fn record_failure(
598 &self,
599 key: EnvelopeKey,
600 class: FailureClass,
601 next_retry_at: Option<i64>,
602 ) -> StorageResult<()> {
603 self.notes
604 .with_writer_tx_storage("sender_transport_failure", move |conn| {
605 let op = "sender_transport_failure";
606 let row = load(conn, key)
607 .map_err(|e| map_err(e, op))?
608 .ok_or_else(|| invalid("unknown sender record"))?;
609 if row.state != TransportState::Pending {
610 return Err(invalid("sender record is not pending"));
611 }
612 if row.hold_reason.is_some() {
613 return Err(invalid("sender record is held"));
614 }
615 let state = if class == FailureClass::Permanent {
616 TransportState::Failed
617 } else {
618 TransportState::Pending
619 };
620 let attempts = if class == FailureClass::Authentication {
621 row.attempt_count
622 } else {
623 row.attempt_count.saturating_add(1).min(i64::MAX as u64)
624 };
625 let retry = if class == FailureClass::Transient {
626 next_retry_at
627 } else {
628 None
629 };
630 conn.execute(
631 FAILURE_SQL,
632 params![
633 key.logical_message_id.to_string(),
634 key.recipient_device_id.to_string(),
635 sql_integer(key.recipient_key_epoch)?,
636 encode(&state),
637 sql_integer(attempts)?,
638 retry,
639 encode(&class),
640 chrono::Utc::now().timestamp_micros()
641 ],
642 )
643 .map_err(|e| map_err(e, op))?;
644 Ok(())
645 })
646 .await
647 }
648 pub async fn record_admission(&self, key: EnvelopeKey, admitted_at: i64) -> StorageResult<()> {
651 self.notes
652 .with_writer_tx_storage("sender_transport_admission", move |conn| {
653 let op = "sender_transport_admission";
654 let row = load(conn, key)
655 .map_err(|e| map_err(e, op))?
656 .ok_or_else(|| invalid("unknown sender record"))?;
657 if row.state != TransportState::Pending {
658 return Err(invalid("sender record is not pending"));
659 }
660 if row.hold_reason.is_some() {
661 return Err(invalid("sender record is held"));
662 }
663 let next_retry_at = admitted_at
664 .checked_add(600_000_000)
665 .ok_or_else(|| invalid("admission deadline exceeds SQLite integer range"))?;
666 conn.execute(
667 ADMISSION_SQL,
668 params![
669 key.logical_message_id.to_string(),
670 key.recipient_device_id.to_string(),
671 sql_integer(key.recipient_key_epoch)?,
672 admitted_at,
673 next_retry_at,
674 chrono::Utc::now().timestamp_micros()
675 ],
676 )
677 .map_err(|e| map_err(e, op))?;
678 Ok(())
679 })
680 .await
681 }
682 pub async fn hold(&self, key: EnvelopeKey, reason: Option<HoldReason>) -> StorageResult<()> {
686 self.notes
687 .with_writer_tx_storage("sender_transport_hold", move |conn| {
688 let op = "sender_transport_hold";
689 let row = load(conn, key)
690 .map_err(|e| map_err(e, op))?
691 .ok_or_else(|| invalid("unknown sender record"))?;
692 if row.state != TransportState::Pending {
693 return Err(invalid("sender record is not pending"));
694 }
695 if row.hold_reason == Some(HoldReason::RecipientKeyChanged)
696 && reason != Some(HoldReason::RecipientKeyChanged)
697 {
698 return Err(invalid("key change requires confirmed re-encryption"));
699 }
700 let (policy_mode, policy_revision) = match reason {
701 Some(HoldReason::PolicyDenied { mode, revision }) => {
702 (Some(encode(&mode)), Some(sql_integer(revision)?))
703 }
704 _ => (None, None),
705 };
706 conn.execute(
707 HOLD_SQL,
708 params![
709 key.logical_message_id.to_string(),
710 key.recipient_device_id.to_string(),
711 sql_integer(key.recipient_key_epoch)?,
712 reason.map(|r| encode(&r)),
713 chrono::Utc::now().timestamp_micros(),
714 policy_mode,
715 policy_revision
716 ],
717 )
718 .map_err(|e| map_err(e, op))?;
719 Ok(())
720 })
721 .await
722 }
723 pub async fn accept_receipt(
726 &self,
727 key: EnvelopeKey,
728 state: TransportState,
729 receipt: Value,
730 ) -> StorageResult<()> {
731 self.notes
732 .with_writer_tx_storage("sender_transport_receipt", move |conn| {
733 let op = "sender_transport_receipt";
734 let row = load(conn, key)
735 .map_err(|e| map_err(e, op))?
736 .ok_or_else(|| invalid("unknown sender record"))?;
737 let disposition = match state {
738 TransportState::RecipientStored => "stored",
739 TransportState::RecipientQuarantined => "quarantined",
740 _ => return Err(invalid("receipt target is not a recipient outcome")),
741 };
742 if receipt.get("disposition").and_then(Value::as_str) != Some(disposition) {
743 return Err(invalid("receipt disposition mismatch"));
744 }
745 let binding = receipt
746 .get("binding")
747 .ok_or_else(|| invalid("missing receipt binding"))?;
748 let e = &row.envelope;
749 let expected = [
750 ("protocol_version", serde_json::json!(e.protocol_version)),
751 (
752 "logical_message_id",
753 serde_json::json!(e.logical_message_id),
754 ),
755 ("sender_agent_id", serde_json::json!(e.sender_agent_id)),
756 (
757 "recipient_agent_id",
758 serde_json::json!(e.recipient_agent_id),
759 ),
760 (
761 "recipient_device_id",
762 serde_json::json!(e.recipient_device_id),
763 ),
764 (
765 "recipient_key_epoch",
766 serde_json::json!(e.recipient_key_epoch),
767 ),
768 (
769 "contact_generation",
770 serde_json::json!(e.contact_generation),
771 ),
772 ];
773 for (field, value) in expected {
774 if binding.get(field) != Some(&value) {
775 return Err(invalid("receipt binding mismatch"));
776 }
777 }
778 let attempt = binding
779 .get("delivery_attempt_id")
780 .and_then(Value::as_str)
781 .ok_or_else(|| invalid("missing delivery attempt"))?;
782 if Uuid::parse_str(attempt)
783 .ok()
784 .map(|id| id.to_string())
785 .as_deref()
786 != Some(attempt)
787 {
788 return Err(invalid("invalid delivery attempt"));
789 }
790 if let Some(accepted) = row.receipt {
791 if accepted != receipt || row.state != state {
792 return Err(invalid("receipt_conflict"));
793 }
794 return Ok(());
795 }
796 conn.execute(
797 RECEIPT_SQL,
798 params![
799 key.logical_message_id.to_string(),
800 key.recipient_device_id.to_string(),
801 sql_integer(key.recipient_key_epoch)?,
802 encode(&state),
803 receipt.to_string(),
804 chrono::Utc::now().timestamp_micros()
805 ],
806 )
807 .map_err(|e| map_err(e, op))?;
808 Ok(())
809 })
810 .await
811 }
812}
813#[cfg(test)]
814mod source_tests;
815#[cfg(test)]
816mod tests;