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
//! The type of a field playing `headers`, shared by the inbox and the outbox.
use BTreeMap;
use mem;
use HeaderMap;
use Json;
/// The type of a field playing `headers`: what the delivery's header map holds.
///
/// `sqlx::types::Json<BTreeMap<String, String>>` implements it under the `json` feature (a
/// `jsonb` or `json` column of string values), and so does an `Option` of any implementation.
/// A publish carrying a header the column cannot hold byte for byte is refused before the
/// service's [`Publish`](crate::Publish) runs: a header never reaches the table changed.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "inbox", feature = "postgres"))]
/// # mod demo {
/// use ruststream::HeaderMap;
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::HeaderColumn;
/// use serde::Deserialize;
/// use sqlx::PgPool;
///
/// /// Headers stored one per line, `name: value`, in a `TEXT` column.
/// #[derive(sqlx::Type)]
/// #[sqlx(transparent)]
/// pub struct Lines(String);
///
/// impl HeaderColumn for Lines {
/// fn take_headers(&mut self) -> HeaderMap {
/// let headers = self
/// .0
/// .lines()
/// .filter_map(|line| line.split_once(": "))
/// .map(|(name, value)| (name.to_owned(), value.to_owned()))
/// .collect();
/// self.0.clear();
/// headers
/// }
///
/// fn from_headers(headers: &HeaderMap) -> Self {
/// let lines: Vec<String> = headers
/// .iter()
/// .map(|(name, value)| format!("{name}: {}", String::from_utf8_lossy(value)))
/// .collect();
/// Self(lines.join("\n"))
/// }
///
/// fn unfit(headers: &HeaderMap) -> Option<&str> {
/// // A value comes back as it went in when it is text on one line.
/// let fits = |value: &[u8]| str::from_utf8(value).is_ok_and(|text| !text.contains('\n'));
/// headers
/// .iter()
/// .find(|(_, value)| !fits(value))
/// .map(|(name, _)| name)
/// }
/// }
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs")]
/// pub struct Job {
/// #[field(id, generated)]
/// id: i64,
/// #[field(headers)]
/// headers: Lines,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// #[derive(Deserialize)]
/// struct Task {
/// n: u32,
/// }
///
/// // The delivery's headers come from `headers`, so the service's middleware reads `x-tenant`
/// // there as on any broker.
/// #[subscriber(InboxQueue::<Job>::new("tasks"))]
/// async fn run(task: &Task) -> HandlerOutcome {
/// tracing::info!(task.n, "running");
/// HandlerOutcome::ack()
/// }
///
/// pub fn app(pool: PgPool) -> RustStream {
/// RustStream::new(AppInfo::new("worker", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
/// b.include(run);
/// })
/// }
/// # }
/// # fn main() {}
/// ```
/// A record or a row whose headers live in one column: the field holding the column, which the
/// table's description names with its `headers` setter.
///
/// `#[derive(Inbox)]` and `#[derive(Outbox)]` implement it for the field playing `headers`. A queue
/// table described by hand implements it where its `InboxSpec` sets `spec::Headers`: a delivery
/// takes the header map out of the field when its row is claimed, so the row a handler reads holds
/// the column empty. A record described by hand implements it where its `OutboxSpec` sets
/// `outbox::spec::Headers`, and a republished record carries the headers it took out of the field.
///
/// # Examples
///
/// A queue table whose headers live in a `jsonb` column:
///
/// ```
/// # #[cfg(all(feature = "inbox", feature = "json", feature = "postgres"))]
/// # mod demo {
/// use std::collections::BTreeMap;
///
/// use ruststream_sqlx::dialect::Column;
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::spec::{Headers, Payload};
/// use ruststream_sqlx::{HeaderRow, InboxSpec, InboxTable, PayloadRow};
/// use serde::Deserialize;
/// use sqlx::PgPool;
/// use sqlx::types::Json;
///
/// #[derive(sqlx::FromRow)]
/// pub struct Job {
/// id: i64,
/// headers: Json<BTreeMap<String, String>>,
/// payload: Vec<u8>,
/// }
///
/// impl InboxTable for Job {
/// type Id = i64;
/// type Table = InboxSpec<(Headers, Payload)>;
/// const TABLE: Self::Table = InboxSpec::new("jobs", Column::new("id").generated())
/// .headers(Column::new("headers"))
/// .payload(Column::new("payload"));
///
/// fn id(&self) -> &i64 {
/// &self.id
/// }
/// }
///
/// impl HeaderRow for Job {
/// type Column = Json<BTreeMap<String, String>>;
///
/// fn headers_mut(&mut self) -> &mut Self::Column {
/// &mut self.headers
/// }
/// }
///
/// impl PayloadRow for Job {
/// type Column = Vec<u8>;
///
/// fn payload(&self) -> &[u8] {
/// &self.payload
/// }
/// }
///
/// #[derive(Deserialize)]
/// struct Task {
/// n: u32,
/// }
///
/// // The delivery's headers come from the `headers` column, as on any broker.
/// #[subscriber(InboxQueue::<Job>::new("tasks"))]
/// async fn run(task: &Task, ctx: &mut Context<'_>) -> HandlerOutcome {
/// let tenant = ctx.headers().get_str("x-tenant").unwrap_or_default();
/// tracing::info!(task.n, tenant, "running");
/// HandlerOutcome::ack()
/// }
///
/// pub fn app(pool: PgPool) -> RustStream {
/// RustStream::new(AppInfo::new("worker", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
/// b.include(run);
/// })
/// }
/// # }
/// # fn main() {}
/// ```
///
/// An outbox record that keeps the headers a message carried:
///
/// ```
/// # #[cfg(all(feature = "outbox", feature = "json", feature = "postgres"))]
/// # mod demo {
/// # use ruststream::OutgoingMessage;
/// use std::collections::BTreeMap;
///
/// use ruststream_sqlx::dialect::Column;
/// use ruststream_sqlx::outbox::spec::Headers;
/// use ruststream_sqlx::outbox::{self, OutboxSpec, OutboxTable};
/// use ruststream_sqlx::{HeaderColumn, HeaderRow};
/// use sqlx::types::Json;
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(sqlx::FromRow)]
/// pub struct OrderEvent {
/// id: i64,
/// name: String,
/// payload: Vec<u8>,
/// headers: Option<Json<BTreeMap<String, String>>>,
/// }
///
/// impl HeaderRow for OrderEvent {
/// type Column = Option<Json<BTreeMap<String, String>>>;
///
/// fn headers_mut(&mut self) -> &mut Self::Column {
/// &mut self.headers
/// }
/// }
///
/// impl OutboxTable for OrderEvent {
/// type Id = i64;
/// type Table = OutboxSpec<(Headers,)>;
/// const TABLE: Self::Table = OutboxSpec::new(
/// "outbox",
/// Column::new("id"),
/// Column::new("name"),
/// Column::new("payload"),
/// )
/// .headers(Column::new("headers"));
///
/// fn id(&self) -> &i64 {
/// &self.id
/// }
///
/// fn name(&self) -> &str {
/// &self.name
/// }
///
/// fn payload(&self) -> &[u8] {
/// &self.payload
/// }
/// }
///
/// // The record keeps what the message carried, so a republish sends the headers again.
/// impl outbox::Publish<Postgres> for OrderEvent {
/// async fn publish(conn: &mut PgConnection, msg: &OutgoingMessage<'_>) -> sqlx::Result<i64> {
/// sqlx::query_scalar(
/// "INSERT INTO outbox (name, payload, headers) VALUES ($1, $2, $3) RETURNING id",
/// )
/// .bind(msg.name())
/// .bind(msg.payload())
/// .bind(Option::<Json<BTreeMap<String, String>>>::from_headers(msg.headers()))
/// .fetch_one(conn)
/// .await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
/// A JSON object of strings. A value that is not UTF-8 does not fit: the broker refuses a publish
/// that carries one, so the replacement `from_headers` would write never reaches the table.