ruststream-sqlx 0.7.0

SQL databases for the RustStream messaging framework through sqlx: a transactional outbox over any RustStream broker and task queues in Postgres, MySQL/MariaDB and SQLite tables.
Documentation
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
//! What each setting of a table described by hand means to the crate: one trait per setting,
//! implemented for [`Unset`] and for the [`Set`] markers of that setting. The blanket contract
//! reads a setting through its trait, so every choice is a type the compiler resolves.

use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;

use ruststream::HeaderMap;
use ruststream_sqlx_dialect::Param;
use sqlx::{Decode, Encode, Error, Type};

use super::{AttemptRow, HeaderFields, KeyRow};
use crate::HeaderColumn;
use crate::HeaderRow;
use crate::inbox::database::QueueDatabase;
use crate::inbox::engine::{self, Events, Leasing, Now, TimeFor, Values};
use crate::inbox::form::{AdvisoryForm, LeaseForm, RowLockForm};
use crate::inbox::headers::{self, HeaderCell, LazyHeaders};
use crate::inbox::named::kinds::KindsOf;
use crate::inbox::queue::Queue;
use crate::inbox::spec::{
    self, Advisory, Attempt, AttemptFrom, Clock, Headers, Key, Lease, OpeningLevel, Opens, Payload,
    ProcessedAt, RetryAfter, Set, Unset,
};
use crate::inbox::time::{QueueTime, SystemClock, TimeSource};
use crate::inbox::{Lane, PayloadLane, PayloadRow, RowLane};

/// Whether a table sets a setting.
pub trait Named {
    /// `true` where the table sets it.
    const NAMED: bool;
}

impl Named for Unset {
    const NAMED: bool = false;
}

impl<Value> Named for Set<Value> {
    const NAMED: bool = true;
}

/// The form setting: the form's type, the lease a delivery holds and how a claim takes it.
pub trait FormAxis {
    /// The form as the type a subscription checks against its dialect.
    type Form;
    /// The lease a delivery holds; `()` outside the lease form.
    type Token: Copy + Debug + Send + Sync + 'static;

    /// The lease a claim takes now.
    ///
    /// # Errors
    ///
    /// As `Events::lease`.
    fn lease<Source: TimeSource>(
        queue: &'static Queue,
        now: Now,
    ) -> Result<Leasing<Self::Token>, Error>;

    /// The lease's time among the column kinds a by-name subscription reads.
    fn kinds(kinds: KindsOf) -> KindsOf;
}

impl FormAxis for Unset {
    type Form = RowLockForm;
    type Token = ();

    fn lease<Source: TimeSource>(_: &'static Queue, _: Now) -> Result<Leasing<()>, Error> {
        engine::no_lease()
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl FormAxis for Set<Advisory> {
    type Form = AdvisoryForm;
    type Token = ();

    fn lease<Source: TimeSource>(_: &'static Queue, _: Now) -> Result<Leasing<()>, Error> {
        engine::no_lease()
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl<Time: QueueTime> FormAxis for Set<Lease<Time>> {
    type Form = LeaseForm;
    type Token = Time;

    fn lease<Source: TimeSource>(queue: &'static Queue, now: Now) -> Result<Leasing<Time>, Error> {
        engine::lease::<Source, Time>(queue, now)
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.locked_until::<Time>()
    }
}

/// The form setting's statement parameters on `DB`.
pub trait FormBind<DB: QueueDatabase>: FormAxis {
    /// Binds a lease parameter; `false` where the form has none.
    ///
    /// # Errors
    ///
    /// The driver's encoding error.
    fn bind<Row: Events<DB, Token = Self::Token>>(
        param: Param,
        arguments: &mut DB::Arguments,
        values: &Values<'_, DB, Row>,
    ) -> Result<bool, Error>;
}

macro_rules! no_lease_bind {
    ($($axis:ty),*) => {
        $(impl<DB: QueueDatabase> FormBind<DB> for $axis {
            fn bind<Row: Events<DB, Token = ()>>(
                _: Param,
                _: &mut DB::Arguments,
                _: &Values<'_, DB, Row>,
            ) -> Result<bool, Error> {
                Ok(false)
            }
        })*
    };
}

no_lease_bind!(Unset, Set<Advisory>);

impl<DB, Time> FormBind<DB> for Set<Lease<Time>>
where
    DB: QueueDatabase,
    Time: QueueTime + for<'q> Encode<'q, DB> + Type<DB>,
{
    fn bind<Row: Events<DB, Token = Time>>(
        param: Param,
        arguments: &mut DB::Arguments,
        values: &Values<'_, DB, Row>,
    ) -> Result<bool, Error> {
        let value = match param {
            Param::LeaseNow => values.leasing.map(|leasing| leasing.now),
            Param::Lease => values.lease,
            Param::Held => values.held,
            _ => return Ok(false),
        };
        let Some(value) = value else {
            return Ok(false);
        };
        engine::put::<DB, _>(arguments, value)?;
        Ok(true)
    }
}

/// The lease form's time, for `LeaseRow`.
pub trait LeaseAxis {
    /// The time `locked_until` holds.
    type Time: QueueTime;
}

impl<Time: QueueTime> LeaseAxis for Set<Lease<Time>> {
    type Time = Time;
}

/// The message mode setting.
pub trait MessageAxis<Row> {
    /// The lane a delivery hands the message on.
    type Lane: Lane<Row>;

    /// The payload's column among the column kinds a by-name subscription reads.
    fn kinds(kinds: KindsOf) -> KindsOf;
}

impl<Row> MessageAxis<Row> for Unset {
    type Lane = RowLane;

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl<Row: PayloadRow> MessageAxis<Row> for Set<Payload> {
    type Lane = PayloadLane;

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.payload::<Row::Column>()
    }
}

/// The `partition_key` setting.
pub trait KeyAxis<Row> {
    /// The row's key.
    fn key(row: &Row) -> Option<&[u8]>;

    /// The key's column among the column kinds a by-name subscription reads.
    fn kinds(kinds: KindsOf) -> KindsOf;
}

impl<Row> KeyAxis<Row> for Unset {
    fn key(_: &Row) -> Option<&[u8]> {
        None
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl<Row: KeyRow> KeyAxis<Row> for Set<Key> {
    fn key(row: &Row) -> Option<&[u8]> {
        crate::KeyColumn::key(row.partition_key())
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.partition_key::<Row::Key>()
    }
}

/// The `attempt` setting on `DB`.
pub trait AttemptAxis<DB: QueueDatabase, Row> {
    /// The row's attempt.
    fn attempt(row: &Row) -> Option<u64>;

    /// The attempt of a row that did not decode, read alone from `column`.
    fn read(row: &DB::Row, column: Option<&str>) -> Option<u64>;

    /// The attempt's column among the column kinds a by-name subscription reads.
    fn kinds(kinds: KindsOf) -> KindsOf;
}

impl<DB: QueueDatabase, Row> AttemptAxis<DB, Row> for Unset {
    fn attempt(_: &Row) -> Option<u64> {
        None
    }

    fn read(_: &DB::Row, _: Option<&str>) -> Option<u64> {
        None
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl<DB, Row> AttemptAxis<DB, Row> for Set<Attempt>
where
    DB: QueueDatabase,
    Row: AttemptRow,
    Row::Attempt: for<'r> Decode<'r, DB> + Type<DB>,
{
    fn attempt(row: &Row) -> Option<u64> {
        Some(crate::AttemptColumn::attempt(row.attempt()))
    }

    fn read(row: &DB::Row, column: Option<&str>) -> Option<u64> {
        engine::attempt_in::<DB, Row::Attempt, Row::Attempt>(row, column?)
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.attempt::<Row::Attempt>()
    }
}

impl<DB, Row, Decoded> AttemptAxis<DB, Row> for Set<AttemptFrom<Decoded>>
where
    DB: QueueDatabase,
    Row: AttemptRow,
    Row::Attempt: TryFrom<Decoded>,
    Decoded: for<'r> Decode<'r, DB> + Type<DB>,
{
    fn attempt(row: &Row) -> Option<u64> {
        Some(crate::AttemptColumn::attempt(row.attempt()))
    }

    fn read(row: &DB::Row, column: Option<&str>) -> Option<u64> {
        engine::attempt_in::<DB, Decoded, Row::Attempt>(row, column?)
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.attempt::<Row::Attempt>()
    }
}

/// The headers setting.
pub trait HeadersAxis<Row> {
    /// Where a delivery keeps its header map.
    type Cell: Default + Send + Sync + 'static;

    /// The header map moved out of the row.
    fn take(row: &mut Row) -> HeaderMap;

    /// The first header the row cannot hold.
    fn unfit(headers: &HeaderMap) -> Option<&str>;

    /// The cell a delivery keeps, as `HeaderCell::take`.
    fn cell<DB: QueueDatabase>(row: &mut Row) -> Self::Cell
    where
        Row: Events<DB>;

    /// As `HeaderCell::is_unset`.
    fn is_unset<DB: QueueDatabase>(cell: &Self::Cell) -> bool
    where
        Row: Events<DB>;

    /// As `HeaderCell::read`.
    fn read<'c, DB: QueueDatabase>(cell: &'c Self::Cell, row: Option<&Row>) -> &'c HeaderMap
    where
        Row: Events<DB>;

    /// The header column among the column kinds a by-name subscription reads.
    fn kinds(kinds: KindsOf) -> KindsOf;
}

/// The header cell of a table described by hand, with the layout of the cell its headers setting
/// names.
///
/// The blanket contract names this type instead of the setting's cell, which would restate the
/// row's own bounds and make the trait solver loop.
pub struct ManualHeaders<Axis: HeadersAxis<Row>, Row>(Axis::Cell, PhantomData<fn() -> Row>);

impl<Axis: HeadersAxis<Row>, Row> Debug for ManualHeaders<Axis, Row> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str("ManualHeaders")
    }
}

impl<Axis: HeadersAxis<Row>, Row> Default for ManualHeaders<Axis, Row> {
    fn default() -> Self {
        Self(Axis::Cell::default(), PhantomData)
    }
}

impl<DB, Row, Axis> HeaderCell<DB, Row> for ManualHeaders<Axis, Row>
where
    DB: QueueDatabase,
    Row: Events<DB> + 'static,
    Axis: HeadersAxis<Row> + 'static,
{
    fn take(row: &mut Row) -> Self {
        Self(Axis::cell::<DB>(row), PhantomData)
    }

    fn is_unset(&self) -> bool {
        Axis::is_unset::<DB>(&self.0)
    }

    fn read<'c>(&'c self, row: Option<&Row>) -> &'c HeaderMap {
        Axis::read::<DB>(&self.0, row)
    }
}

/// The cell of a table whose header map the row hands over: the map itself.
macro_rules! map_cell {
    () => {
        fn cell<DB: QueueDatabase>(row: &mut Row) -> HeaderMap
        where
            Row: Events<DB>,
        {
            <HeaderMap as HeaderCell<DB, Row>>::take(row)
        }

        fn is_unset<DB: QueueDatabase>(cell: &HeaderMap) -> bool
        where
            Row: Events<DB>,
        {
            <HeaderMap as HeaderCell<DB, Row>>::is_unset(cell)
        }

        fn read<'c, DB: QueueDatabase>(cell: &'c HeaderMap, row: Option<&Row>) -> &'c HeaderMap
        where
            Row: Events<DB>,
        {
            <HeaderMap as HeaderCell<DB, Row>>::read(cell, row)
        }
    };
}

impl<Row> HeadersAxis<Row> for Unset {
    type Cell = HeaderMap;

    fn take(_: &mut Row) -> HeaderMap {
        HeaderMap::new()
    }

    fn unfit(headers: &HeaderMap) -> Option<&str> {
        engine::first_header(headers)
    }

    map_cell!();

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

impl<Row: HeaderRow> HeadersAxis<Row> for Set<Headers> {
    type Cell = HeaderMap;

    fn take(row: &mut Row) -> HeaderMap {
        row.headers_mut().take_headers()
    }

    fn unfit(headers: &HeaderMap) -> Option<&str> {
        <Row::Column as HeaderColumn>::unfit(headers)
    }

    map_cell!();

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds.headers::<Row::Column>()
    }
}

impl<Row: HeaderFields> HeadersAxis<Row> for Set<spec::HeaderFields> {
    type Cell = LazyHeaders;

    fn take(_: &mut Row) -> HeaderMap {
        HeaderMap::new()
    }

    fn unfit(headers: &HeaderMap) -> Option<&str> {
        headers::unnamed_header(headers, Row::NAMES)
    }

    fn cell<DB: QueueDatabase>(row: &mut Row) -> LazyHeaders
    where
        Row: Events<DB>,
    {
        <LazyHeaders as HeaderCell<DB, Row>>::take(row)
    }

    fn is_unset<DB: QueueDatabase>(cell: &LazyHeaders) -> bool
    where
        Row: Events<DB>,
    {
        <LazyHeaders as HeaderCell<DB, Row>>::is_unset(cell)
    }

    fn read<'c, DB: QueueDatabase>(cell: &'c LazyHeaders, row: Option<&Row>) -> &'c HeaderMap
    where
        Row: Events<DB>,
    {
        <LazyHeaders as HeaderCell<DB, Row>>::read(cell, row)
    }

    fn kinds(kinds: KindsOf) -> KindsOf {
        kinds
    }
}

/// A time role on `DB`: `retry_after` or `processed_at`.
pub trait TimeAxis<DB: QueueDatabase> {
    /// Binds now; `false` without the column.
    ///
    /// # Errors
    ///
    /// The driver's encoding error, or the clock's.
    fn now<Source: TimeSource, Row: Events<DB>>(
        arguments: &mut DB::Arguments,
        values: &Values<'_, DB, Row>,
    ) -> Result<bool, Error>;

    /// Binds now plus the delay; `false` without the column.
    ///
    /// # Errors
    ///
    /// As [`now`](Self::now).
    fn later<Source: TimeSource, Row: Events<DB>>(
        arguments: &mut DB::Arguments,
        values: &Values<'_, DB, Row>,
    ) -> Result<bool, Error>;

    /// The column among the column kinds a by-name subscription reads, as `retry_after` when
    /// `due` and as `processed_at` otherwise.
    fn kinds(kinds: KindsOf, due: bool) -> KindsOf;
}

impl<DB: QueueDatabase> TimeAxis<DB> for Unset {
    fn now<Source: TimeSource, Row: Events<DB>>(
        _: &mut DB::Arguments,
        _: &Values<'_, DB, Row>,
    ) -> Result<bool, Error> {
        Ok(false)
    }

    fn later<Source: TimeSource, Row: Events<DB>>(
        _: &mut DB::Arguments,
        _: &Values<'_, DB, Row>,
    ) -> Result<bool, Error> {
        Ok(false)
    }

    fn kinds(kinds: KindsOf, _: bool) -> KindsOf {
        kinds
    }
}

macro_rules! time_axis {
    ($($marker:ident),*) => {$(
        impl<DB, Time> TimeAxis<DB> for Set<$marker<Time>>
        where
            DB: QueueDatabase,
            Time: TimeFor<DB>,
        {
            fn now<Source: TimeSource, Row: Events<DB>>(
                arguments: &mut DB::Arguments,
                values: &Values<'_, DB, Row>,
            ) -> Result<bool, Error> {
                let now = engine::now::<Source, Time::Time, DB, Row>(values)?;
                engine::put::<DB, _>(arguments, now)?;
                Ok(true)
            }

            fn later<Source: TimeSource, Row: Events<DB>>(
                arguments: &mut DB::Arguments,
                values: &Values<'_, DB, Row>,
            ) -> Result<bool, Error> {
                let later = engine::later::<Source, Time::Time, DB, Row>(values)?;
                engine::put::<DB, _>(arguments, later)?;
                Ok(true)
            }

            fn kinds(kinds: KindsOf, due: bool) -> KindsOf {
                if due {
                    kinds.retry_after::<Time::Time>()
                } else {
                    kinds.processed_at::<Time::Time>()
                }
            }
        }
    )*};
}

time_axis!(RetryAfter, ProcessedAt);

/// The clock setting.
pub trait ClockAxis {
    /// Where the table reads now.
    type Source: TimeSource;
}

impl ClockAxis for Unset {
    type Source = SystemClock;
}

impl<Source: TimeSource> ClockAxis for Set<Clock<Source>> {
    type Source = Source;
}

/// The opening setting.
pub trait OpeningAxis {
    /// The opening as the type a subscription checks against its dialect.
    type Opening;
}

impl OpeningAxis for Unset {
    type Opening = ();
}

impl<Level: OpeningLevel> OpeningAxis for Set<Opens<Level>> {
    type Opening = Level;
}