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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! One trait per event of the queue: what a service implements when its table names the event as
//! its own, in `#[inbox(custom(..))]` or with `InboxSpec::own`, and `Publish`, which has no
//! default.
use Future;
use Duration;
use OutgoingMessage;
use ;
use InboxRow;
use LeaseRow;
/// Claims up to `limit` rows of the queue `queue` and returns their ids, inside the claim's
/// transaction.
///
/// The dialect builds it from the table's description; a table names `claim` as its own to take it
/// over (`custom(claim)`, or [`own::Claim`](crate::spec::own::Claim) by hand), for a database
/// without a built-in dialect or a claim of its own. The crate then reads the
/// rows with the service's [`Fetch`], or with its own fetch by a list of ids, which Postgres
/// alone runs: on MySQL and SQLite a claim of the service's own comes with a `Fetch` of its own,
/// and a subscription without one stops at startup. In the lease form the crate also leases each
/// id the claim returns, in the same transaction, and passes over an id whose row another lease
/// holds.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream_sqlx::{Claim, Inbox};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs", custom(claim))]
/// pub struct Job {
/// #[field(id)]
/// id: i64,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// impl Claim<Postgres> for Job {
/// async fn claim(
/// conn: &mut PgConnection,
/// _queue: &str,
/// limit: i64,
/// ) -> Result<Vec<i64>, sqlx::Error> {
/// // The oldest rows first, skipping the ones another worker holds.
/// sqlx::query_scalar("SELECT id FROM jobs ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED")
/// .bind(limit)
/// .fetch_all(conn)
/// .await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
/// Reads the rows of claimed ids, on the claim's connection.
///
/// The dialect builds it, for a flat table and for a message assembled from header fields; a table
/// names `fetch` as its own (`custom(fetch)`, or [`own::Fetch`](crate::spec::own::Fetch) by hand)
/// to assemble messages itself, from other tables
/// ([a fetch over a join](https://powersemmi.github.io/ruststream-sqlx/latest/components/headers/fetch/)). Rows are matched to the claimed ids by their `id` field; a
/// claimed id with no row settles by the decode-failure policy before its handler runs, and the
/// log names the id. It runs inside the claim's transaction, or right after a lease claim that
/// leased the rows and committed in one statement, as on Postgres and SQLite. In the advisory lock
/// form it runs once per row, with that row's id alone, after the take that counted its attempt.
/// Either way a delivery reports the attempt its row held before the claim. It runs only after a
/// claim that took ids, so `ids` is never empty.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream_sqlx::{Fetch, Inbox};
/// use sqlx::{PgConnection, Postgres};
///
/// /// A job whose message is the body of the order it refers to.
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs", custom(fetch))]
/// pub struct Job {
/// #[field(id)]
/// id: i64,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// impl Fetch<Postgres> for Job {
/// async fn fetch(conn: &mut PgConnection, ids: &[i64]) -> Result<Vec<Self>, sqlx::Error> {
/// sqlx::query_as(
/// "SELECT j.id, o.body AS payload FROM jobs j JOIN orders o ON o.id = j.order_id \
/// WHERE j.id = ANY($1)",
/// )
/// .bind(ids)
/// .fetch_all(conn)
/// .await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
///
/// In the headers layout two messages may flatten one headers struct: the default fetch reads one
/// from the queue table, and the service's own fetch reads the other over a join. A claimed id the
/// join finds no row for settles by the decode policy before the handler runs:
///
/// ```no_run
/// # #[cfg(all(feature = "inbox", feature = "postgres"))]
/// # mod demo {
/// use ruststream_sqlx::Fetch;
/// use ruststream_sqlx::prelude::*;
/// use serde::Deserialize;
/// use sqlx::{PgConnection, PgPool, Postgres};
///
/// // order_jobs: job_id BIGSERIAL PRIMARY KEY, name TEXT, attempt SMALLINT DEFAULT 1, tenant TEXT,
/// // trace TEXT NULL, order_id BIGINT, note TEXT NULL
/// // orders: id BIGINT PRIMARY KEY, customer TEXT, total BIGINT
/// /// The queue table: the columns that run the queue, and the headers `tenant`, `trace` and
/// /// `order_id`.
/// #[derive(Debug, Clone, InboxHeaders, sqlx::FromRow)]
/// #[inbox(table = "order_jobs")]
/// pub struct OrderHeaders {
/// #[field(id, generated)]
/// job_id: i64,
/// #[field(group)]
/// name: String,
/// #[field(attempt, generated)]
/// attempt: i16,
/// tenant: String,
/// trace: Option<String>,
/// order_id: i64,
/// }
///
/// /// A job and its note, read from the queue table by the default fetch.
/// #[derive(Debug, Clone, Inbox, sqlx::FromRow)]
/// pub struct OrderJob {
/// #[field(headers)]
/// #[sqlx(flatten)]
/// headers: OrderHeaders,
/// note: Option<String>,
/// }
///
/// /// A job and the order it is for, read by the service's own fetch over a join.
/// #[derive(Debug, Clone, Inbox, sqlx::FromRow)]
/// #[inbox(custom(fetch))]
/// pub struct OrderMail {
/// #[field(headers)]
/// #[sqlx(flatten)]
/// headers: OrderHeaders,
/// customer: String,
/// total: i64,
/// }
///
/// impl Fetch<Postgres> for OrderMail {
/// async fn fetch(conn: &mut PgConnection, ids: &[i64]) -> Result<Vec<Self>, sqlx::Error> {
/// sqlx::query_as(
/// "SELECT j.job_id, j.name, j.attempt, j.tenant, j.trace, j.order_id, \
/// o.customer, o.total \
/// FROM order_jobs j JOIN orders o ON o.id = j.order_id \
/// WHERE j.job_id = ANY($1)",
/// )
/// .bind(ids)
/// .fetch_all(conn)
/// .await
/// }
/// }
///
/// #[derive(Deserialize)]
/// pub struct Tenant {
/// tenant: String,
/// trace: Option<String>,
/// }
///
/// #[subscriber(InboxQueue::<OrderJob>::new("packing"))]
/// async fn pack(job: &OrderJob) -> HandlerOutcome {
/// tracing::info!(attempt = job.headers.attempt, note = ?job.note, "packing");
/// HandlerOutcome::ack()
/// }
///
/// // The header map is built from `OrderHeaders` on its first read, here by `Headers<Tenant>`.
/// #[subscriber(InboxQueue::<OrderMail>::new("receipts"))]
/// async fn send_receipt(mail: &OrderMail, Headers(tenant): Headers<Tenant>) -> HandlerOutcome {
/// tracing::info!(
/// tenant = %tenant.tenant,
/// trace = ?tenant.trace,
/// customer = %mail.customer,
/// total = mail.total,
/// "sending the receipt"
/// );
/// HandlerOutcome::ack()
/// }
///
/// pub fn app(pool: PgPool) -> RustStream {
/// RustStream::new(AppInfo::new("shop", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
/// b.include(pack);
/// // A job whose order is gone fails to decode: the default policy drops it.
/// b.include(send_receipt);
/// })
/// }
/// # }
/// # fn main() {}
/// ```
settle_event!;
settle_event!;
settle_event!;
settle_event!;
settle_event!;
/// Extends the lease on a row: writes `until` into `locked_until` while the row still holds
/// `held`, and says whether it did.
///
/// The dialect builds it for every table in the lease form; a table names `extend` as its own
/// (`custom(extend)`, or [`own::Extend`](crate::spec::own::Extend) by hand) to take it over, for a
/// database without a built-in dialect. A
/// subscription runs it each half lease for every delivery in work, on one connection. The crate
/// also runs it with `until` equal to `held` to confirm a delivery's lease, inside the transaction
/// where an event of the service's own then runs.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "postgres", feature = "chrono"))]
/// # mod demo {
/// use chrono::{DateTime, Utc};
/// use ruststream_sqlx::{Extend, Inbox};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs", custom(extend))]
/// pub struct Job {
/// #[field(id)]
/// id: i64,
/// #[field(locked_until)]
/// locked_until: Option<DateTime<Utc>>,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// impl Extend<Postgres> for Job {
/// async fn extend(
/// conn: &mut PgConnection,
/// id: &i64,
/// held: &DateTime<Utc>,
/// until: &DateTime<Utc>,
/// ) -> Result<bool, sqlx::Error> {
/// // The row keeps its lease only while it holds the expiry the delivery knows.
/// let extended =
/// sqlx::query("UPDATE jobs SET locked_until = $1 WHERE id = $2 AND locked_until = $3")
/// .bind(until)
/// .bind(id)
/// .bind(held)
/// .execute(conn)
/// .await?;
/// Ok(extended.rows_affected() == 1)
/// }
/// }
/// # }
/// # fn main() {}
/// ```
/// Takes the advisory lock on a row's key for the session that will hold its delivery, without
/// waiting: the `lock` event of the advisory lock form.
///
/// The dialect takes the lock itself on Postgres and MySQL, and the process keeps the keys in work
/// on SQLite. A table names `lock` and `unlock` as its own together (`custom(lock, unlock)`, or
/// [`own::Lock`](crate::spec::own::Lock) and [`own::Unlock`](crate::spec::own::Unlock) by hand) to
/// run the service's own SQL for them instead, as a database without a built-in dialect does, MSSQL with
/// `sp_getapplock` and `sp_releaseapplock`; the dialect still selects the candidates and takes
/// each row. A claim calls it once per candidate with the key the template renders, on the
/// connection that holds the delivery; [`Unlock`] releases the lock when the delivery settles,
/// and where the delivery is dropped unsettled the connection closes after that unlock. With a
/// lock of the service's own the process keeps no registry of keys, on SQLite too.
///
/// The dialect's candidate select cannot see a lock of the service's own, so a claim reads as many
/// candidates past its limit as the subscription has deliveries in work: a key its deliveries hold
/// does not hold back the rows behind it. A key the service's lock holds elsewhere, in another
/// process or system, is passed over within that margin only: while such keys head the claim
/// order, the claim may end empty and wait for its next poll.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream_sqlx::{Inbox, Lock, Unlock};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs", advisory_lock = "jobs-{id}", custom(lock, unlock))]
/// pub struct Job {
/// #[field(id)]
/// id: i64,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// // The pair MSSQL writes with `sp_getapplock` and `sp_releaseapplock`, written here with
/// // Postgres's session locks on a 32-bit hash of the key.
/// impl Lock<Postgres> for Job {
/// async fn lock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_try_advisory_lock(hashtext($1))")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
///
/// impl Unlock<Postgres> for Job {
/// async fn unlock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_advisory_unlock(hashtext($1))")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
///
/// A queue that takes the lock another system already holds on an account, so a payout never
/// runs beside that system's work on it:
///
/// ```no_run
/// # #[cfg(all(feature = "inbox", feature = "postgres"))]
/// # mod demo {
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::{Lock, Unlock};
/// use serde::Deserialize;
/// use sqlx::{PgConnection, PgPool, Postgres};
///
/// // payouts: id BIGSERIAL PRIMARY KEY, account_id BIGINT NOT NULL, payload BYTEA NOT NULL
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "payouts", advisory_lock = "{account_id}", custom(lock, unlock))]
/// pub struct Payout {
/// #[field(id, generated)]
/// id: i64,
/// account_id: i64,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// // The billing system holds `pg_advisory_lock(account_id)` while it changes an account. The queue
/// // takes the same lock, so a payout never runs beside a billing run of its account.
/// impl Lock<Postgres> for Payout {
/// async fn lock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_try_advisory_lock($1::bigint)")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
///
/// impl Unlock<Postgres> for Payout {
/// async fn unlock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_advisory_unlock($1::bigint)")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
///
/// #[derive(Deserialize)]
/// pub struct Transfer {
/// cents: i64,
/// }
///
/// # async fn transfer_to_bank(transfer: &Transfer) { let _ = transfer.cents; }
/// #[subscriber(InboxQueue::<Payout>::new("payouts"))]
/// async fn pay(transfer: &Transfer) -> HandlerOutcome {
/// transfer_to_bank(transfer).await;
/// HandlerOutcome::ack()
/// }
///
/// pub fn app(pool: PgPool) -> RustStream {
/// RustStream::new(AppInfo::new("payouts", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
/// b.include(pay);
/// })
/// }
/// # }
/// # fn main() {}
/// ```
/// Releases the advisory lock on a delivery's key: the `unlock` event of the advisory lock form,
/// which a table names as its own beside [`Lock`].
///
/// A settlement calls it after its statement, on the connection that holds the delivery, and the
/// connection goes back to the pool once it answered `true`. An unlock that answers `false` or
/// fails closes the connection instead, which ends the session and its locks. A delivery dropped
/// unsettled runs it before its connection closes, and `shutdown` runs it for every delivery in
/// work.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream_sqlx::{Inbox, Lock, Unlock};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "jobs", advisory_lock = "jobs-{id}", custom(lock, unlock))]
/// pub struct Job {
/// #[field(id)]
/// id: i64,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// // MSSQL releases with `sp_releaseapplock`; Postgres's session lock stands in for it here.
/// impl Unlock<Postgres> for Job {
/// async fn unlock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_advisory_unlock(hashtext($1))")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
///
/// impl Lock<Postgres> for Job {
/// async fn lock(conn: &mut PgConnection, key: &str) -> Result<bool, sqlx::Error> {
/// sqlx::query_scalar("SELECT pg_try_advisory_lock(hashtext($1))")
/// .bind(key)
/// .fetch_one(conn)
/// .await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
/// Writes a published message into the table: the name, the bytes and the headers reach the
/// service's SQL, which lays them out in its columns.
///
/// It has no default. With it, the struct's [`Repository`](crate::Repository) is a publisher and
/// a route can lead names to it; without it, a mount that needs one does not compile, rather than
/// publish into nothing. A message carrying a header the struct cannot hold byte for byte (any
/// header, without a `#[field(headers)]` field; see [`HeaderColumn`](crate::HeaderColumn)) is
/// refused before this runs.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream::OutgoingMessage;
/// use ruststream_sqlx::{Inbox, Publish};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "email_jobs")]
/// pub struct SendEmail {
/// #[field(id, generated)]
/// job_id: i64,
/// #[field(group)]
/// name: String,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// impl Publish<Postgres> for SendEmail {
/// async fn publish(
/// conn: &mut PgConnection,
/// message: &OutgoingMessage<'_>,
/// ) -> Result<(), sqlx::Error> {
/// sqlx::query("INSERT INTO email_jobs (name, payload) VALUES ($1, $2)")
/// .bind(message.name())
/// .bind(message.payload())
/// .execute(conn)
/// .await?;
/// Ok(())
/// }
/// }
/// # }
/// # fn main() {}
/// ```
/// Inserts the row: every field except the `generated` ones, the queue's mechanics included, so
/// a delayed task is a row whose `retry_after` lies ahead.
///
/// The derive implements it for the connection of each built-in dialect, `PgConnection` (feature
/// `postgres`), `MySqlConnection` (feature `mysql`) and `SqliteConnection` (feature `sqlite`), with
/// the statements built at compile time. A headers struct gets it from
/// [`InboxHeaders`](derive@crate::InboxHeaders): the queue table's columns.
/// A struct with a `#[sqlx(flatten)]` field gets none: the derive cannot see the nested struct's
/// columns, so the service writes that insert itself.
/// A table described by hand implements it over the text
/// [`dialect::insert`](crate::dialect::insert) renders from its description, binding the columns
/// in the description's order, as below.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "postgres")]
/// # mod demo {
/// use ruststream::OutgoingMessage;
/// use ruststream_sqlx::{Inbox, Insert, Publish};
/// use sqlx::{PgConnection, Postgres};
///
/// #[derive(Inbox, sqlx::FromRow)]
/// #[inbox(table = "email_jobs")]
/// pub struct SendEmail {
/// #[field(id, generated)]
/// job_id: i64,
/// #[field(group)]
/// name: String,
/// #[field(payload)]
/// payload: Vec<u8>,
/// }
///
/// impl Publish<Postgres> for SendEmail {
/// async fn publish(
/// conn: &mut PgConnection,
/// message: &OutgoingMessage<'_>,
/// ) -> Result<(), sqlx::Error> {
/// let job = SendEmail {
/// job_id: 0,
/// name: message.name().to_owned(),
/// payload: message.payload().to_vec(),
/// };
/// // `job_id` is generated: the database fills it in.
/// job.insert(conn).await
/// }
/// }
/// # }
/// # fn main() {}
/// ```
///
/// A table described by hand in row mode writes its insert over the text
/// [`dialect::insert`](crate::dialect::insert) renders, in a constant:
///
/// ```no_run
/// # #[cfg(all(feature = "inbox", feature = "postgres"))]
/// # mod demo {
/// use ruststream::runtime::{Input, SoloCarried};
/// use ruststream_sqlx::dialect::Column;
/// use ruststream_sqlx::dialect::insert::{self, Sql};
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::spec::Attempt;
/// use ruststream_sqlx::{AttemptRow, InboxSpec, InboxTable};
/// use serde::{Deserialize, Serialize};
/// use sqlx::{PgConnection, PgPool};
///
/// #[derive(sqlx::FromRow, Clone)]
/// pub struct SendEmail {
/// job_id: i64,
/// name: String,
/// attempt: i16,
/// to: String,
/// subject: Option<String>,
/// #[sqlx(json)]
/// attachments: Vec<Attachment>,
/// }
///
/// #[derive(Clone, Serialize, Deserialize)]
/// pub struct Attachment {
/// file: String,
/// }
///
/// impl InboxTable for SendEmail {
/// type Id = i64;
/// type Table = InboxSpec<(Attempt,)>;
/// const TABLE: Self::Table = InboxSpec::new("email_jobs", Column::new("job_id").generated())
/// .group(Column::new("name"))
/// .attempt(Column::new("attempt").generated())
/// .data(&[Column::new("to"), Column::new("subject"), Column::new("attachments")]);
///
/// fn id(&self) -> &i64 {
/// &self.job_id
/// }
/// }
///
/// // Row mode: a handler takes the row itself.
/// impl Input for SendEmail {
/// type Axis = SoloCarried<Self>;
/// }
///
/// impl AttemptRow for SendEmail {
/// type Attempt = i16;
///
/// fn attempt(&self) -> &i16 {
/// &self.attempt
/// }
/// }
///
/// // INSERT INTO "email_jobs" ("name", "to", "subject", "attachments") VALUES ($1, $2, $3, $4)
/// const INSERT: Sql<128> = insert::postgres(&SendEmail::TABLE.spec());
///
/// impl Insert<PgConnection> for SendEmail {
/// async fn insert(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
/// sqlx::query(INSERT.as_str())
/// .bind(&self.name)
/// .bind(&self.to)
/// .bind(&self.subject)
/// .bind(sqlx::types::Json(&self.attachments))
/// .execute(conn)
/// .await?;
/// Ok(())
/// }
/// }
/// # async fn deliver(_: &SendEmail) -> bool { true }
/// # #[subscriber(InboxQueue::<SendEmail>::new("emails"))]
/// # async fn send(email: &SendEmail) -> HandlerOutcome {
/// # if deliver(email).await { HandlerOutcome::ack() } else { HandlerOutcome::retry() }
/// # }
/// # pub fn app(pool: PgPool) -> RustStream {
/// # RustStream::new(AppInfo::new("mailer", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
/// # b.include(send);
/// # })
/// # }
/// # }
/// # fn main() {}
/// ```