reliar_outbox/enqueue.rs
1//! The enqueue capability an application calls directly, in its own transaction (ADR 0036
2//! amendment B): there is no facade type between the caller and the store.
3
4use reliar_core::{Classify, Envelope, Message, MessageId};
5
6/// Enqueuing a typed message in the caller's own transaction. A provider (`PostgresOutboxStore`)
7/// implements this directly, alongside [`crate::OutboxStore`]; there is no separate handle type
8/// to construct.
9///
10/// `Tx` is the provider's transaction type: `sqlx::Transaction<'_, Postgres>` for
11/// `reliar-store-postgres`. It is a **type parameter** precisely so this crate names no storage
12/// type, and one implementor may support several.
13///
14/// Deliberately **not** a method on [`crate::OutboxStore`]: enqueuing takes a transaction handle
15/// the claim side never sees, `OutboxStore` is already published, and a GAT `type Tx<'a>` would
16/// have to spell `&'a mut Transaction<'c, _>` and reintroduce an invariance problem.
17///
18/// **Two methods, one call each** (ADR 0037 amendment A): a required
19/// [`Self::enqueue_envelope`] that every implementor writes, and a provided [`Self::enqueue`] —
20/// the fire-and-forget spelling — built on top of it. An earlier shape tried an `impl
21/// Into<Envelope<T>>` parameter so one method covered both a bare `T: Message` and an
22/// already-built `Envelope<T>`; that was rejected in favor of a second, explicit method instead
23/// — no inference trick, no `Envelope<T>: !Message` invariant to guard.
24///
25/// **One serialized twin, deliberately absent** (ADR 0036 amendment B.10): a
26/// `enqueue_serialized(&mut tx, &SerializedEnvelope)` existed briefly and was cut for having no
27/// production caller; re-adding it is additive.
28///
29/// Renamed from `OutboxStaging` in 0.4.0; `stage` became `enqueue`, and the facade
30/// `OutboxPublisher` that briefly wrapped it (0.4.0, never released) was withdrawn before
31/// shipping in favor of calling this trait directly.
32///
33/// A provider implements the trait, then a caller enqueues in its own transaction. This crate
34/// constructs no store of its own (ADR 0043), so the shape below is a compiled generic call,
35/// never invoked — `reliar-store-postgres`'s own rustdoc has the runnable version over
36/// `PgPool::connect`.
37///
38/// ```
39/// use reliar_core::Message;
40/// use reliar_outbox::OutboxEnqueue;
41///
42/// # #[derive(serde::Serialize, serde::Deserialize)]
43/// # struct OrderCreated;
44/// # impl Message for OrderCreated {
45/// # const TYPE: &'static str = "orders.created";
46/// # const VERSION: u16 = 1;
47/// # }
48/// async fn enqueue_order<S, Tx>(store: &S, tx: &mut Tx) -> Result<(), S::Error>
49/// where
50/// S: OutboxEnqueue<Tx>,
51/// {
52/// store.enqueue(tx, OrderCreated).await?;
53/// Ok(())
54/// }
55/// ```
56pub trait OutboxEnqueue<Tx>: Send + Sync {
57 /// What enqueuing fails with.
58 type Error: std::error::Error + Send + Sync + 'static + Classify;
59
60 /// Serializes `envelope`'s body with **this implementor's own** configured `Serializer` and
61 /// enqueues it in `tx`. Writes the serializer's own `content_type`.
62 ///
63 /// The **propagating** spelling: use it when an id must carry over from an inbound request
64 /// — conversation, correlation, causation, tenant, trace, headers — via
65 /// [`Envelope::builder`](reliar_core::Envelope::builder).
66 ///
67 /// ```
68 /// use reliar_core::{ConversationId, Envelope, Message};
69 /// use reliar_outbox::OutboxEnqueue;
70 ///
71 /// # #[derive(serde::Serialize, serde::Deserialize)]
72 /// # struct OrderCreated;
73 /// # impl Message for OrderCreated {
74 /// # const TYPE: &'static str = "orders.created";
75 /// # const VERSION: u16 = 1;
76 /// # }
77 /// async fn propagate_conversation<S, Tx>(
78 /// store: &S,
79 /// tx: &mut Tx,
80 /// conversation: ConversationId,
81 /// ) -> Result<(), S::Error>
82 /// where
83 /// S: OutboxEnqueue<Tx>,
84 /// {
85 /// let envelope = Envelope::builder(OrderCreated).conversation(conversation).build();
86 /// store.enqueue_envelope(tx, envelope).await?;
87 /// Ok(())
88 /// }
89 /// ```
90 ///
91 /// Returns the id written, for the caller's own use — e.g. as a *next* message's
92 /// `causation_id` in the same transaction. The envelope already carries its `id`; this is not
93 /// how a caller learns it, only a convenience.
94 ///
95 /// **Implementors:** the trait bounds neither `T` nor `Tx` on `Send`, so a plain `async fn`
96 /// that carries `envelope: Envelope<T>` (or `tx`) across an `.await` will not satisfy this
97 /// method's `+ Send` return bound. Serialize (or otherwise consume) `T` synchronously, before
98 /// the async block is built — see `PostgresOutboxStore::enqueue_envelope`'s `//` comment in
99 /// `reliar-store-postgres` for the reference shape and the full argument.
100 ///
101 /// The implementation SHALL issue no network I/O other than the statement itself, and SHALL
102 /// NOT commit, roll back or otherwise consume `tx` — the caller owns it.
103 ///
104 /// # Errors
105 ///
106 /// Provider-defined. An `Err` **MAY** leave `tx` unusable, and whether it does is the
107 /// provider's contract — every implementor documents which. The portable rule a caller can
108 /// rely on is therefore: treat any enqueue error as *abort this transaction* — issue no
109 /// further statement on `tx`, roll it back, and consider every earlier write in it lost. With
110 /// `reliar-store-postgres` the transaction **is** aborted: PostgreSQL rejects every
111 /// subsequent statement on it, so no earlier write in that transaction can still be committed.
112 fn enqueue_envelope<T: Message + Sync>(
113 &self,
114 tx: &mut Tx,
115 envelope: Envelope<T>,
116 ) -> impl Future<Output = Result<MessageId, Self::Error>> + Send;
117
118 /// The **fire-and-forget** spelling: builds `body` into an envelope with default metadata
119 /// and a freshly rooted conversation — exactly `Envelope::builder(body).build()` — then
120 /// enqueues it via [`Self::enqueue_envelope`].
121 ///
122 /// ```
123 /// use reliar_core::Message;
124 /// use reliar_outbox::OutboxEnqueue;
125 ///
126 /// # #[derive(serde::Serialize, serde::Deserialize)]
127 /// # struct OrderCreated {
128 /// # order_id: u64,
129 /// # }
130 /// # impl Message for OrderCreated {
131 /// # const TYPE: &'static str = "orders.created";
132 /// # const VERSION: u16 = 1;
133 /// # }
134 /// async fn enqueue_order<S, Tx>(store: &S, tx: &mut Tx, order_id: u64) -> Result<(), S::Error>
135 /// where
136 /// S: OutboxEnqueue<Tx>,
137 /// {
138 /// store.enqueue(tx, OrderCreated { order_id }).await?;
139 /// Ok(())
140 /// }
141 /// ```
142 ///
143 /// Use [`Self::enqueue_envelope`] instead when an id must propagate from an inbound request;
144 /// this spelling never has anything to propagate from.
145 ///
146 /// Implementors **SHALL NOT** override this method — it is a fixed, provided spelling of
147 /// [`Self::enqueue_envelope`], not an extension point. `Envelope::builder(body).build()` mints
148 /// the envelope and its id eagerly, at call time, not on the returned future's first poll.
149 ///
150 /// # Errors
151 ///
152 /// Same as [`Self::enqueue_envelope`].
153 // Direct delegation, not `async fn` and no `async move` block either — returns
154 // `enqueue_envelope`'s own future unchanged. See `PostgresOutboxStore::enqueue_envelope`'s
155 // comment in `reliar-store-postgres/src/outbox/enqueue.rs` for the full `Send`/capture argument.
156 fn enqueue<T: Message + Sync>(
157 &self,
158 tx: &mut Tx,
159 body: T,
160 ) -> impl Future<Output = Result<MessageId, Self::Error>> + Send {
161 self.enqueue_envelope(tx, Envelope::builder(body).build())
162 }
163}