The Game Panel Design record
The Game Panel
RFC-0014 Proposed

Sessions

Comparing
v1 to v2
Current
Read the document

Abstract

We I will add server-side sessions, keyed by a cookie and stored in the database, with flash state carrying one a value from the request that writes it to the request that follows. A session will be resolved once per cycle, loaded only when something reads it, and written only when something changedchanged it. The cookie The cookie will be set on the response during the request, and the record persisted when the cycle closes.

Motivation

A server-rendered panel needs to remember who is using it between requests, and to carry a message across the redirect that follows a form submission. Neither is possible with the request alone.

Sessions will be a component of their own component rather than part of the HTTP layer. They will own a table, a store, an expiry an expiry policy and a pruning task, none of which is transport. What is HTTP-facing faces HTTP will be thin: reading a cookie, and writing and writing one onto a response.

Proposal

StorageWhere a session lives

A session will live in the database, and the its cookie will carry nothing but an identifier. We I rejected a a self-contained contained cookie holding the session's data: it would save a read on every request, but it cannot be revoked. . Suspending someone, , or forcing them out, has to invalidate a live session, and a cookie that carries its own data data stays valid until it it expires.

SessionStore will be the contract for loading, persisting and removing records, and the . The database implementation will be will be the one that existsonly one, named as the entity stores in RFC-0013 are.

The A record will hold:

Field Purpose
Identifier Names the record, and is what the cookie carries.
Payload What the session holds.
Created, last seen When it began, and when it was last used.
Client address Stored truncated, per ADR-0022.
User agent As sent by the clientclient sent it.
Expiry When it lapses, whether by age or by idleness.

The address and user agent will be recorded so that a person someone reading the table, or a page listing their a person's own sessions, can tell one session from another. Neither will be used to decide whether a session is valid: binding a session to an to an address signs out anyone whose network changes, and binding it to a user agent breaks it on a browser update.

Identifiers

A session identifier will be 32 random bytes, hex encoded. It will not be an an entity entity identifier: those . Those are ULIDs, as ADR-0011 recordsdecides, which embed and a ULID embeds a timestamp and a counter and are therefore guessable counter, so one can be guessed from a known oneanother. A session identifier is a bearer credential, so it has to be unguessable.

The identifier will be regenerated whenever privilege changes, which means : on signing in in, and on any elevation. Regenerating will write a new record and keep the old one for a short, configurable window as a superseded record pointing at the new one. A request already in flight with the old identifier will then resolve to the new record, rather than failing or loading a stale copy of the session that it would write back when it ends. Superseded records will be removed by the same pruning that removes expired ones.

Regenerating will write a new record and mark the old one as a superseded record, pointing at the new one, for a short configurable window. A request already in flight carrying the old identifier will resolve to the new record rather than to a stale copy of the session, which is what would otherwise be written back when that request ends. Superseded records will be removed by the same pruning that removes expired ones.

Lifetime and loading

Loading and writing

A session will have the Cycle lifetime from RFC-0007, so it will be resolved once per request and discarded when the cycle closes.

Loading will be lazy, lazy and writing conditional:. A request that never touches the session will read nothing, and a session that nothing changed will write nothing.

  • A request that never touches the session will read nothing.
  • A session nothing changed will write nothing.

When a session does write, it will write twice, at different moments. The cookie will be written on the response, during the request, because the response is emitted before the cycle closes. The record will be written when the cycle closes. The client already has its response by then, so persisting will cost it nothing.

Persisting Nothing will lock a session. A hypermedia page loads several fragments at cycle close once, so requests for one session arrive concurrently. PHP's own session handling serialises them by locking, which would load those fragments one after another. The last write will be the disposal described in RFC-0007win instead, which is why a session will hold little and change rarely.

Concurrency

Nothing will lock a session. A hypermedia page loads several fragments at once, so requests for one session arrive concurrently. PHP's own session handling serialises them by locking, which would make those fragments load one after another. The last write will win instead, which is why a session will hold little and change rarely.

Flash A session will be the exception, and hold two types of state by key. Ordinary state will carry a hazardpersist until something changes it: two concurrent requests can each read put() will hold a flash value before either clears value, get() will return it, or one can clear it before the other reads and forget() will drop it. Flash state will be written by live for exactly the next request: a value held with flash() during one request that redirects will be readable in the next and is meant for gone after that, which is what carries a message across the document request redirect that followsfollows a form submission. get() will return a default when there is no value, null unless one is given, so and pull() will return a fragment request must not consume itvalue, or a default when there is none, and drop it in one step.

The session

Session will read, write and discard the session's data:

Method Effect
get(string $key, mixed $default = null): mixed The value held, or the default.
put(string $key, mixed $value): void Holds the value.
forget(string $key): void Drops the value.
flash(string $key, mixed $value): void Holds the value for the next request only.
pull(string $key, mixed $default = null): mixed Returns the value and drops it.
regenerate(): void Issues a new identifier, superseding the old record.
invalidate(): void Removes the record and clears the cookie.

A flash value written during one request will be readable in the next, and gone after it.

A session that does write will write twice, at different moments. The cookie will be set on the response during the request, because the response is emitted before the cycle closes. The record will be persisted when the cycle closes, as the disposal that RFC-0007 describes. The client already has its response by then, so persisting costs it nothing.

Concurrent requests

Flash will be the exception, and carries a hazard: two concurrent requests can each read a flash value before either clears it, or one can clear it before the other reads it. Flash will be written by the request that redirects and is meant for the document request that follows, so a fragment request must not consume it.

Using a session

A session will also manage its own identifier. regenerate() will issue a new one and supersede the old record, as described under Identifiers, and invalidate() will end the session by removing its record and clearing the cookie.

The cookie

The cookie will carry the identifier and nothing else. It will be unavailable to scripts, sent only over a secure connection, scoped to the whole panel, and given no domain, so it is not shared with subdomains. Its name will be configurable.

It will be sent on same-site requests and on inbound navigation arriving from elsewhere, but not on cross-site form form submissions. We . I will not use the stricter setting, which withholds it the cookie on any inbound navigationnavigation arriving from another site, because following a link from an an email would then arrive signed out.

Reaching a session from longer-lived code

The middleware that writes the cookie will have the Process lifetime, as RFC-0010 describes, so taking . Taking a session as a constructor dependency would resolve one on the first request and hold it for the life of the worker.

It will take a provider instead, as RFC-0007 describes, which resolves the session against whichever cycle is open when it is called:

final class WriteSessionCookie implements Middleware
{
    public function __construct(
        #[Provide(Session::class)] private Provider $session,
    ) {}

    public function process(Request $request, Handler $next): Response
    {
        $session = $this->session->get();
        // ...
    }
}

The same applies to anything Anything else that outlives a request and needs the sessionsession will reach it the same way.

Expiry and pruning

A session will carry an absolute expiry and an idle timeout, both configurable. A session past either will be treated as treated as absent, so a request carrying its identifier will start a new one.

SessionConfig will hold the cookie's name, the expiry and idle timeoutabsolute expiry, the idle timeout and the regeneration window.

Expired records, and any every superseded record, will be removed by a scheduled task rather than by work attached to a requestrequests, so no visitor pays for the cleanup. There is no scheduler yet, so the query pruning query will ship with this design and be scheduled when once one exists.

Out of scope

  • Authentication. A session will hold whatever signs someone in in, and give it no meaning of its own.
  • Long-lived re-authentication. That belongs with authentication.
  • Encrypting the payload. It never leaves the server; only the identifier does.
  • Cross-site request forgery. The Its token belongs in the session, but issuing and verifying it is a separate component built on this one.
  • Rate limiting.
  • The schema itself. The table's columns and types are written with the schema builder in RFC-0012.

Alternatives considered

The decision this This design rests on is recorded separatelyADR-0022, with the alternatives it rejected:which stores a client address truncated.

  • storing a client address truncated, in ADR-0022

A self-contained cookieLocking a session for the duration of a request. A signed or encrypted cookie would hold the sessionThis is what PHP's data with no record on the server, saving a read per requestown session handling does. We I rejected this this because it cannot be revoked, so suspending an account leaves its sessions working until they expireserialises the concurrent fragment requests a hypermedia page depends on.

Locking a session for Deleting the duration of a requestold record when regenerating. This is what PHP's own session handling does. We I rejected this this because it serialises the concurrent fragment requests a hypermedia page depends onrequest already in flight would then fail, which is why the old record is kept briefly and marked superseded instead.

Deleting Identifying sessions with the old record when regeneratingentity identifier. We I rejected this because a request already in flight would then failULID embeds a timestamp and a counter, which is why the old record so one is kept briefly guessable from another, and marked superseded insteada session identifier is a bearer credential.

Identifying sessions with the entity identifier. We rejected this because a ULID embeds a timestamp and a counter, so one is guessable from another, and this identifier is a bearer credential.

No other alternatives were weighed.

A self-contained cookie. A signed or encrypted cookie would hold the session's data with no record on the server, saving a read on every request. I rejected this because it cannot be revoked, so suspending an account would leave its sessions working until they expire.

Backwards compatibility

Nothing will break. The panel has no sessions today.

Open questions

  • What tells a session that a request is a document rather than a fragment. Only a document request should consume flash, and this component cannot tell the difference: it is carried in a request header and belongs to the hypermedia layer.

What tells a session that a request is a document rather than a fragment

Only a document request should consume flash, and this component cannot tell the difference: it is carried in a request header and belongs to the hypermedia layer.

Changelog

  • : Reworded in the readable house style, and the project's own vocabulary linked to the glossary. The design is unchanged.
  • : Rewrote the document in full, with no change to the design.

Sources

  • Issue #67, Engine - Sessions, , edited the same day: sessions as their own component and why, the database store and the rejected self-contained cookie, the random identifier and why it is not an entity identifier, regeneration on privilege change with the previous record retained, cycle lifetime with lazy loading, the two writes at their different moments, the absence of locking and the flash hazard, the session's methods, the cookie's attributes and why the looser same-site setting, reaching a session through a provider, expiry and scheduled pruning, and every boundary listed under Out of scope. Its edit split out cross-site request forgery and corrected the cookie write, which the body had said happened at cycle close.
  • Issue #65, Engine - HTTP - Middleware pipeline, : middleware being process lifetime and taking a provider for anything shorter-lived.
  • The superseded record pointing at its replacement so an in-flight request resolves to the new session rather than a stale copy; the window being configurable and cleaned up by the same pruning; and the record carrying created and last-seen timestamps, a truncated client address and the user agent, for reading rather than for validation: first written down on .

Source rfc/0014-sessions.md · commit 9444a99 · published