Skip to content

SessionCache

SessionCache holds the small lists that get recomputed many times while serving one request — the teams a user belongs to, the ids they are allowed to see. It is deliberately narrow: two value types, a short TTL, and invalidation by user.

For a general-purpose cache with a lazy getter, use TimedCache instead.

import crate.collection.sessionCache;
auto cache = SessionCache.instance;
if (!cache.existsId(key)) {
cache.storeId(key, computeVisibleIds());
}
auto ids = cache.getId(key);
this(Duration ttl = 10.seconds);

SessionCache.instance is a process-wide instance created at module construction with the default 10-second TTL. Construct your own when you need a different lifetime.

The TTL is short by design. This is a cache for the span of a request, or a burst of them — not a place to keep data that must stay fresh across a mutation you did not route through invalidateUser.

Two value types are supported, each with its own set of methods. There is no generic accessor.

String listsObjectId listsBehavior
exists(key)existsId(key)true while a non-expired entry is present; an expired entry is dropped and false returned
get(key)getId(key)The stored value
store(key, value)storeId(key, value)Stores the value with now + ttl as its expiry

get and getId do not check expiry and throw on a missing key — always guard them with exists or existsId.

cache.invalidateUser(userId);
cache.invalidatePublicTeams();

invalidateUser drops every entry, of either type, whose key starts with <userId>. — so key your per-user entries as userId ~ ".something" and one call clears all of them. invalidatePublicTeams drops the single public.team entry.

Call invalidateUser after any change to what a user may see. Without it the stale answer survives for up to the TTL.

Storing runs a cleanup pass, but only once the map holds more than 5000 entries; below that, expired entries stay in memory until something overwrites or invalidates them. The pass removes expired entries only — a cache full of live entries keeps growing.