-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_task.rs
More file actions
77 lines (66 loc) · 2.44 KB
/
Copy pathbasic_task.rs
File metadata and controls
77 lines (66 loc) · 2.44 KB
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
//! Smallest complete typed producer/worker flow.
//!
//! The example defines one `Task`, registers an in-process async handler, spawns a
//! logical task, and awaits its typed result. It intentionally avoids retries and
//! checkpoints so the basic relationship between `Task`, `Queue`, `Worker`, and
//! `SpawnedTask` and its typed result stay visible.
/// Shared setup and finite-worker helpers.
mod common;
use std::time::Duration;
use common::RunningWorker;
use serde::{Deserialize, Serialize};
use steda::{Result, Task, TaskContext};
/// Input accepted by the invoice renderer.
#[derive(Debug, Deserialize, Serialize)]
struct RenderInvoiceInput {
/// Human-facing invoice identifier.
invoice_number: String,
/// Pre-tax subtotal in cents.
subtotal_cents: u64,
/// Tax amount in cents.
tax_cents: u64,
}
/// Typed result returned by the task.
#[derive(Debug, Deserialize, Serialize)]
struct RenderInvoiceOutput {
/// Human-facing invoice identifier.
invoice_number: String,
/// Final total in cents.
total_cents: u64,
}
/// Task definition for rendering an invoice.
const RENDER_INVOICE: Task<RenderInvoiceInput, RenderInvoiceOutput> = Task::new("render-invoice");
/// Run the basic producer/worker example.
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let steda = common::connect().await?;
let queue = steda.queue("example-basic")?;
queue.create().await?;
// Register the handler this worker can execute.
let worker = queue
.worker()
.task(RENDER_INVOICE, async |input: RenderInvoiceInput, _ctx: TaskContext| {
Ok(RenderInvoiceOutput {
invoice_number: input.invoice_number,
total_cents: input.subtotal_cents + input.tax_cents,
})
})
.build()?;
let worker = RunningWorker::start(worker);
// The task definition fixes both the accepted input and decoded result type.
let task = queue
.spawn(
RENDER_INVOICE,
RenderInvoiceInput {
invoice_number: "INV-1001".to_owned(),
subtotal_cents: 12_500,
tax_cents: 2_625,
},
)
.await?;
let invoice = task.result_with_timeout(Duration::from_secs(10)).await?;
println!("invoice {} rendered", invoice.invoice_number);
println!("total: €{}.{:02}", invoice.total_cents / 100, invoice.total_cents % 100);
worker.stop().await?;
Ok(())
}