Expire sessions with a Cache
Resolve a session token to its user for a bounded lifetime, expiring entries automatically without writing a sweep, and report how many sessions are currently live.
commons tokens
---A session token — an opaque, bounded handle that addresses a cache entry. It isnon-empty and length-capped, so a malformed token is rejected at the boundarybefore any cache lookup runs.---type Token = String where NonEmpty && MaxLength(128)
---The authenticated user a live token resolves to.---type UserId = String where NonEmptycontext sessions
uses tokensconsumes bynk { Clock, Cookie, Random }
type LoginRequest = { user: UserId,}
---The cookies a request carries. `sid` is the session token, read from the`__Host-sid` cookie: a hyphen cannot be part of a field name, so `@name` gives thefield the wire name the browser sends. The router decodes and validates it before thehandler runs, so a malformed token never reaches the cache. A missing cookie is `None`.---type SessionCookies = { @name("__Host-sid") sid: Option[Token],}
---A shard of live sessions (a Cloudflare Durable Object). State is a `Cache` — a`Map` whose entries expire on their own. `@ttl(30.minutes)` sets the lifetime:each `put` (re)starts the 30-minute clock, an entry past its TTL reads as `None`,and expired entries are reaped at the next commit.
Eviction consults the clock, so every cache op *except* `remove` declares`given Clock` — the time dependency is visible in the signature.---agent Sessions { key shard: String
store live: Cache[Token, UserId] @ttl(30.minutes)
// start or refresh a session; stamps a fresh 30-minute expiry on call login(token: Token, user: UserId) -> Effect[()] given Clock { do live.put(token, user) }
// resolve a token to its user, or None if unknown or expired on call whoami(token: Token) -> Effect[Option[UserId]] given Clock { live.get(token) }
// end a session now; `remove` is idempotent and needs no clock on call logout(token: Token) -> Effect[()] { do live.remove(token) }
// how many sessions are currently live (expired entries are not counted) on call active() -> Effect[Int] given Clock { live.size() }}
service api from http { // Log in: mint an unguessable token, store the session under it, and hand it // to the browser in a `__Host-` cookie (`Secure`, `HttpOnly` and `SameSite=Lax` // by default, bound to this origin by the prefix: the compiler checks `secure`, // `path: "/"` and no `domain`). on POST("/sessions") ( body: LoginRequest ) -> Effect[HttpResult[String]] by Visitor given Random { let raw <- Random.bytes(16) let text = raw.toBase64Url() match Token.of(text) { Ok(token) => { do Sessions("default").login(token, body.user) Created("ok").withCookie(Cookie { ...SessionCookies.sid.cookie(token), maxAge: Some(30.minutes), }) }, Err(_) => ServerError("could not mint a session token"), } }
// Who am I? The session cookie names the live session; the typed `cookies` // record has already checked it is a `Token` (a malformed one is a `400`). on GET("/me") (cookies: SessionCookies) -> Effect[HttpResult[UserId]] by Visitor { match cookies.sid { None => Unauthorized, Some(token) => { let who <- Sessions("default").whoami(token) match who { Some(user) => Ok(user), None => Unauthorized, } }, } }
// Log out: end the session and clear the cookie. This handler reads the raw // `RequestCookies` view, not the typed record: a typed `cookies` record rejects a // malformed `__Host-sid` with a `400` before the handler runs, and logout must still // clear such a cookie, whatever it holds. on POST("/logout") (cookies: RequestCookies) -> Effect[HttpResult[String]] by Visitor { match cookies.get("__Host-sid") { None => NoContent, Some(raw) => match Token.of(raw) { Ok(token) => { do Sessions("default").logout(token) NoContent.withCookie(SessionCookies.sid.expire()) }, Err(_) => NoContent.withCookie(SessionCookies.sid.expire()), }, } }
on GET("/sessions") () -> Effect[HttpResult[Int]] by Visitor { let n <- Sessions("default").active() Ok(n) }}This example reaches Workers-only shapes (storage bindings, agents, or cron), so it runs with bynk dev rather than in the browser playground. See Install to get started.
How it works
Section titled “How it works”agent Sessions is keyed by a shard string and holds one store:
live: Cache[Token, UserId] @ttl(30.minutes). A Cache is a Map whose entries
expire on their own — each put (re)starts the 30-minute clock, an entry past its
TTL reads as None, and expired entries are reaped at the next commit, so size
counts only live entries with no separate sweep to write. The boundary types are
refined in commons tokens: Token is NonEmpty && MaxLength(128), UserId is
NonEmpty, so a malformed token is rejected before any cache lookup.
Time is honest. Eviction consults the clock, so every cache operation except
remove declares given Clock — login, whoami, and active all carry it,
while logout (an idempotent live.remove) does not. The dependency is visible in
each signature, and a mocked clock would make expiry deterministic.
The session travels in a cookie. POST /sessions mints an unguessable token with
Random.bytes(16).toBase64Url(), starts the session under it, and answers
Created("ok").withCookie(Cookie { name: "__Host-sid", value: text, maxAge: Some(30.minutes) }).
A Cookie’s defaults are the safe ones: Secure, HttpOnly, SameSite=Lax and Path=/,
and the __Host- prefix, which binds the cookie to this origin, is checked at compile time.
GET /me reads it back through a typed cookies: SessionCookies record whose field is
@name("__Host-sid") sid: Option[Token] (a hyphenated name cannot be a field name, so @name
gives the field the key the browser sends), so a malformed value is refused with a 400 by the
Token refinement before the handler runs. POST /logout reads the raw cookies: RequestCookies
view instead, so it clears the cookie whatever it holds, even a value the typed record would
refuse. Whoami answers
Unauthorized for an unknown or expired token, and logout ends the session and clears the
cookie with clearCookie. GET /sessions still reports the live count.