Stateful and Stateless
Both modes can query, create, update and delete data; the only difference is whether the Linker transport keeps the component's state.
| Stateful (default) | Stateless | |
|---|---|---|
| Good for | Wizards, drafts, flow guards across calls | Server-side computation, queries, one-off commands |
| Mount data | alias + uuid + rev | alias + a signed URL with an expiry |
| State | Stored in the cache (linker:{user}:{uuid}), restored before each call | Not stored; each call builds a fresh C::default() |
| Endpoint | POST /{prefix}/linker | POST /{prefix}/linker/stateless/{alias}/call?user=…&absolute_expires_at=…&expires=…&signature=… |
| Request | {component, instance, rev, method, args} | {method, args} |
| Response also carries | instance, rev | The renewed url |
| Mount parameters | Yes (mount(&mut self, ctx, params)) | Not accepted (mount with parameters returns an error) |
| Concurrency | Locked per instance; an old rev gets conflict | The same URL can run in parallel; correctness comes from DB transactions, unique constraints, idempotency |
| Reload | A brand new instance; state not saved to the DB is gone | A brand new URL |
| Struct fields | Saved back | Thrown away when the call ends |
Switching to Stateless
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerMode, LinkerResponse};
#[derive(Default, Serialize, Deserialize)]
pub struct Quote;
impl LinkerComponent for Quote {
const ALIAS: &'static str = "quote";
const MODE: LinkerMode = LinkerMode::Stateless;
const METHODS: &'static [&'static str] = &["price"];
async fn call(&mut self, _: &LinkerContext, _: &str, args: Args) -> laravel::Result<LinkerResponse> {
let qty = args.get("qty").and_then(|v| v.as_str()?.parse::<u32>().ok()).filter(|q| *q >= 1);
let Some(qty) = qty else {
return Ok(LinkerResponse::validation([("qty", "The quantity must be at least 1.")]));
};
Ok(LinkerResponse::ok().data("total", qty * 120))
}
}Mounting is the same: linker::mount::<Quote, User>(&user, linker::Args::new()). The example project's src/cg/greeter.rs is Stateless.
- Stateless doesn't accept mount parameters; put the scope into verifiable arguments on each call instead.
- The signed URL only proves integrity and expiry; it isn't authorization. Login, CSRF, the signed user matching the logged-in user, Referer and
METHODSare all still checked, and business permissions are still yours to check incall. - A different user (the signed
user≠ the logged-in user) or a tampered URL gets 403 policy.
Lifetimes
| Idle | Renewal | Maximum | |
|---|---|---|---|
| Stateful instances | 30 minutes (store::IDLE) | On successful calls; on validation failures at most every 90 seconds (RENEW_INTERVAL) | 8 hours (MAX_LIFETIME) |
| Stateless URLs | 30 minutes | A new URL is returned on success or validation failure | 8 hours (signed into absolute_expires_at) |
In the PHP version these are settings in config/linker.php; in Rust they're constants in runtime/linker/store.rs. The minimum interval between interactions, 0.8 seconds, is linker::MIN_DELAY_MS, written into data-linker-min-delay by mount.
One Stateful call
POST /{prefix}/linker
→ wrong prefix → 404
→ not logged in → 401 policy "請先登入。" (please log in)
→ invalid fields (component / instance / rev / method / args) → 422
→ alias not registered, or not Stateful → 404 policy
→ cache lock linker:dispatch:{user}:{instance} (60 s lease, 3 s wait) → can't get it → service "操作忙碌中" (busy)
→ read the instance: missing, expired, alias mismatch (including someone else's uuid) → 409 expired
→ rev mismatch → 409 conflict, with the server's rev
→ serde restores the struct (failure → expired) → booted() → referer → METHODS → call()
→ success: rev + 1, save the state, renew → 200 { ok, data, pipeline, instance, rev }
→ validation failure: state unchanged, rev unchanged, renew
→ other failures: state unchanged, rev unchangedrun_stateful saves the struct back only when the call succeeds. If call changes fields and then returns validation or policy, those changes are thrown away. That's a good thing: a failure never leaves half-updated state.
How to choose
Does this component need to remember the result of the last call?
├─ No → Stateless
└─ Yes → Must that memory survive a reload?
├─ Yes → write a draft row in the DB (the component can be Stateless)
└─ No → Must the server block skipped steps?
├─ Yes → Stateful
└─ No → client state is enough; submit once at the endExample: in A multi-step wizard, option A is Stateful and option B can be Stateless.
Deploying Stateful
Instances live in Laravel's cache (by default the database cache table, DB_CACHE_TABLE).
- Clearing the cache clears in-progress forms too.
- When scaling horizontally, every node must share the same cache store, and the locks must be shared too.
- After you change the struct's fields, old instances fail to deserialize and return
expired; the user just reloads. Giving new fields#[serde(default)]lets old instances keep working.