Ниже показан английский оригинал.
Roles
Each #[field(..)] role turns on one behaviour of the queue: group, priority, partition key, retry_after, attempt, processed_at, lease, headers, payload.
A column that plays a role switches its behaviour on, and a table without it keeps the default:
| Role | With the role | Without it |
|---|---|---|
group | a subscription reads the group its name selects; a dead letter moves the row to another group | a subscription reads the whole table; a dead letter moves the row into another table |
group, fifo = true | one row of a group is in work at a time, in claim order (FIFO) | the rows of a group run side by side |
priority | a smaller value is claimed first | rows are claimed by retry_after where the table has it, then by id |
partition_key | the delivery's partition key: under workers_by_key(n) the rows of one key run in order | the delivery has no key |
retry_after | retry_after(d) hides the row for d | retry_after(d) returns the row at once, with a warning |
attempt | Ctx<keys::Attempt> reads the count, and max_attempts(n) caps it | Ctx<keys::Attempt> reads None, and a mount with max_attempts(n) stops at startup |
processed_at | acknowledgement marks the row | acknowledgement deletes the row |
locked_until | the lease form | the row lock form, or the advisory lock form under advisory_lock |
headers | the delivery's headers, kept in one column | the delivery's headers are empty |
payload | payload mode: the handler takes the decoded payload | row mode: the handler takes the row |
Every role but id is optional, and each plays on one column at most.
generated beside a role marks a column the database fills in, such as a serial id or a column with a default, and the derive's insert leaves it out.
By hand, each role is a setter of InboxSpec.
A role a delivery reads off the row also names its marker in type Table and implements a small trait: Payload and PayloadRow, Key and KeyRow, Attempt and AttemptRow, Headers and HeaderRow.
The roles only the queue reads, such as group, priority and processed_at, need no field in the struct.
Example
The billing queue of a support table takes urgent tickets first, keeps each customer's tickets in order on one worker, and hides an open ticket for five minutes; an answered ticket stays in the table with its processed_at set.
- Macros
- Manual
#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "support_tickets")]
struct Ticket {
#[field(id, generated)]
id: i64,
#[field(group)]
queue: String,
#[field(priority)]
urgency: i16,
#[field(partition_key)]
customer: String,
#[field(retry_after)]
retry_after: DateTime<Utc>,
#[field(attempt, generated)]
attempt: i16,
#[field(processed_at)]
processed_at: Option<DateTime<Utc>>,
#[field(locked_until)]
locked_until: Option<DateTime<Utc>>,
#[field(payload)]
payload: Vec<u8>,
}
#[subscriber(InboxQueue::<Ticket>::new("billing"))]
async fn triage(question: &Question) -> HandlerOutcome {
if answer(question) {
return HandlerOutcome::ack();
}
HandlerOutcome::retry_after(Duration::from_secs(300))
}
/// The service on the database `url` names.
fn service(url: &str) -> RustStream {
let schema_url = url.to_owned();
// Nothing connects here: the broker builds its pool when the service starts.
let broker = SqlxBroker::from_url(url, SqlitePoolOptions::new());
RustStream::new(AppInfo::new("support", "0.1.0"))
// The table, created before the subscription checks it.
.on_startup(async move |()| {
let mut conn = SqliteConnection::connect(&schema_url).await?;
sqlx::raw_sql(SCHEMA).execute(&mut conn).await?;
conn.close().await
})
.with_broker(broker.route::<Ticket>("billing"), |b| {
b.include(triage.workers_by_key(nonzero!(4)));
})
}
#[derive(sqlx::FromRow)]
struct Ticket {
id: i64,
customer: String,
attempt: i16,
payload: Vec<u8>,
}
impl InboxTable for Ticket {
type Id = i64;
type Table = InboxSpec<(
Key,
RetryAfter<DateTime<Utc>>,
Attempt,
ProcessedAt<DateTime<Utc>>,
Lease<DateTime<Utc>>,
Payload,
)>;
const TABLE: Self::Table = InboxSpec::new("support_tickets", Column::new("id").generated())
.group(Column::new("queue"))
.priority(Column::new("urgency"))
.partition_key(Column::new("customer"))
.retry_after(Column::new("retry_after"))
.attempt(Column::new("attempt").generated())
.processed_at(Column::new("processed_at"))
.lease(Column::new("locked_until"))
.payload(Column::new("payload"));
fn id(&self) -> &i64 {
&self.id
}
}
impl KeyRow for Ticket {
type Key = String;
fn partition_key(&self) -> &String {
&self.customer
}
}
impl AttemptRow for Ticket {
type Attempt = i16;
fn attempt(&self) -> &i16 {
&self.attempt
}
}
impl PayloadRow for Ticket {
type Column = Vec<u8>;
fn payload(&self) -> &[u8] {
&self.payload
}
}
struct Triage;
impl Handle<Question> for Triage {
fn handle(
&self,
question: &Question,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
if answer(question) {
return ready(Ok(()));
}
ready(Err(HandlerOutcome::retry_after(Duration::from_secs(300))))
}
}
/// The service on the database `url` names.
fn service(url: &str) -> RustStream {
let schema_url = url.to_owned();
// Nothing connects here: the broker builds its pool when the service starts.
let broker = SqlxBroker::from_url(url, SqlitePoolOptions::new());
RustStream::new(AppInfo::new("support", "0.1.0"))
// The table, created before the subscription checks it.
.on_startup(async move |()| {
let mut conn = SqliteConnection::connect(&schema_url).await?;
sqlx::raw_sql(SCHEMA).execute(&mut conn).await?;
conn.close().await
})
.with_broker(broker.route::<Ticket>("billing"), |b| {
let triage = subscriber("billing", Triage)
.map_source(|_| InboxQueue::<Ticket>::new("billing"))
.workers_by_key(nonzero!(4));
b.include(triage.build());
})
}