Examples
Stow is lightweight S3-compatible storage for tests, local applications and processing pipelines. These examples start with a disposable bucket and grow, one change at a time, into storage that survives a restart and can be replayed.
Every example runs against a real S3 client. The Stow-specific part is small: a session starts a private loopback server, hands back an ordinary client, and cleans up. The application code that stores and reads objects does not change between examples.
Install for an application
The TypeScript package is available on public npmjs with its native binary:
npm install @chester-hill-solutions/stow-s3@0.4.4 @aws-sdk/client-s3Linux and macOS on x64 or ARM64 need no Go build or STOW_BIN setting.
The Python client is not yet published to PyPI.
Run this checkout's examples
The repository examples use the local TypeScript package so they exercise the same source revision. Build that source once:
git clone https://github.com/chester-hill-solutions/stow-s3
cd stow-s3
make build
export STOW_BIN="$PWD/bin/stow-s3"The TypeScript examples import the AWS SDK and the local client. Install both once:
npm ci --ignore-scripts --omit=optional --prefix packages/stow-s3
npm run build --prefix packages/stow-s3
npm install --prefix examples/stow-recipesFor Python:
python -m venv .venv
. .venv/bin/activate
pip install -e "packages/stow-s3-py[boto3]"STOW_BIN selects the source-built server for these repository examples.
Applications using the published npm package receive their native binary automatically.
1. Start small
A session is a private, loopback S3 endpoint with generated credentials and a generated bucket. The callback form cleans up the server and its temporary data when it returns, even if the callback throws.
// Store an artifact in a disposable S3 bucket and read it back.
//
// make build
// STOW_BIN=./bin/stow-s3 node examples/stow-recipes/start-small.mjs
//
// The application code takes an S3 client and a bucket and does not know Stow
// exists. Only the last block is Stow-specific: it runs that code against a
// private session and cleans it up.
// #region example
import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { withStow } from "@chester-hill-solutions/stow-s3";
// Ordinary application code: any S3 client and bucket will do.
async function publishReport(s3, bucket, report) {
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: "reports/latest.json",
Body: JSON.stringify(report),
ContentType: "application/json",
}));
const stored = await s3.send(new GetObjectCommand({
Bucket: bucket,
Key: "reports/latest.json",
}));
return JSON.parse(await stored.Body.transformToString());
}
const report = { service: "checkout", ok: true, durationMs: 128 };
// Stow: a private bucket, generated credentials, cleanup on exit.
await withStow(async ({ s3, bucket }) => {
const roundTripped = await publishReport(s3, bucket, report);
console.log("stored reports/latest.json:", JSON.stringify(roundTripped));
});
// #endregion example"""Store an artifact in a disposable S3 bucket and read it back.
make build
export STOW_BIN="$PWD/bin/stow-s3"
python examples/stow-recipes/start_small.py
The application code takes an S3 client and a bucket and does not know Stow
exists. Only the ``with_session`` block is Stow-specific. A Python session
starts a private loopback server and cleans it up; it does not create a bucket,
so the example names one and creates it.
"""
import json
from stow_s3 import with_session
def publish_report(s3, bucket, report):
"""Ordinary application code: any S3 client and bucket will do."""
s3.put_object(
Bucket=bucket,
Key="reports/latest.json",
Body=json.dumps(report).encode(),
ContentType="application/json",
)
response = s3.get_object(Bucket=bucket, Key="reports/latest.json")
try:
return json.loads(response["Body"].read())
finally:
response["Body"].close()
report = {"service": "checkout", "ok": True, "duration_ms": 128}
with with_session() as session:
s3 = session.s3_client()
bucket = session.new_bucket_name()
s3.create_bucket(Bucket=bucket)
print("stored reports/latest.json:", json.dumps(publish_report(s3, bucket, report)))
s3.close()Only the last block is Stow-specific. publishReport takes an S3 client and a
bucket, so the same function runs against a real bucket, a test session, or a
local pipeline. TypeScript's session creates the bucket and exposes it as
session.bucket; Python's session creates no bucket, so the example names one
with session.new_bucket_name() and creates it.
A session starts a separate server process, not an in-process client. It is
isolated from your STOW_*, S3_* and AWS_* environment, it cannot outlive
your process, and it is bounded (16 MiB and 1,000 objects by default). Read your
instance's capabilities rather than assuming a limit.
2. Keep the artifacts
Name a data directory and the objects outlive the session. The directory is yours: the server stops, but the bytes stay, and the next session on the same directory reads them.
// Keep the artifacts: the same round trip, but the objects outlive the session.
//
// make build
// STOW_BIN=./bin/stow-s3 node examples/stow-recipes/keep-artifacts.mjs ./artifacts
//
// The only change from start-small.mjs is naming a data directory and a bucket:
// withStow(...) becomes openStow({ dataDir, bucket }). A named directory selects
// the filesystem backend, so the bytes survive close, and a fixed bucket name
// lets the next session find them.
import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { openStow } from "@chester-hill-solutions/stow-s3";
const dataDir = process.argv[2] ?? "./artifacts";
const bucket = "artifacts";
// First session: write the artifact, then stop the server.
const first = await openStow({ dataDir, bucket });
await first.s3.send(new PutObjectCommand({
Bucket: bucket,
Key: "notes/design.md",
Body: "# Design\n\nFirst draft.\n",
ContentType: "text/markdown",
}));
await first.close();
console.log(`wrote ${bucket}/notes/design.md; server stopped`);
// Second session on the same directory: the caller-owned data is still there.
const second = await openStow({ dataDir, bucket });
const stored = await second.s3.send(new GetObjectCommand({
Bucket: bucket,
Key: "notes/design.md",
}));
console.log("read back after reopen:", JSON.stringify(await stored.Body.transformToString()));
await second.close();"""Keep the artifacts: the same round trip, but the objects outlive the session.
make build
export STOW_BIN="$PWD/bin/stow-s3"
python examples/stow-recipes/keep_artifacts.py ./artifacts
The only change from start_small.py is passing ``data_dir``. A named directory
selects the filesystem backend, so the bytes survive close, and the caller's
directory is left in place for the next session.
"""
import sys
from pathlib import Path
from stow_s3 import with_session
data_dir = Path(sys.argv[1] if len(sys.argv) > 1 else "./artifacts")
bucket = "artifacts"
with with_session(data_dir=data_dir) as session:
s3 = session.s3_client()
s3.create_bucket(Bucket=bucket)
s3.put_object(
Bucket=bucket,
Key="notes/design.md",
Body=b"# Design\n\nFirst draft.\n",
ContentType="text/markdown",
)
s3.close()
print(f"wrote {bucket}/notes/design.md; server stopped")
with with_session(data_dir=data_dir) as reopened:
s3 = reopened.s3_client()
response = s3.get_object(Bucket=bucket, Key="notes/design.md")
try:
print("read back after reopen:", response["Body"].read().decode())
finally:
response["Body"].close()
s3.close()The change from the first example is one option. A named directory selects the
filesystem backend; a session with no directory stays memory-backed and
disposable. Because the TypeScript session generates a bucket name per session,
the example also passes a fixed bucket so the reopened session finds the
objects it wrote.
3. Re-run a processing stage
A stage reads input objects by key and writes derived results. Retaining both means you can inspect a result, add documents, and run the stage again.
// A classify stage: workers read input objects and write category results.
//
// make build
// STOW_BIN=./bin/stow-s3 node examples/stow-recipes/processing-stage.mjs ./pipeline
//
// Inputs and results are retained, so the stage can be rerun after adding
// documents. Stow stores the bytes; the application owns the queue, the
// scheduling and the retries. This is not a durable job queue and does not
// promise exactly-once processing: if a worker is interrupted, rerun the key.
import { GetObjectCommand, ListObjectsV2Command, PutObjectCommand } from "@aws-sdk/client-s3";
import { openStow } from "@chester-hill-solutions/stow-s3";
const dataDir = process.argv[2] ?? "./pipeline";
const bucket = "pipeline";
const inputs = {
"invoices/march.txt": "Invoice 1001 for March services.",
"invoices/april.txt": "Invoice 1002 for April services.",
"support/tickets.txt": "Support ticket: cannot sign in.",
};
// Stands in for a real classifier.
function categorize(text) {
return /\binvoice\b/i.test(text) ? "invoice" : "support";
}
// #region excerpt
// One unit of work: read an input key, write its result under results/.
async function classifyOne(s3, key) {
const source = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: `inputs/${key}` }));
const category = categorize(await source.Body.transformToString());
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: `results/${key}.json`,
Body: JSON.stringify({ input: key, category }),
ContentType: "application/json",
}));
return `${key} -> ${category}`;
}
// The application builds the queue and runs two workers over it. Stow does not
// schedule this or retry it; if a worker fails, the application retries the key.
async function runWorkers(s3, keys) {
const queue = [...keys];
const worker = async () => {
for (let key = queue.shift(); key !== undefined; key = queue.shift()) {
console.log(await classifyOne(s3, key));
}
};
await Promise.all([worker(), worker()]);
}
// #endregion excerpt
const session = await openStow({ dataDir, bucket });
try {
const s3 = session.s3;
// Seed the inputs. Rerunning overwrites the same keys, so it is idempotent.
for (const [key, text] of Object.entries(inputs)) {
await s3.send(new PutObjectCommand({ Bucket: bucket, Key: `inputs/${key}`, Body: text, ContentType: "text/plain" }));
}
await runWorkers(s3, Object.keys(inputs));
// Inputs and results are retained, so the stage can be inspected or rerun.
const results = await s3.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: "results/" }));
console.log("retained results:", (results.Contents ?? []).map((object) => object.Key).sort());
} finally {
await session.close();
}"""A classify stage: workers read input objects and write category results.
make build
export STOW_BIN="$PWD/bin/stow-s3"
python examples/stow-recipes/processing_stage.py ./pipeline
Inputs and results are retained, so the stage can be rerun after adding
documents. Stow stores the bytes; the application owns the queue, the
scheduling and the retries. This is not a durable job queue and does not promise
exactly-once processing: if a worker is interrupted, rerun the key.
"""
import json
import re
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from stow_s3 import with_session
data_dir = Path(sys.argv[1] if len(sys.argv) > 1 else "./pipeline")
bucket = "pipeline"
inputs = {
"invoices/march.txt": "Invoice 1001 for March services.",
"invoices/april.txt": "Invoice 1002 for April services.",
"support/tickets.txt": "Support ticket: cannot sign in.",
}
def categorize(text):
"""Stands in for a real classifier."""
return "invoice" if re.search(r"\binvoice\b", text, re.IGNORECASE) else "support"
# #region excerpt
def classify_one(s3, key):
"""One unit of work: read an input key, write its result under results/."""
response = s3.get_object(Bucket=bucket, Key=f"inputs/{key}")
try:
source = response["Body"].read()
finally:
response["Body"].close()
category = categorize(source.decode())
s3.put_object(
Bucket=bucket,
Key=f"results/{key}.json",
Body=json.dumps({"input": key, "category": category}).encode(),
ContentType="application/json",
)
return f"{key} -> {category}"
def run_workers(s3, keys):
"""The application builds the queue and runs two workers over it.
Stow does not schedule this or retry it; if a worker fails, the application
retries the key.
"""
queue = list(keys)
with ThreadPoolExecutor(max_workers=2) as pool:
for message in pool.map(lambda key: classify_one(s3, key), queue):
print(message)
# #endregion excerpt
with with_session(data_dir=data_dir) as session:
s3 = session.s3_client()
s3.create_bucket(Bucket=bucket)
# Seed the inputs. Rerunning overwrites the same keys, so it is idempotent.
for key, text in inputs.items():
s3.put_object(Bucket=bucket, Key=f"inputs/{key}", Body=text.encode(), ContentType="text/plain")
run_workers(s3, list(inputs))
# Inputs and results are retained, so the stage can be inspected or rerun.
retained = s3.list_objects_v2(Bucket=bucket, Prefix="results/")
print("retained results:", sorted(item["Key"] for item in retained.get("Contents", [])))
s3.close()Stow stores the inputs and the results. Your application owns the queue, decides what runs and when, and retries what fails. Stow is not a durable job queue and does not promise exactly-once processing: if a worker is interrupted, the application reruns that key, and a rerun overwrites the same result.
4. Reject a stale update
A conditional write compares the ETag you pass with the object's current ETag and refuses the write if they differ, so two writers cannot silently clobber one another.
// Reject a stale update: overwrite only the version you actually read.
//
// make build
// STOW_BIN=./bin/stow-s3 node examples/stow-recipes/conditional-write.mjs
//
// A conditional write compares the object's current ETag with the one you pass
// and refuses the write if they differ. Two writers can read the same version;
// the second update is rejected instead of silently overwriting the first.
import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { withStow } from "@chester-hill-solutions/stow-s3";
await withStow(async ({ s3, bucket }) => {
const created = await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: "config.json",
Body: '{"version":1}',
}));
// The first writer updates the version it read.
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: "config.json",
Body: '{"version":2}',
IfMatch: created.ETag,
}));
// The second writer still holds the original ETag, so its update is refused.
// The refusal has to be the precondition failure and not some other error:
// a request that failed for another reason has proved nothing about the
// write it was supposed to make.
let rejection;
try {
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: "config.json",
Body: '{"version":3}',
IfMatch: created.ETag,
}));
} catch (error) {
rejection = error;
}
if (!rejection) throw new Error("the stale update was accepted");
if (rejection.name !== "PreconditionFailed" && rejection.$metadata?.httpStatusCode !== 412) {
throw rejection;
}
console.log("stale update rejected:", rejection.name, rejection.$metadata?.httpStatusCode);
// The version that was saved is still the one that is stored. A refusal is
// only worth anything if the object it refused to replace is intact.
const stored = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: "config.json" }));
const retained = await stored.Body.transformToString();
if (retained !== '{"version":2}') {
throw new Error(`the stored object is ${retained}, want the version that was saved`);
}
console.log("retained:", retained);
});"""Reject a stale update: overwrite only the version you actually read.
make build
export STOW_BIN="$PWD/bin/stow-s3"
python examples/stow-recipes/conditional_write.py
A conditional write compares the object's current ETag with the one you pass
and refuses the write if they differ. Two writers can read the same version; the
second update is rejected instead of silently overwriting the first.
"""
from botocore.exceptions import ClientError
from stow_s3 import with_session
with with_session() as session:
s3 = session.s3_client()
bucket = session.new_bucket_name()
s3.create_bucket(Bucket=bucket)
created = s3.put_object(Bucket=bucket, Key="config.json", Body=b'{"version":1}')
# The first writer updates the version it read.
s3.put_object(Bucket=bucket, Key="config.json", Body=b'{"version":2}', IfMatch=created["ETag"])
# The second writer still holds the original ETag, so its update is refused.
# The refusal has to be the precondition failure and not some other error:
# a request that failed for another reason has proved nothing about the
# write it was supposed to make.
try:
s3.put_object(Bucket=bucket, Key="config.json", Body=b'{"version":3}', IfMatch=created["ETag"])
except ClientError as error:
code = error.response["Error"]["Code"]
status = error.response["ResponseMetadata"]["HTTPStatusCode"]
if code != "PreconditionFailed" and status != 412:
raise
print("stale update rejected:", code, status)
else:
raise AssertionError("the stale update was accepted")
# The version that was saved is still the one that is stored. A refusal is
# only worth anything if the object it refused to replace is intact.
retained = s3.get_object(Bucket=bucket, Key="config.json")
try:
body = retained["Body"].read().decode()
finally:
retained["Body"].close()
if body != '{"version":2}':
raise AssertionError(f"the stored object is {body}, want the version that was saved")
print("retained:", body)
s3.close()The refused update returns 412 PreconditionFailed and leaves the successful
version in place. This is an ordinary S3 conditional write; it needs no Stow
extension.
Run the examples
Each example is a complete, runnable file:
| Example | File |
|---|---|
| Start small (TypeScript) | start-small.mjs |
| Start small (Python) | start_small.py |
| Keep the artifacts (TypeScript) | keep-artifacts.mjs |
| Keep the artifacts (Python) | keep_artifacts.py |
| Re-run a stage (TypeScript) | processing-stage.mjs |
| Re-run a stage (Python) | processing_stage.py |
| Reject a stale update (TypeScript) | conditional-write.mjs |
| Reject a stale update (Python) | conditional_write.py |
Go uses the embedded object runtime instead of a server. It stores and reads objects in process with no HTTP endpoint, so it is the right surface only when the application is written in Go:
// Store a report in an embedded object runtime and read it back.
//
// go run ./examples/stow-recipes/go/start-small
//
// This is the embedded Go runtime: it stores objects in process with no HTTP
// server and no S3 client. Use a scoped TypeScript or Python session when the
// application already speaks S3.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
stow "github.com/chester-hill-solutions/stow-s3/pkg/stow"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
ctx := context.Background()
store, err := stow.Open(stow.Options{Backend: stow.BackendMemory})
if err != nil {
return err
}
defer store.Close()
if err := store.CreateBucket(ctx, "reports"); err != nil {
return err
}
report := map[string]any{"service": "checkout", "ok": true, "durationMs": 128}
body, err := json.Marshal(report)
if err != nil {
return err
}
if _, err := store.PutObject(ctx, "reports", "latest.json", body, stow.PutOptions{ContentType: "application/json"}); err != nil {
return err
}
object, err := store.GetObject(ctx, "reports", "latest.json")
if err != nil {
return err
}
fmt.Println("stored reports/latest.json:", string(object.Data))
return nil
}Next: the getting started guide, the TypeScript client and the Python client.