Skip to content

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 forWizards, drafts, flow guards across callsServer-side computation, queries, one-off commands
Mount dataalias + uuid + revalias + a signed URL with an expiry
StateStored in the cache (linker:{user}:{uuid}), restored before each callNot stored; each call builds a fresh C::default()
EndpointPOST /{prefix}/linkerPOST /{prefix}/linker/stateless/{alias}/call?user=…&absolute_expires_at=…&expires=…&signature=…
Request{component, instance, rev, method, args}{method, args}
Response also carriesinstance, revThe renewed url
Mount parametersYes (mount(&mut self, ctx, params))Not accepted (mount with parameters returns an error)
ConcurrencyLocked per instance; an old rev gets conflictThe same URL can run in parallel; correctness comes from DB transactions, unique constraints, idempotency
ReloadA brand new instance; state not saved to the DB is goneA brand new URL
Struct fieldsSaved backThrown away when the call ends

Switching to Stateless ​

rust
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 METHODS are all still checked, and business permissions are still yours to check in call.
  • A different user (the signed user ≠ the logged-in user) or a tampered URL gets 403 policy.

Lifetimes ​

IdleRenewalMaximum
Stateful instances30 minutes (store::IDLE)On successful calls; on validation failures at most every 90 seconds (RENEW_INTERVAL)8 hours (MAX_LIFETIME)
Stateless URLs30 minutesA new URL is returned on success or validation failure8 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 unchanged

run_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 end

Example: 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.

See Deployment and operations.