diff --git a/README.md b/README.md index ba06cf54..92b099bf 100644 --- a/README.md +++ b/README.md @@ -3,109 +3,142 @@ [![npm version](https://img.shields.io/npm/v/dialcache.svg)](https://www.npmjs.com/package/dialcache) [![crates.io](https://img.shields.io/crates/v/dialcache.svg)](https://crates.io/crates/dialcache) [![PyPI version](https://img.shields.io/pypi/v/dialcache.svg)](https://pypi.org/project/dialcache/) -[![TypeScript coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=typescript&label=TypeScript%20coverage)](https://codecov.io/gh/lan17/DialCache) -[![Go coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=go&label=Go%20coverage)](https://codecov.io/gh/lan17/DialCache) -[![Rust coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=rust&label=Rust%20coverage)](https://codecov.io/gh/lan17/DialCache) -[![Python coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=python&label=Python%20coverage)](https://codecov.io/gh/lan17/DialCache) -[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/lan17/DialCache/badge)](https://scorecard.dev/viewer/?uri=github.com/lan17/DialCache) -Read the [shared behavior guides](https://lan17.github.io/DialCache/) with a -language selector and native examples for TypeScript, Go, Rust and Python. +DialCache is a read-through caching library for TypeScript, Go, Rust and Python. +It has three layers: request-local, process-local and Redis. -**TypeScript is the reference implementation. Go, Rust, and Python are experimental.** -The [Python asyncio guide](python/README.md) covers its native decorator API, -request scopes, and checkout installation. +You register each cached read as a use case. Each use case has its own: -DialCache organizes caching into use cases, with runtime control and -observability for each one. Its TypeScript, Go, Rust and Python implementations share -behavioral contracts and documentation. +- **Configuration** — layers, TTLs and rollout ramps, changed at runtime. +- **Metrics** — requests, misses by reason and errors, labeled by use case and layer. +- **Invalidation** — one call per `keyType` and id fences every use case keyed by that id. -- **Off by default:** caching runs only inside an `enable()` scope. -- **Multi-layer:** request-local → process-local → Redis. -- **Runtime policies per use case:** layers, TTLs, and rollout ramps. -- **Targeted invalidation:** one call per entity for its tracked Redis results. -- **Coalescing:** same-key reads share work when a cache layer is active. -- **Fail-open:** cache failures fall back to the loader. -- **Stale-on-error (opt-in):** retained Redis values for selected source errors. -- **Shadow validation (opt-in):** cache coherence checks through sampling. -- **Observability:** Prometheus and Datadog metrics, including miss reasons. +Caching is off until a call runs inside `enable()`. On a cache failure, DialCache +calls the loader. Stale-on-error and shadow validation are opt-in per use case. [Documentation](https://lan17.github.io/DialCache/) · [Getting started](https://lan17.github.io/DialCache/getting-started.html) · [API reference](https://lan17.github.io/DialCache/api.html) -| Language | Implementation | Native guide | -| --- | --- | --- | -| TypeScript | [`typescript/`](typescript/) — reference implementation | [TypeScript and npm](typescript/README.md) | -| Go | [`go/`](go/) — experimental | [Go guide](go/README.md) | -| Rust | [`rust/`](rust/) — experimental | [Rust guide](rust/README.md) · [crates.io](https://crates.io/crates/dialcache) | -| Python | [`python/`](python/) — experimental | [Python guide](python/README.md) · [PyPI](https://pypi.org/project/dialcache/) | - -One [Quint specification](formal/README.md) defines the behavior, and every -implementation is checked against the same histories generated from it. - -## Install TypeScript - -```bash -npm install dialcache -``` + -Requires Node.js 22.15.0 or newer within 22.x, or 23.8.0 and newer, for -`node:zlib` zstd support. Use a -[supported LTS release](https://nodejs.org/en/about/previous-releases) in production. -Install a [Redis or Valkey client](https://lan17.github.io/DialCache/redis.html) -and a [metrics client](https://lan17.github.io/DialCache/observability.html) -when using those integrations. +## Example -## Usage +The example is TypeScript. The [documentation](https://lan17.github.io/DialCache/) +has the same examples in Go, Rust and Python. ```ts -import { CacheLayer, DialCache, DialCacheKeyConfig } from "dialcache"; - -const dialcache = new DialCache(); - -// The loader: the database or service read. -async function fetchUser(userId: string) { - console.log("Loading from source:", userId); - return { id: userId, name: "Ada" }; -} +import { DialCache, DialCacheKeyConfig } from "dialcache"; +import { createNodeRedisDialCacheClient } from "dialcache/node-redis"; +import { createPrometheusDialCacheMetrics } from "dialcache/prometheus"; + +// fetchUser, redisClient, registry, flags and writeLagMs are your application's objects. +const dialcache = new DialCache({ + namespace: "users-api", + redis: { client: createNodeRedisDialCacheClient(redisClient) }, + metrics: createPrometheusDialCacheMetrics({ registry }), + // Runtime configuration. Runs before each enabled call; omitted fields inherit. + cacheConfigProvider: (key) => { + const override = flags.get(`dialcache.${key.useCase}`); // e.g. { ramp: { remote: 10 } } + return override ? new DialCacheKeyConfig(override) : null; + }, +}); -// Register once; use getUser at read sites. +// Register the use case once. Call getUser at read sites. const getUser = dialcache.cached(fetchUser, { - keyType: "user_id", // Entity kind; groups tracked results by id. - useCase: "GetUser", // Operation name; part of the key and metric labels. - cacheKey: (userId) => userId, // Include every input that changes the result. + useCase: "GetUser", // The name in keys and metric labels. + keyType: "user_id", // The entity kind; the invalidation group. + cacheKey: (userId) => userId, // Every input that changes the result. + trackForInvalidation: true, defaultConfig: new DialCacheKeyConfig({ - ttlSec: { [CacheLayer.LOCAL]: 60 }, + ttlSec: { local: 60, remote: 600 }, + ramp: { remote: 0 }, // Redis stays off until a runtime override raises the ramp. }), }); // In a service, wrap each request's reads in one enable() call. await dialcache.enable(async () => { - await getUser("123"); // Loads from source and caches the result. - await getUser("123"); // Reuses the value for up to 60 seconds. + await getUser("123"); // Miss: calls fetchUser and stores the result. + await getUser("123"); // Hit. }); -await getUser("123"); // Outside enable(): loads from source again. +// After a committed write, fence every tracked use case keyed by this user. +// writeLagMs: your bound on stale loads that were still in flight at the write. +await dialcache.invalidateRemote("user_id", "123", writeLagMs); +``` + +**Metrics.** Each use case reports under its own labels: + +```text +dialcache_request_counter{cache_namespace="users-api",use_case="GetUser",key_type="user_id",layer="local"} 2 +dialcache_miss_counter{cache_namespace="users-api",use_case="GetUser",key_type="user_id",layer="local",reason="value_absent"} 1 +dialcache_disabled_counter{cache_namespace="users-api",use_case="GetUser",key_type="user_id",layer="remote",reason="ramped_down"} 1 ``` -Results containing `Date`, `bigint`, or other non-JSON-compatible values need an -explicit [typed serializer](https://lan17.github.io/DialCache/redis.html#typed-serializer-requirement), -even when caching only in memory. Cached objects are shared references; copy -before modifying. +**Runtime configuration.** Set the flag `dialcache.GetUser` to +`{ "ramp": { "remote": 10 } }`. From the next call, Redis serves a stable 10% of +the keys of `GetUser`. No deploy. Raise the ramp to `100` when the metrics look +right. A change applies to new calls; it does not evict values. + +**Invalidation.** `invalidateRemote("user_id", "123", writeLagMs)` writes one +watermark. On its next Redis read, each tracked use case with `keyType: "user_id"` +rejects values for user `123` stamped at or before the watermark. Local hits are +not fenced. A caller that joins a load in flight can get a value that load read +before the invalidation. +[Targeted invalidation](https://lan17.github.io/DialCache/invalidation.html) +covers the buffer and these boundaries. + +Results that contain `Date`, `bigint` or other non-JSON values need an explicit +[typed serializer](https://lan17.github.io/DialCache/redis.html#typed-serializer-requirement), +also for in-memory caching. Cached objects are shared references; copy before you +modify. [`getOrLoad()`](https://lan17.github.io/DialCache/api.html#getorload) gives +the same cache path to an inline loader and a direct key. + +## Safe to roll out + +- **Off by default.** Caching runs only inside an `enable()` scope. `disable()` + restores pass-through for nested mutation work and evicts nothing. +- **Fail-open.** A cache error runs the loader. A configuration provider error + runs the loader uncached. An invalid configuration field disables only its + layer or feature; valid layers continue. Metrics record each case. +- **Coalescing.** Concurrent same-key calls share one loader execution when a + cache layer is active. Set `coalesce: false` for independent execution. +- **Stale-on-error (opt-in).** For selected source errors, DialCache serves a + retained Redis value up to a maximum age. +- **Shadow validation (opt-in).** DialCache compares a sample of keys with the + source in the background. The caller does not wait for it. + +## Languages + +| Language | Status | Implementation | Guide | +| --- | --- | --- | --- | +| TypeScript | Reference implementation | [`typescript/`](typescript/) | [TypeScript and npm](typescript/README.md) | +| Go | Experimental | [`go/`](go/) | [Go guide](go/README.md) | +| Rust | Experimental | [`rust/`](rust/) | [Rust guide](rust/README.md) · [crates.io](https://crates.io/crates/dialcache) | +| Python | Experimental | [`python/`](python/) | [Python guide](python/README.md) · [PyPI](https://pypi.org/project/dialcache/) | + +One [Quint specification](formal/README.md) defines the behavior. Every +implementation replays the same histories generated from it. + +## Install TypeScript +```bash +npm install dialcache +``` -[`getOrLoad()`](https://lan17.github.io/DialCache/api.html#getorload) provides the -same cache path for an inline loader and a direct key. +Requires Node.js 22.15.0 or newer within 22.x, or 23.8.0 and newer, for +`node:zlib` zstd support. Use a +[supported LTS release](https://nodejs.org/en/about/previous-releases) in production. +Install a [Redis or Valkey client](https://lan17.github.io/DialCache/redis.html) +and a [metrics client](https://lan17.github.io/DialCache/observability.html) +when using those integrations. ## How reads work -Wrap each request's reads in one `enable()` call. Use `disable()` for nested -mutation work; it restores pass-through behavior without evicting anything. -Within an enabled call, the first active layer with a hit returns the value: +Inside an enabled call, the first active layer with a hit returns the value: ```text request-local → process-local → Redis / Valkey → loader @@ -117,30 +150,10 @@ request-local → process-local → Redis / Valkey → loader | Process-local | Requests using one `DialCache` instance | Insertion TTL, bounded by LRU capacity | | Remote | Instances sharing the Redis keyspace | Physical TTL and logical age checks; optional watermarks | -Local hits bypass Redis, including its invalidation checks. A Redis hit can warm -an active local layer. Concurrent calls share work when a cache layer is active; -set `coalesce: false` when callers need independent execution. +A local hit does not read Redis, so it bypasses the invalidation watermark. A +Redis hit can warm an active local layer. [How DialCache works](https://lan17.github.io/DialCache/concepts.html) covers the -read path, publication rules, and freshness boundaries. - - - -## Runtime control - -An operation's `defaultConfig` is its baseline. A `cacheConfigProvider` overrides -individual policy fields for each enabled call. Ramps select stable cohorts of -keys: raising a ramp adds keys, while lowering it removes keys without -reshuffling the rest. A 10% key cohort need not account for 10% of traffic. - -Policy changes apply to new invocations. They do not evict values or cancel work -already admitted. Shadow validation has an independent ramp and compares sampled -Redis values with the source in the background. It can also fill misses while -remote serving is ramped down; callers do not wait for shadow checks or fills. - -See [Configuration and rollout](https://lan17.github.io/DialCache/configuration.html) -for precedence and runtime examples, and -[Shadow validation](https://lan17.github.io/DialCache/shadow-validation.html) -for sampling and comparison behavior. +read path, publication rules and freshness boundaries. @@ -153,6 +166,7 @@ for sampling and comparison behavior. | Defaults, overrides, and policy changes | [Configuration and rollout](https://lan17.github.io/DialCache/configuration.html) | | Watermarks and mutation handling | [Targeted invalidation](https://lan17.github.io/DialCache/invalidation.html) | | Recovery from selected source failures | [Stale-on-error](https://lan17.github.io/DialCache/stale-on-error.html) | +| Sampling and comparison against the source | [Shadow validation](https://lan17.github.io/DialCache/shadow-validation.html) | | Shared execution and deadlines | [Coalescing and liveness](https://lan17.github.io/DialCache/coalescing.html) | | Methods, options, and exports | [API reference](https://lan17.github.io/DialCache/api.html) | | Native implementations and shared behavior contracts | [TypeScript guide](typescript/README.md) · [Go guide](go/README.md) · [Rust guide](rust/README.md) · [Python guide](python/README.md) · [Quint specification](formal/README.md) · [Worked walkthrough](formal/guides/WALKTHROUGH.md) | @@ -163,6 +177,12 @@ setup, observability, and upgrades. Everything is ## Development +[![TypeScript coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=typescript&label=TypeScript%20coverage)](https://codecov.io/gh/lan17/DialCache) +[![Go coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=go&label=Go%20coverage)](https://codecov.io/gh/lan17/DialCache) +[![Rust coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=rust&label=Rust%20coverage)](https://codecov.io/gh/lan17/DialCache) +[![Python coverage](https://img.shields.io/codecov/c/github/lan17/DialCache/main?flag=python&label=Python%20coverage)](https://codecov.io/gh/lan17/DialCache) +[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/lan17/DialCache/badge)](https://scorecard.dev/viewer/?uri=github.com/lan17/DialCache) + Run `make check` from the repository root for the routine checks of every language; [Validation and evidence](formal/guides/VALIDATION.md) lists the toolchains and the other lanes. [Development process](DEVELOPMENT_PROCESS.md) explains how a change travels from a diff --git a/formal/catalogs/go-parity.json b/formal/catalogs/go-parity.json index 80ef31d5..81dfffdd 100644 --- a/formal/catalogs/go-parity.json +++ b/formal/catalogs/go-parity.json @@ -10,7 +10,7 @@ "inputs": { "semanticCasesSha256": "380273598e1d956a3f9fce270cc84424b342e456139b279bd56576bd3b837f65", "executionSha256": "eaf117c3e8630013cc8df0524f84af440c470f42e8711ab4dd07b931161c784f", - "sourceAuditDispositionsSha256": "942eab018ae0d8fa189ff16c322f6d9b3301aadc7c46d00b311018728c62f34e", + "sourceAuditDispositionsSha256": "24857672eb35558aa6af24a5fabc98e12b63825641dd47d85181830d2899ede2", "featureCoverageSha256": "7bfe01e9ed074fc4661e6db2d3397341f7f691f476e2358e4af082c8117570de", "coverageWitnessesSha256": "745cebececddbfa97912621ada94072d648e8e60e8b3eb013b91eefd16f352a1", "profilesSha256": "888a522f8ad97862ebcb0b5fe363ec7bec60367fa42c60e1623141814b1991b3" diff --git a/formal/catalogs/source-audit.json b/formal/catalogs/source-audit.json index 6ca2b244..668adce0 100644 --- a/formal/catalogs/source-audit.json +++ b/formal/catalogs/source-audit.json @@ -22,13 +22,14 @@ }, { "path": "README.md", - "sha256": "2f57974de4039f45a3608464f1235a5567af7e6f32c7f58cf0232dde051e9304", + "sha256": "5c43a8fdd938880e2d7acfc3f3217a8dea4ca9a9a4ddbcf531223fbba5a0a162", "entries": [ {"title":"DialCache","contracts":["B01"]}, + {"title":"Example","contracts":["C01","C05","C16","C18","C32","W01"]}, + {"title":"Safe to roll out","contracts":["C01","C13","C17","C27","C40","C47"]}, + {"title":"Languages","contracts":["B01"]}, {"title":"Install TypeScript","contracts":["B01"]}, - {"title":"Usage","contracts":["C01","C05","W01"]}, {"title":"How reads work","contracts":["C05","C31"]}, - {"title":"Runtime control","contracts":["C16","C18"]}, {"title":"Documentation","contracts":["B01"]}, {"title":"Development","contracts":["B01"]} ] diff --git a/formal/guides/course/13-catalogs-and-ledgers.md b/formal/guides/course/13-catalogs-and-ledgers.md index 2c2f8800..b7564df5 100644 --- a/formal/guides/course/13-catalogs-and-ledgers.md +++ b/formal/guides/course/13-catalogs-and-ledgers.md @@ -99,7 +99,7 @@ You will edit a tracked guide and undo it at the end. { sources: 50, tests: 633, - sections: 216, + sections: 217, reviewedGuides: 19, guideSections: 195 }