simple-state-model-s3
v0.1.3
Published
Simple State Model — S3 provider: holds states in memory, writes changed states to objects on an interval, and reads an object again once its read has gone stale
Readme
simple-state-model-s3
A simple-state-model provider that keeps states in memory and uses objects in a bucket for
durability.
Reads and patches stay synchronous — the in-memory behaviour is identical to the built-in
InMemoryKeyedStateProvider. The bucket is used for three things:
- hydration — the first
load()of a key reads its object; later loads are served from memory - writing back — keys changed since the last tick are written on a fixed interval
- reading back — a key whose last read is older than the read interval is read again before it is served, and the difference is applied as a patch, so existing subscribers just see an ordinary minimal patch
The caching, the intervals and the read-back are all
CachedKeyedStateProvider in
simple-state-model; this package is the bucket. It is the sibling of
simple-state-model-postgres, and differs from it in one way that matters: a bucket announces
nothing. Postgres can say "this row changed" over LISTEN/NOTIFY; nothing calls back to say an
object was written. The read interval is what finds out, and it is the only thing that notices a
write this process did not make — by a data pipeline, by another instance, or by hand. Without it a
state held in memory stands as the truth for as long as the process runs: served to readers,
patched, and written back over whatever had really been there.
Install
npm install simple-state-model-s3 @aws-sdk/client-s3@aws-sdk/client-s3 is a peer dependency, so the host application controls the SDK version.
Usage
import { StateModel } from "simple-state-model";
import { S3StateProvider } from "simple-state-model-s3";
const stateProvider = new S3StateProvider({
bucket: "states.example.com",
prefix: "states/",
connection: { region: "us-east-1" },
readInterval: 5000,
writeInterval: 10000,
logger: console
});
const stateModel = new StateModel({
providers: { s3: stateProvider },
defaultProviderID: "s3"
});
const stateController = await stateModel.load(undefined, { id: "element-1" });
stateController.patch([{ op: "add", path: "/title", value: "Hello" }]);
// on shutdown: writes outstanding changes, then releases the client
await stateProvider.close();The two intervals
Think of them as a debounce in each direction.
writeInterval — a patch applies in memory and returns; the object is written at most this
often. A write is the whole object however small the change, so a state being typed into would
otherwise be one upload per keystroke. A caller that needs the bucket to be current now rather
than eventually — a shutdown, or a hand-off to something that reads the object itself — calls
flush() and waits for it.
readInterval — a read of a key is good for this long. Inside it, loads are answered from
memory; past it, the next load reads the object again first. Reading is the cheaper of the two and
the one a stale answer is felt through, so it is the shorter of the pair by default.
They meet at one rule: a state holding changes that have not been written yet is ahead of the bucket, not behind it, so it is written out before it is read back. An external change is never merged with an unwritten local one — whole-object writes are last-writer-wins and a merge would be inventing a third value — but it is never the unwritten local change that is dropped, because that is the one somebody is looking at and believes they made.
Options
| Option | Default | Meaning |
| --- | --- | --- |
| bucket | — | Bucket holding the objects, for the default location. |
| prefix | "" | Key prefix within the bucket, for the default location. |
| suffix | .json | Key suffix, for the default location. |
| connection | — | { region, endpoint, credentials, forcePathStyle }. Omit credentials to use the ambient chain. |
| client | — | An already-built S3Client to use instead of connecting. |
| location | — | key => { bucket, path, client? }. See below. |
| serialize | JSON | value => contents written into the object. |
| deserialize | JSON | contents => value read out of it. |
| writeOnCreate | false | Write an object for a key that has none. Off by default: a read should not leave anything behind in the bucket. |
| create | true | Serve an empty state for a key with no object. false rejects unknown IDs. |
| readInterval | 5000 | Milliseconds a read stays good for. 0 never re-reads. |
| writeInterval | 10000 | Milliseconds between writes. 0 disables the timer — call flush() yourself. |
| contentType | application/json | Content type written with the object. |
Buckets laid out by somebody else
A bucket is rarely arranged for the convenience of whatever is reading it, so two things are replaceable.
location maps a key to wherever its object actually lives, and may name a client of its own,
so one provider can serve keys spread across buckets that are not reached the same way:
location: (key) => datapages[key] // => { bucket, path, client? }A provider given a location builds no client of its own, since there is nothing to configure one
from, so a location either returns a client or the provider is also given one.
serialize / deserialize put the value inside a document whose shape belongs to its other
readers — an envelope, say, where the value sits under data beside a stamp for whoever opens the
file:
serialize: (value) => JSON.stringify({ modified: new Date().toISOString(), data: value }, null, 2),
deserialize: (parsed) => parsed?.data ?? {}Missing objects, and failed reads
A key with no object is an empty state, and nothing is written for it until something changes it. Every other read failure — no such bucket, no credentials, a network fault, a body that is not readable JSON — is the read not answering, which is not the same as an answer of nothing, and is reported rather than served as empty. A failure that way leaves the value already held in memory in place, which is the last thing the bucket is known to have given; the next load tries again.
Stamps
Objects are recognised by their ETag rather than by LastModified, because a write returns one
and not the other, and the provider has to be able to tell its own write from somebody else's
without reading the object back.
Config variant
S3ConfigProvider is the same thing for ConfigControllers. A ConfigController has no mutation
queue, so external changes arrive as setValue() rather than as a patch; the cache handles both, so
the provider is nothing but the choice of controller class.
Testing
The tests run against an in-memory stand-in for the bucket, so no bucket and no credentials are needed:
npm test