@open-mercato/cache-redis-protocol 0.0.0-stage → 0.11.1-develop.9002.1.e180dacef1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -2
- package/dist/client.js +162 -0
- package/dist/client.js.map +7 -0
- package/dist/cluster.js +7 -0
- package/dist/cluster.js.map +7 -0
- package/dist/index.js +48 -0
- package/dist/index.js.map +7 -0
- package/dist/layout.js +39 -0
- package/dist/layout.js.map +7 -0
- package/dist/provider.js +63 -0
- package/dist/provider.js.map +7 -0
- package/dist/scripts.js +77 -0
- package/dist/scripts.js.map +7 -0
- package/dist/server.js +32 -0
- package/dist/server.js.map +7 -0
- package/dist/settings.js +107 -0
- package/dist/settings.js.map +7 -0
- package/dist/strategy.js +315 -0
- package/dist/strategy.js.map +7 -0
- package/package.json +64 -3
- package/src/client.ts +223 -0
- package/src/cluster.ts +6 -0
- package/src/index.ts +45 -0
- package/src/layout.ts +49 -0
- package/src/provider.ts +86 -0
- package/src/scripts.ts +103 -0
- package/src/server.ts +41 -0
- package/src/settings.ts +127 -0
- package/src/strategy.ts +413 -0
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @open-mercato/cache-redis-protocol
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shared RESP (Redis protocol) cache strategy for Open Mercato cache provider packages. **This is a library, not a provider**: apps install an engine package (`@open-mercato/cache-provider-valkey`, `-redis`, `-keydb`, or an Enterprise managed-service provider) which depends on it.
|
|
4
|
+
|
|
5
|
+
It implements the v1 `CacheStrategy` over already tenant-scoped physical keys (see `@open-mercato/cache/provider`) on top of [ioredis](https://github.com/redis/ioredis), pinned to exactly `6.0.0` (the engine packages get it through this package and do not declare it themselves).
|
|
6
|
+
|
|
7
|
+
## API
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import {
|
|
11
|
+
createRespCacheStrategy,
|
|
12
|
+
createIoredisClientFactory,
|
|
13
|
+
createRespCacheProvider,
|
|
14
|
+
createRespStandaloneSettingsSchema,
|
|
15
|
+
createRespSettingsSchema,
|
|
16
|
+
redactRespSettings,
|
|
17
|
+
} from '@open-mercato/cache-redis-protocol'
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
| Export | Purpose |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `createRespCacheStrategy(clientFactory, { namespace, helpers, logger?, defaultTtl?, batchSize?, maxValueBytes?, timeouts? })` | The strategy. `clientFactory` returns an ioredis `Redis`/`Cluster` (or `{ client, dispose }`), so client construction stays injectable. |
|
|
23
|
+
| `createIoredisClientFactory(settings, { credentialsProvider?, refreshIntervalMs?, redisOptions?, clusterOptions?, onError? })` | Standalone or cluster client with TLS, ACL credentials, bounded connect/command timeouts and capped reconnect backoff. `credentialsProvider` supplies fresh credentials before connecting, on every reconnect of the client and of each cluster node, to cluster nodes as they join, and on the `refreshIntervalMs` schedule (re-`AUTH` of live connections); a connection that becomes ready with a credential older than the current one is re-`AUTH`ed at once. `refreshIntervalMs` is a fixed interval or a function evaluated after each refresh returning the next delay (floored at `RESP_MIN_REFRESH_DELAY_MS`), so token-aware callers re-authenticate before the token expires — the hook managed providers use for token-based auth. |
|
|
24
|
+
| `createRespCacheProvider({ id, settings, expectedEngine?, clientOptions? })` | Everything a provider definition needs except `apiVersion`; provider packages pass it to `defineCacheProvider`. |
|
|
25
|
+
| `createRespStandaloneSettingsSchema()` / `createRespSettingsSchema()` | Strict zod settings (standalone only / standalone or cluster). |
|
|
26
|
+
| `redactRespSettings(settings)` | Operator-safe view: endpoints and tuning, never credentials or key material. |
|
|
27
|
+
| `buildRespKeyLayout(namespace)` | The physical key layout (below). |
|
|
28
|
+
|
|
29
|
+
## Storage layout (version 1)
|
|
30
|
+
|
|
31
|
+
With `<ns>` the deployment namespace (`CACHE_PROVIDER_NAMESPACE`):
|
|
32
|
+
|
|
33
|
+
| Key | Type | Content |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| `om:{<ns>}:v:<physicalKey>` | string | `helpers.encode(JSON {v:1, value, tags, expiresAt})` with a native `PX` TTL |
|
|
36
|
+
| `om:{<ns>}:t:<tag>` | set | physical keys indexed under the tag. Native TTL no shorter than its longest-lived member; none while a member without TTL was written into it |
|
|
37
|
+
|
|
38
|
+
- **Single-slot trade-off.** The `{<ns>}` hash tag places every key of a namespace in one cluster slot. That is what makes the value + tag-set write a single script, lets one Lua script compare and delete a value and its memberships, and keeps `MGET` batches legal on a cluster. The cost: a namespace never spreads across shards — one namespace's data and traffic live on one primary. Use several namespaces (or deployments) if one primary cannot hold the cache.
|
|
39
|
+
- **Writes**: one `EVALSHA` (`WRITE_ENTRY`) runs `SET value [PX ttl]` and, per tag, `SADD tag-set member` plus the tag-set TTL update. A new tag set takes the entry TTL, an existing volatile set is only ever extended (`PEXPIRE` when the entry outlives the set), and an entry without TTL makes the set persistent (`PERSIST`). A tag set therefore lives at least as long as its longest-lived member and disappears with it. The rule is plain Lua rather than `PEXPIRE … GT` because KeyDB 6.3 (Redis 6.2 base) has no `GT` flag. A retag does not touch old tag sets; stale memberships are reaped lazily.
|
|
40
|
+
- **Stale members.** A set that once held a member without TTL stays persistent, and members of overwritten, retagged, deleted or expired entries stay in their sets until an invalidation touches them or the set expires. Schedule `cleanup()` (for example from a periodic job) to reclaim them: it `SSCAN`s every tag set and removes members whose value is gone, and a set whose last member is removed disappears.
|
|
41
|
+
- **Tag invalidation**: `SSCAN` each tag set in `batchSize` pages, `MGET` the members, decode them, then one `EVALSHA` per batch that deletes a value (and removes it from all its tag sets) **only if its bytes still hash to the observed SHA-1**. A concurrent rewrite or retag therefore survives, and stale members are removed only while the value is still absent or unchanged — membership of a concurrently re-tagged entry is never lost. `NOSCRIPT` falls back to `EVAL`.
|
|
42
|
+
- **Enumeration** (`keys`, `stats`, `clear`) uses `SCAN MATCH om:{<ns>}:v:<literal prefix>*` with `COUNT batchSize`; never `KEYS`, `FLUSHDB` or `FLUSHALL`. On a cluster every primary is scanned. `clear` unlinks values first, then conditionally prunes memberships whose values are absent. An interrupted clear leaves surviving entries indexed. `stats().size` counts the keys `SCAN` returns without holding them in memory. It can over-count by keys `SCAN` returns twice while the server rehashes its keyspace, so treat it as a diagnostic.
|
|
43
|
+
- **Expiry** is native: expired entries are gone, so `returnExpired` is not supported and `stats().expired` is always 0. `cleanup()` reaps tag-set members whose value expired.
|
|
44
|
+
- **Reads** go to primaries only (`scaleReads: 'master'` on clusters, a single writable endpoint otherwise).
|
|
45
|
+
- **Corrupt values** (undecodable bytes) are a miss and are deleted with the same compare-and-delete.
|
|
46
|
+
- **Oversize writes** (encoded entry larger than `maxValueBytes`) are skipped with a warning and the previous value is deleted so no stale value is served.
|
|
47
|
+
|
|
48
|
+
### Least-privilege ACL
|
|
49
|
+
|
|
50
|
+
The strategy needs only `@read @write @keyspace @scripting @transaction @connection` minus `@dangerous`, fenced to `~om:*` (`@transaction` is no longer used by the strategy and can be dropped):
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
user om-cache on >… ~om:* resetchannels -@all +@read +@write +@keyspace +@scripting +@transaction +@connection -@dangerous
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`INFO` (used only for an optional engine-mismatch warning) is not required; the ioredis ready check is disabled for that reason. A cluster client additionally needs topology discovery: `+cluster|slots +cluster|shards +cluster|info`.
|
|
57
|
+
|
|
58
|
+
### Cluster behaviour
|
|
59
|
+
|
|
60
|
+
Multi-key commands (the write script, invalidation scripts, `MGET`) receive `TRYAGAIN` while their slot is being migrated; the strategy retries them up to `tryAgainAttempts` (default 40) × 50 ms, so writes wait out a short migration instead of failing. Single-key commands follow `MOVED`/`ASK` through ioredis.
|
|
61
|
+
|
|
62
|
+
## Settings (shared by the engine packages)
|
|
63
|
+
|
|
64
|
+
| Key | Default | Notes |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `mode` | `standalone` | `cluster` only through `createRespSettingsSchema()` (needs `nodes`) |
|
|
67
|
+
| `host`, `port`, `db` | –, `6379`, `0` | standalone endpoint |
|
|
68
|
+
| `nodes[]` | – | cluster seeds `{ host, port }` |
|
|
69
|
+
| `username`, `password` | – | ACL credentials; a username requires a password |
|
|
70
|
+
| `tls` | off | `{ ca?, cert?, key?, servername?, rejectUnauthorized = true }` (PEM strings) |
|
|
71
|
+
| `connectTimeoutMs` | `5000` | 100–120000 |
|
|
72
|
+
| `commandTimeoutMs` | `2000` | 50–120000 |
|
|
73
|
+
| `maxRetriesPerRequest` | `1` | 0–10 |
|
|
74
|
+
| `batchSize` | `500` | 1–5000; SCAN/SSCAN COUNT and per-script batch |
|
|
75
|
+
| `maxValueBytes` | `8 MiB` | 1 KiB–512 MiB |
|
|
76
|
+
|
|
77
|
+
Unknown keys are rejected.
|
|
78
|
+
|
|
79
|
+
At `create`, the provider logs one warning when `tls.rejectUnauthorized` is `false` (certificate verification disabled) or when a password or `credentialsProvider` is used without `tls` (credentials over plaintext). Both configurations are accepted for local development; do not use them in production.
|
|
80
|
+
|
|
81
|
+
## Tests
|
|
82
|
+
|
|
83
|
+
- `yarn workspace @open-mercato/cache-redis-protocol test` — Docker-free unit tests (layout, settings, redaction, scripts).
|
|
84
|
+
- `test-support/` holds the shared real-engine harness used by every provider package: pinned containers with an ACL file and throwaway TLS CA (`engine.ts`), an independent-process conformance host (`host.ts`, `conformance-child.mjs`), packed installation (`packed.ts`) and the latency/command-count qualification (`qualify.ts`). It is not published.
|
|
85
|
+
- `OM_CACHE_PROVIDER_CONTAINER_TESTS=1 yarn workspace @open-mercato/cache-redis-protocol test:containers` — protocol-level container tests (Valkey Cluster profile).
|
|
86
|
+
- `yarn test:cache-providers:containers` (repo root) — runs the container suites of this library and of every cache provider package (Valkey, Redis, KeyDB, Memcached, Infinispan, Ignite) one package at a time, so engines never compete for the Docker host. It needs a local Docker daemon and takes a few minutes; it prints all workspace results and exits nonzero if any suite fails.
|
|
87
|
+
|
|
88
|
+
### Proposed CI job
|
|
89
|
+
|
|
90
|
+
The container suites are **not** part of CI today. Every evidence table in the provider READMEs is a dated manual run that records its command. Proposed job, which needs maintainer approval before a workflow is added:
|
|
91
|
+
|
|
92
|
+
- **Trigger:** nightly on `main`, plus on pull requests that carry a `cache-providers` label (set manually or by a path filter on `packages/cache*/**`). Not on every PR, because the suites start real engines and take several minutes.
|
|
93
|
+
- **Runner:** `ubuntu-latest` (linux/amd64) with Docker. The KeyDB and Ignite suites select the pinned image for the host architecture.
|
|
94
|
+
- **Steps:** `yarn install --immutable`, `yarn build:packages`, `yarn test:cache-providers:containers`, then upload the qualification JSON files (`$TMPDIR/om-resp-qualification-*.json`) as artifacts.
|
|
95
|
+
- **Gate:** a failing provider suite fails the job. The nightly job opens or updates an issue instead of blocking merges, and the labelled PR job is a required check for PRs that touch a provider package.
|
|
96
|
+
- **Evidence refresh:** when a job passes on a changed engine image or client version, update the provider README evidence row with the CI run link instead of a manual-run note.
|
|
97
|
+
|
|
98
|
+
## Evidence — Valkey Cluster profile (protocol level)
|
|
99
|
+
|
|
100
|
+
Manual run on a developer machine (macOS arm64, Docker Desktop), not CI. Command: `yarn workspace @open-mercato/cache-redis-protocol test:containers`. Last rerun 2026-11-24 after the tag-set TTL change: 19/19 passed.
|
|
101
|
+
|
|
102
|
+
| Image | Topology | Auth / transport | Suite | Date |
|
|
103
|
+
|---|---|---|---|---|
|
|
104
|
+
| `valkey/valkey:8.1` | 3 primaries (3 `valkey-server` processes, 0 replicas) in one container, announced on 127.0.0.1 | ACL user fenced to `~om:*` (+ cluster topology commands), plain TCP | **19/19 passed**: v1 conformance (16, incl. independent process, 601-entry batch crossing with `batchSize` 64, corrupt value), namespaces spread over ≥2 primaries with one slot each, live slot migration under concurrent reads/writes (MOVED/ASK + TRYAGAIN: 412 keys moved, 642 live ops, 0 errors), reconnect after `CLIENT KILL` on every node | 2026-11-24 |
|
|
105
|
+
|
|
106
|
+
**Not verified:** replica failover (no replicas in the test topology), TLS on cluster bus/client, Redis Cluster and KeyDB cluster/active-active. The Valkey provider package therefore still accepts only the standalone profile.
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { Cluster, Redis } from "ioredis";
|
|
2
|
+
import { isClusterClient } from "./cluster.js";
|
|
3
|
+
const RESP_MIN_REFRESH_DELAY_MS = 100;
|
|
4
|
+
const RECONNECT_BASE_DELAY_MS = 100;
|
|
5
|
+
const RECONNECT_MAX_DELAY_MS = 2e3;
|
|
6
|
+
function respReconnectDelay(attempt) {
|
|
7
|
+
return Math.min(RECONNECT_BASE_DELAY_MS * Math.max(1, attempt), RECONNECT_MAX_DELAY_MS);
|
|
8
|
+
}
|
|
9
|
+
function toTlsOptions(tls) {
|
|
10
|
+
if (!tls) return void 0;
|
|
11
|
+
return {
|
|
12
|
+
...tls.ca !== void 0 ? { ca: tls.ca } : {},
|
|
13
|
+
...tls.cert !== void 0 ? { cert: tls.cert } : {},
|
|
14
|
+
...tls.key !== void 0 ? { key: tls.key } : {},
|
|
15
|
+
...tls.servername !== void 0 ? { servername: tls.servername } : {},
|
|
16
|
+
rejectUnauthorized: tls.rejectUnauthorized
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function baseRedisOptions(settings) {
|
|
20
|
+
const tls = toTlsOptions(settings.tls);
|
|
21
|
+
return {
|
|
22
|
+
lazyConnect: true,
|
|
23
|
+
connectTimeout: settings.connectTimeoutMs,
|
|
24
|
+
commandTimeout: settings.commandTimeoutMs,
|
|
25
|
+
maxRetriesPerRequest: settings.maxRetriesPerRequest,
|
|
26
|
+
enableReadyCheck: false,
|
|
27
|
+
autoResubscribe: false,
|
|
28
|
+
retryStrategy: respReconnectDelay,
|
|
29
|
+
...settings.username !== void 0 ? { username: settings.username } : {},
|
|
30
|
+
...settings.password !== void 0 ? { password: settings.password } : {},
|
|
31
|
+
...tls ? { tls } : {}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function applyCredentials(target, credentials) {
|
|
35
|
+
target.options.username = credentials.username;
|
|
36
|
+
target.options.password = credentials.password;
|
|
37
|
+
}
|
|
38
|
+
function credentialTargets(client) {
|
|
39
|
+
if (isClusterClient(client)) {
|
|
40
|
+
const nodes = client.nodes("all");
|
|
41
|
+
const template = client.options.redisOptions;
|
|
42
|
+
return template ? [...nodes, { options: template }] : nodes;
|
|
43
|
+
}
|
|
44
|
+
return [client];
|
|
45
|
+
}
|
|
46
|
+
async function authenticate(connection, credentials) {
|
|
47
|
+
if (credentials.username !== void 0) await connection.auth(credentials.username, credentials.password);
|
|
48
|
+
else await connection.auth(credentials.password);
|
|
49
|
+
}
|
|
50
|
+
async function reauthenticate(client, credentials) {
|
|
51
|
+
const connections = isClusterClient(client) ? client.nodes("all") : [client];
|
|
52
|
+
await Promise.all(connections.map(async (connection) => {
|
|
53
|
+
if (connection.status !== "ready") return;
|
|
54
|
+
await authenticate(connection, credentials);
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
function credentialsOf(options) {
|
|
58
|
+
return { ...options.username !== void 0 ? { username: options.username } : {}, password: options.password ?? "" };
|
|
59
|
+
}
|
|
60
|
+
function sameCredentials(left, right) {
|
|
61
|
+
return left.username === right.username && left.password === right.password;
|
|
62
|
+
}
|
|
63
|
+
function nextRefreshDelay(schedule) {
|
|
64
|
+
if (schedule === void 0) return null;
|
|
65
|
+
const raw = typeof schedule === "function" ? schedule() : schedule;
|
|
66
|
+
if (typeof schedule === "number" && !(raw > 0)) return null;
|
|
67
|
+
return Number.isFinite(raw) ? Math.max(RESP_MIN_REFRESH_DELAY_MS, raw) : null;
|
|
68
|
+
}
|
|
69
|
+
function createIoredisClientFactory(settings, options = {}) {
|
|
70
|
+
return async () => {
|
|
71
|
+
const redisOptions = { ...baseRedisOptions(settings), ...options.redisOptions ?? {} };
|
|
72
|
+
if (options.credentialsProvider) applyCredentials({ options: redisOptions }, await options.credentialsProvider());
|
|
73
|
+
const client = settings.mode === "cluster" ? new Cluster(settings.nodes.map((node) => ({ host: node.host, port: node.port })), {
|
|
74
|
+
lazyConnect: true,
|
|
75
|
+
scaleReads: "master",
|
|
76
|
+
enableOfflineQueue: true,
|
|
77
|
+
maxRedirections: 16,
|
|
78
|
+
retryDelayOnFailover: 100,
|
|
79
|
+
retryDelayOnClusterDown: 100,
|
|
80
|
+
retryDelayOnTryAgain: 100,
|
|
81
|
+
slotsRefreshTimeout: settings.connectTimeoutMs,
|
|
82
|
+
clusterRetryStrategy: respReconnectDelay,
|
|
83
|
+
...options.clusterOptions ?? {},
|
|
84
|
+
redisOptions
|
|
85
|
+
}) : new Redis({ ...redisOptions, host: settings.host, port: settings.port, db: settings.db });
|
|
86
|
+
client.on("error", (error) => options.onError?.(error));
|
|
87
|
+
let refreshTimer = null;
|
|
88
|
+
let disposed = false;
|
|
89
|
+
const provider = options.credentialsProvider;
|
|
90
|
+
if (provider) {
|
|
91
|
+
const report = (error) => {
|
|
92
|
+
options.onError?.(error instanceof Error ? error : new Error("[internal] credential refresh failed"));
|
|
93
|
+
};
|
|
94
|
+
const refresh = async (live) => {
|
|
95
|
+
try {
|
|
96
|
+
const credentials = await provider();
|
|
97
|
+
for (const target of credentialTargets(client)) applyCredentials(target, credentials);
|
|
98
|
+
if (live) await reauthenticate(client, credentials);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
report(error);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const watched = /* @__PURE__ */ new WeakSet();
|
|
104
|
+
const watchConnection = (connection) => {
|
|
105
|
+
if (watched.has(connection)) return;
|
|
106
|
+
watched.add(connection);
|
|
107
|
+
let connectedWith = credentialsOf(connection.options);
|
|
108
|
+
connection.on("connecting", () => {
|
|
109
|
+
connectedWith = credentialsOf(connection.options);
|
|
110
|
+
});
|
|
111
|
+
connection.on("reconnecting", () => {
|
|
112
|
+
provider().then((credentials) => applyCredentials(connection, credentials), report);
|
|
113
|
+
});
|
|
114
|
+
connection.on("ready", () => {
|
|
115
|
+
provider().then(async (credentials) => {
|
|
116
|
+
applyCredentials(connection, credentials);
|
|
117
|
+
if (sameCredentials(connectedWith, credentials) || connection.status !== "ready") return;
|
|
118
|
+
await authenticate(connection, credentials);
|
|
119
|
+
connectedWith = credentials;
|
|
120
|
+
}).catch(report);
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
if (isClusterClient(client)) {
|
|
124
|
+
client.on("+node", (node) => {
|
|
125
|
+
watchConnection(node);
|
|
126
|
+
provider().then((credentials) => applyCredentials(node, credentials), report);
|
|
127
|
+
});
|
|
128
|
+
for (const node of client.nodes("all")) watchConnection(node);
|
|
129
|
+
client.on("reconnecting", () => {
|
|
130
|
+
void refresh(false);
|
|
131
|
+
});
|
|
132
|
+
} else {
|
|
133
|
+
watchConnection(client);
|
|
134
|
+
}
|
|
135
|
+
const schedule = () => {
|
|
136
|
+
if (disposed) return;
|
|
137
|
+
const delay = nextRefreshDelay(options.refreshIntervalMs);
|
|
138
|
+
if (delay === null) return;
|
|
139
|
+
refreshTimer = setTimeout(() => {
|
|
140
|
+
refreshTimer = null;
|
|
141
|
+
void refresh(true).finally(schedule);
|
|
142
|
+
}, delay);
|
|
143
|
+
refreshTimer.unref();
|
|
144
|
+
};
|
|
145
|
+
schedule();
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
client,
|
|
149
|
+
dispose() {
|
|
150
|
+
disposed = true;
|
|
151
|
+
if (refreshTimer) clearTimeout(refreshTimer);
|
|
152
|
+
refreshTimer = null;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
export {
|
|
158
|
+
RESP_MIN_REFRESH_DELAY_MS,
|
|
159
|
+
createIoredisClientFactory,
|
|
160
|
+
respReconnectDelay
|
|
161
|
+
};
|
|
162
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/client.ts"],
|
|
4
|
+
"sourcesContent": ["import { Cluster, Redis } from 'ioredis'\nimport type { ClusterOptions, RedisOptions } from 'ioredis'\nimport type { RespSettings, RespTlsSettings } from './settings'\nimport { isClusterClient } from './cluster'\n\nexport type RespClient = Redis | Cluster\n\nexport type RespClientFactory = () => RespClient | Promise<RespClient>\n\nexport type RespCredentials = {\n username?: string\n password: string\n}\n\n/**\n * Supplies fresh credentials (for example a short-lived cloud access token).\n * Called before the first connection, on every reconnect (of the client and of\n * every cluster node), when a cluster node joins and, with `refreshIntervalMs`,\n * on a schedule to re-authenticate live connections.\n */\nexport type RespCredentialsProvider = () => Promise<RespCredentials>\n\n/**\n * Re-`AUTH` schedule: a fixed interval, or a function evaluated after every\n * refresh returning the delay until the next one (so a token-aware caller can\n * re-authenticate before the current token expires).\n */\nexport type RespRefreshSchedule = number | (() => number)\n\nexport type RespClientFactoryOptions = {\n credentialsProvider?: RespCredentialsProvider\n refreshIntervalMs?: RespRefreshSchedule\n /** Extra ioredis options merged last (managed-service specifics such as `dnsLookup` or `natMap`). */\n redisOptions?: RedisOptions\n clusterOptions?: Omit<ClusterOptions, 'redisOptions'>\n onError?: (error: Error) => void\n}\n\nexport type RespManagedClient = {\n client: RespClient\n /** Stop credential refresh timers; the strategy calls this on close. */\n dispose(): void\n}\n\n/** Lower bound for a scheduled re-`AUTH`, so a misbehaving schedule cannot spin. */\nexport const RESP_MIN_REFRESH_DELAY_MS = 100\n\nconst RECONNECT_BASE_DELAY_MS = 100\nconst RECONNECT_MAX_DELAY_MS = 2_000\n\nexport function respReconnectDelay(attempt: number): number {\n return Math.min(RECONNECT_BASE_DELAY_MS * Math.max(1, attempt), RECONNECT_MAX_DELAY_MS)\n}\n\nfunction toTlsOptions(tls: RespTlsSettings | undefined): RedisOptions['tls'] {\n if (!tls) return undefined\n return {\n ...(tls.ca !== undefined ? { ca: tls.ca } : {}),\n ...(tls.cert !== undefined ? { cert: tls.cert } : {}),\n ...(tls.key !== undefined ? { key: tls.key } : {}),\n ...(tls.servername !== undefined ? { servername: tls.servername } : {}),\n rejectUnauthorized: tls.rejectUnauthorized,\n }\n}\n\nfunction baseRedisOptions(settings: RespSettings): RedisOptions {\n const tls = toTlsOptions(settings.tls)\n return {\n lazyConnect: true,\n connectTimeout: settings.connectTimeoutMs,\n commandTimeout: settings.commandTimeoutMs,\n maxRetriesPerRequest: settings.maxRetriesPerRequest,\n enableReadyCheck: false,\n autoResubscribe: false,\n retryStrategy: respReconnectDelay,\n ...(settings.username !== undefined ? { username: settings.username } : {}),\n ...(settings.password !== undefined ? { password: settings.password } : {}),\n ...(tls ? { tls } : {}),\n }\n}\n\ntype CredentialTarget = { options: RedisOptions }\n\nfunction applyCredentials(target: CredentialTarget, credentials: RespCredentials): void {\n target.options.username = credentials.username\n target.options.password = credentials.password\n}\n\nfunction credentialTargets(client: RespClient): CredentialTarget[] {\n if (isClusterClient(client)) {\n const nodes: CredentialTarget[] = client.nodes('all')\n const template = client.options.redisOptions\n return template ? [...nodes, { options: template }] : nodes\n }\n return [client]\n}\n\nasync function authenticate(connection: Redis, credentials: RespCredentials): Promise<void> {\n if (credentials.username !== undefined) await connection.auth(credentials.username, credentials.password)\n else await connection.auth(credentials.password)\n}\n\nasync function reauthenticate(client: RespClient, credentials: RespCredentials): Promise<void> {\n const connections: Redis[] = isClusterClient(client) ? client.nodes('all') : [client]\n await Promise.all(connections.map(async (connection) => {\n if (connection.status !== 'ready') return\n await authenticate(connection, credentials)\n }))\n}\n\nfunction credentialsOf(options: RedisOptions): RespCredentials {\n return { ...(options.username !== undefined ? { username: options.username } : {}), password: options.password ?? '' }\n}\n\nfunction sameCredentials(left: RespCredentials, right: RespCredentials): boolean {\n return left.username === right.username && left.password === right.password\n}\n\nfunction nextRefreshDelay(schedule: RespRefreshSchedule | undefined): number | null {\n if (schedule === undefined) return null\n const raw = typeof schedule === 'function' ? schedule() : schedule\n if (typeof schedule === 'number' && !(raw > 0)) return null\n return Number.isFinite(raw) ? Math.max(RESP_MIN_REFRESH_DELAY_MS, raw) : null\n}\n\n/**\n * Build a RESP client factory over ioredis for standalone or cluster settings.\n * Mutations and reads always go to primaries (`scaleReads: 'master'`).\n */\nexport function createIoredisClientFactory(settings: RespSettings, options: RespClientFactoryOptions = {}): () => Promise<RespManagedClient> {\n return async () => {\n const redisOptions: RedisOptions = { ...baseRedisOptions(settings), ...(options.redisOptions ?? {}) }\n if (options.credentialsProvider) applyCredentials({ options: redisOptions }, await options.credentialsProvider())\n\n const client: RespClient = settings.mode === 'cluster'\n ? new Cluster(settings.nodes.map((node) => ({ host: node.host, port: node.port })), {\n lazyConnect: true,\n scaleReads: 'master',\n enableOfflineQueue: true,\n maxRedirections: 16,\n retryDelayOnFailover: 100,\n retryDelayOnClusterDown: 100,\n retryDelayOnTryAgain: 100,\n slotsRefreshTimeout: settings.connectTimeoutMs,\n clusterRetryStrategy: respReconnectDelay,\n ...(options.clusterOptions ?? {}),\n redisOptions,\n })\n : new Redis({ ...redisOptions, host: settings.host, port: settings.port, db: settings.db })\n\n client.on('error', (error: Error) => options.onError?.(error))\n\n let refreshTimer: ReturnType<typeof setTimeout> | null = null\n let disposed = false\n const provider = options.credentialsProvider\n if (provider) {\n const report = (error: unknown) => {\n options.onError?.(error instanceof Error ? error : new Error('[internal] credential refresh failed'))\n }\n const refresh = async (live: boolean) => {\n try {\n const credentials = await provider()\n for (const target of credentialTargets(client)) applyCredentials(target, credentials)\n if (live) await reauthenticate(client, credentials)\n } catch (error) {\n report(error)\n }\n }\n const watched = new WeakSet<Redis>()\n const watchConnection = (connection: Redis) => {\n if (watched.has(connection)) return\n watched.add(connection)\n let connectedWith = credentialsOf(connection.options)\n connection.on('connecting', () => {\n connectedWith = credentialsOf(connection.options)\n })\n connection.on('reconnecting', () => {\n provider().then((credentials) => applyCredentials(connection, credentials), report)\n })\n connection.on('ready', () => {\n provider().then(async (credentials) => {\n applyCredentials(connection, credentials)\n if (sameCredentials(connectedWith, credentials) || connection.status !== 'ready') return\n await authenticate(connection, credentials)\n connectedWith = credentials\n }).catch(report)\n })\n }\n if (isClusterClient(client)) {\n client.on('+node', (node: Redis) => {\n watchConnection(node)\n provider().then((credentials) => applyCredentials(node, credentials), report)\n })\n for (const node of client.nodes('all')) watchConnection(node)\n client.on('reconnecting', () => {\n void refresh(false)\n })\n } else {\n watchConnection(client)\n }\n const schedule = () => {\n if (disposed) return\n const delay = nextRefreshDelay(options.refreshIntervalMs)\n if (delay === null) return\n refreshTimer = setTimeout(() => {\n refreshTimer = null\n void refresh(true).finally(schedule)\n }, delay)\n refreshTimer.unref()\n }\n schedule()\n }\n\n return {\n client,\n dispose() {\n disposed = true\n if (refreshTimer) clearTimeout(refreshTimer)\n refreshTimer = null\n },\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS,aAAa;AAG/B,SAAS,uBAAuB;AA0CzB,MAAM,4BAA4B;AAEzC,MAAM,0BAA0B;AAChC,MAAM,yBAAyB;AAExB,SAAS,mBAAmB,SAAyB;AAC1D,SAAO,KAAK,IAAI,0BAA0B,KAAK,IAAI,GAAG,OAAO,GAAG,sBAAsB;AACxF;AAEA,SAAS,aAAa,KAAuD;AAC3E,MAAI,CAAC,IAAK,QAAO;AACjB,SAAO;AAAA,IACL,GAAI,IAAI,OAAO,SAAY,EAAE,IAAI,IAAI,GAAG,IAAI,CAAC;AAAA,IAC7C,GAAI,IAAI,SAAS,SAAY,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,IACnD,GAAI,IAAI,QAAQ,SAAY,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;AAAA,IAChD,GAAI,IAAI,eAAe,SAAY,EAAE,YAAY,IAAI,WAAW,IAAI,CAAC;AAAA,IACrE,oBAAoB,IAAI;AAAA,EAC1B;AACF;AAEA,SAAS,iBAAiB,UAAsC;AAC9D,QAAM,MAAM,aAAa,SAAS,GAAG;AACrC,SAAO;AAAA,IACL,aAAa;AAAA,IACb,gBAAgB,SAAS;AAAA,IACzB,gBAAgB,SAAS;AAAA,IACzB,sBAAsB,SAAS;AAAA,IAC/B,kBAAkB;AAAA,IAClB,iB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AM,WAAW,MAAM;AACrB,YAAI,SAAU;AACd,cAAM,QAAQ,iBAAiB,QAAQ,iBAAiB;AACxD,YAAI,UAAU,KAAM;AACpB,uBAAe,WAAW,MAAM;AAC9B,yBAAe;AACf,eAAK,QAAQ,IAAI,EAAE,QAAQ,QAAQ;AAAA,QACrC,GAAG,KAAK;AACR,qBAAa,MAAM;AAAA,MACrB;AACA,eAAS;AAAA,IACX;AAEA,WAAO;AAAA,MACL;AAAA,MACA,UAAU;AACR,mBAAW;AACX,YAAI,aAAc,cAAa,YAAY;AAC3C,uBAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/cluster.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/cluster.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Cluster } from 'ioredis'\nimport type { RespClient } from './client'\n\nexport function isClusterClient(client: RespClient): client is Cluster {\n return (client as { isCluster?: unknown }).isCluster === true\n}\n"],
|
|
5
|
+
"mappings": "AAGO,SAAS,gBAAgB,QAAuC;AACrE,SAAQ,OAAmC,cAAc;AAC3D;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createRespCacheStrategy } from "./strategy.js";
|
|
2
|
+
import { createIoredisClientFactory, RESP_MIN_REFRESH_DELAY_MS, respReconnectDelay } from "./client.js";
|
|
3
|
+
import { isClusterClient } from "./cluster.js";
|
|
4
|
+
import { buildRespKeyLayout, escapeRespGlob, literalPatternPrefix, RESP_KEY_ROOT, RESP_LAYOUT_VERSION } from "./layout.js";
|
|
5
|
+
import { DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, RESP_SCRIPTS, WRITE_ENTRY, sha1Hex } from "./scripts.js";
|
|
6
|
+
import {
|
|
7
|
+
createRespSettingsSchema,
|
|
8
|
+
createRespStandaloneSettingsSchema,
|
|
9
|
+
redactRespSettings,
|
|
10
|
+
respClusterSettingsSchema,
|
|
11
|
+
respTransportWarnings,
|
|
12
|
+
respStandaloneSettingsSchema,
|
|
13
|
+
respTlsSettingsSchema,
|
|
14
|
+
RESP_DEFAULTS,
|
|
15
|
+
RESP_LIMITS
|
|
16
|
+
} from "./settings.js";
|
|
17
|
+
import { detectRespServer, parseRespServerInfo } from "./server.js";
|
|
18
|
+
import { createRespCacheProvider } from "./provider.js";
|
|
19
|
+
export {
|
|
20
|
+
DELETE_IF_UNCHANGED,
|
|
21
|
+
REAP_TAG_MEMBERS,
|
|
22
|
+
RESP_DEFAULTS,
|
|
23
|
+
RESP_KEY_ROOT,
|
|
24
|
+
RESP_LAYOUT_VERSION,
|
|
25
|
+
RESP_LIMITS,
|
|
26
|
+
RESP_MIN_REFRESH_DELAY_MS,
|
|
27
|
+
RESP_SCRIPTS,
|
|
28
|
+
WRITE_ENTRY,
|
|
29
|
+
buildRespKeyLayout,
|
|
30
|
+
createIoredisClientFactory,
|
|
31
|
+
createRespCacheProvider,
|
|
32
|
+
createRespCacheStrategy,
|
|
33
|
+
createRespSettingsSchema,
|
|
34
|
+
createRespStandaloneSettingsSchema,
|
|
35
|
+
detectRespServer,
|
|
36
|
+
escapeRespGlob,
|
|
37
|
+
isClusterClient,
|
|
38
|
+
literalPatternPrefix,
|
|
39
|
+
parseRespServerInfo,
|
|
40
|
+
redactRespSettings,
|
|
41
|
+
respClusterSettingsSchema,
|
|
42
|
+
respReconnectDelay,
|
|
43
|
+
respStandaloneSettingsSchema,
|
|
44
|
+
respTlsSettingsSchema,
|
|
45
|
+
respTransportWarnings,
|
|
46
|
+
sha1Hex
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["export { createRespCacheStrategy } from './strategy'\nexport type {\n RespCacheStrategy,\n RespCacheStrategyOptions,\n RespCacheStrategyTimeouts,\n RespStrategyClientFactory,\n} from './strategy'\nexport { createIoredisClientFactory, RESP_MIN_REFRESH_DELAY_MS, respReconnectDelay } from './client'\nexport type {\n RespClient,\n RespClientFactory,\n RespClientFactoryOptions,\n RespCredentials,\n RespCredentialsProvider,\n RespManagedClient,\n RespRefreshSchedule,\n} from './client'\nexport { isClusterClient } from './cluster'\nexport { buildRespKeyLayout, escapeRespGlob, literalPatternPrefix, RESP_KEY_ROOT, RESP_LAYOUT_VERSION } from './layout'\nexport type { RespKeyLayout } from './layout'\nexport { DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, RESP_SCRIPTS, WRITE_ENTRY, sha1Hex } from './scripts'\nexport type { RespScript } from './scripts'\nexport {\n createRespSettingsSchema,\n createRespStandaloneSettingsSchema,\n redactRespSettings,\n respClusterSettingsSchema,\n respTransportWarnings,\n respStandaloneSettingsSchema,\n respTlsSettingsSchema,\n RESP_DEFAULTS,\n RESP_LIMITS,\n} from './settings'\nexport type {\n RespClusterSettings,\n RespSettings,\n RespSettingsInput,\n RespStandaloneSettings,\n RespTlsSettings,\n RespTransportWarning,\n} from './settings'\nexport { detectRespServer, parseRespServerInfo } from './server'\nexport type { RespServerEngine, RespServerInfo } from './server'\nexport { createRespCacheProvider } from './provider'\nexport type { RespCacheProviderOptions } from './provider'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,+BAA+B;AAOxC,SAAS,4BAA4B,2BAA2B,0BAA0B;AAU1F,SAAS,uBAAuB;AAChC,SAAS,oBAAoB,gBAAgB,sBAAsB,eAAe,2BAA2B;AAE7G,SAAS,qBAAqB,kBAAkB,cAAc,aAAa,eAAe;AAE1F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AASP,SAAS,kBAAkB,2BAA2B;AAEtD,SAAS,+BAA+B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/layout.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const RESP_LAYOUT_VERSION = 1;
|
|
2
|
+
const RESP_KEY_ROOT = "om";
|
|
3
|
+
const GLOB_SPECIAL_CHARACTERS = /[*?[\]\\]/g;
|
|
4
|
+
const NAMESPACE_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/;
|
|
5
|
+
function escapeRespGlob(literal) {
|
|
6
|
+
return literal.replace(GLOB_SPECIAL_CHARACTERS, (character) => `\\${character}`);
|
|
7
|
+
}
|
|
8
|
+
function literalPatternPrefix(pattern) {
|
|
9
|
+
if (!pattern) return "";
|
|
10
|
+
const wildcard = pattern.search(/[*?]/);
|
|
11
|
+
return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
|
|
12
|
+
}
|
|
13
|
+
function buildRespKeyLayout(namespace) {
|
|
14
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
15
|
+
throw new Error('[internal] RESP cache namespace must be 1-64 characters of letters, digits, ".", "_" or "-"');
|
|
16
|
+
}
|
|
17
|
+
const prefix = `${RESP_KEY_ROOT}:{${namespace}}:`;
|
|
18
|
+
const valuePrefix = `${prefix}v:`;
|
|
19
|
+
const tagPrefix = `${prefix}t:`;
|
|
20
|
+
return {
|
|
21
|
+
namespace,
|
|
22
|
+
prefix,
|
|
23
|
+
valuePrefix,
|
|
24
|
+
tagPrefix,
|
|
25
|
+
valueKey: (physicalKey) => `${valuePrefix}${physicalKey}`,
|
|
26
|
+
tagKey: (tag) => `${tagPrefix}${tag}`,
|
|
27
|
+
physicalKeyFromValueKey: (valueKey) => valueKey.startsWith(valuePrefix) ? valueKey.slice(valuePrefix.length) : null,
|
|
28
|
+
valueScanPattern: (pattern) => `${escapeRespGlob(valuePrefix)}${escapeRespGlob(literalPatternPrefix(pattern))}*`,
|
|
29
|
+
tagScanPattern: () => `${escapeRespGlob(tagPrefix)}*`
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export {
|
|
33
|
+
RESP_KEY_ROOT,
|
|
34
|
+
RESP_LAYOUT_VERSION,
|
|
35
|
+
buildRespKeyLayout,
|
|
36
|
+
escapeRespGlob,
|
|
37
|
+
literalPatternPrefix
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=layout.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/layout.ts"],
|
|
4
|
+
"sourcesContent": ["export const RESP_LAYOUT_VERSION = 1\nexport const RESP_KEY_ROOT = 'om'\n\nconst GLOB_SPECIAL_CHARACTERS = /[*?[\\]\\\\]/g\nconst NAMESPACE_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/\n\nexport type RespKeyLayout = {\n namespace: string\n /** `om:{<namespace>}:` \u2014 the `{...}` hash tag pins every key of a namespace to one cluster slot. */\n prefix: string\n valuePrefix: string\n tagPrefix: string\n valueKey(physicalKey: string): string\n tagKey(tag: string): string\n physicalKeyFromValueKey(valueKey: string): string | null\n /** SCAN MATCH pattern covering every value key whose physical key starts with the literal part of `pattern`. */\n valueScanPattern(pattern?: string): string\n tagScanPattern(): string\n}\n\nexport function escapeRespGlob(literal: string): string {\n return literal.replace(GLOB_SPECIAL_CHARACTERS, (character) => `\\\\${character}`)\n}\n\nexport function literalPatternPrefix(pattern: string | undefined): string {\n if (!pattern) return ''\n const wildcard = pattern.search(/[*?]/)\n return wildcard < 0 ? pattern : pattern.slice(0, wildcard)\n}\n\nexport function buildRespKeyLayout(namespace: string): RespKeyLayout {\n if (!NAMESPACE_PATTERN.test(namespace)) {\n throw new Error('[internal] RESP cache namespace must be 1-64 characters of letters, digits, \".\", \"_\" or \"-\"')\n }\n const prefix = `${RESP_KEY_ROOT}:{${namespace}}:`\n const valuePrefix = `${prefix}v:`\n const tagPrefix = `${prefix}t:`\n return {\n namespace,\n prefix,\n valuePrefix,\n tagPrefix,\n valueKey: (physicalKey) => `${valuePrefix}${physicalKey}`,\n tagKey: (tag) => `${tagPrefix}${tag}`,\n physicalKeyFromValueKey: (valueKey) => (valueKey.startsWith(valuePrefix) ? valueKey.slice(valuePrefix.length) : null),\n valueScanPattern: (pattern) => `${escapeRespGlob(valuePrefix)}${escapeRespGlob(literalPatternPrefix(pattern))}*`,\n tagScanPattern: () => `${escapeRespGlob(tagPrefix)}*`,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,sBAAsB;AAC5B,MAAM,gBAAgB;AAE7B,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAgBnB,SAAS,eAAe,SAAyB;AACtD,SAAO,QAAQ,QAAQ,yBAAyB,CAAC,cAAc,KAAK,SAAS,EAAE;AACjF;AAEO,SAAS,qBAAqB,SAAqC;AACxE,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,WAAW,QAAQ,OAAO,MAAM;AACtC,SAAO,WAAW,IAAI,UAAU,QAAQ,MAAM,GAAG,QAAQ;AAC3D;AAEO,SAAS,mBAAmB,WAAkC;AACnE,MAAI,CAAC,kBAAkB,KAAK,SAAS,GAAG;AACtC,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACA,QAAM,SAAS,GAAG,aAAa,KAAK,SAAS;AAC7C,QAAM,cAAc,GAAG,MAAM;AAC7B,QAAM,YAAY,GAAG,MAAM;AAC3B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,CAAC,gBAAgB,GAAG,WAAW,GAAG,WAAW;AAAA,IACvD,QAAQ,CAAC,QAAQ,GAAG,SAAS,GAAG,GAAG;AAAA,IACnC,yBAAyB,CAAC,aAAc,SAAS,WAAW,WAAW,IAAI,SAAS,MAAM,YAAY,MAAM,IAAI;AAAA,IAChH,kBAAkB,CAAC,YAAY,GAAG,eAAe,WAAW,CAAC,GAAG,eAAe,qBAAqB,OAAO,CAAC,CAAC;AAAA,IAC7G,gBAAgB,MAAM,GAAG,eAAe,SAAS,CAAC;AAAA,EACpD;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createIoredisClientFactory } from "./client.js";
|
|
2
|
+
import { detectRespServer } from "./server.js";
|
|
3
|
+
import { redactRespSettings, respTransportWarnings } from "./settings.js";
|
|
4
|
+
import { createRespCacheStrategy } from "./strategy.js";
|
|
5
|
+
const ERROR_LOG_INTERVAL_MS = 3e4;
|
|
6
|
+
const TRANSPORT_WARNING_MESSAGES = {
|
|
7
|
+
tls_verification_disabled: "TLS server certificate verification is disabled (tls.rejectUnauthorized: false); the connection is open to interception",
|
|
8
|
+
credentials_over_plaintext: "credentials are sent over a plaintext connection; configure tls"
|
|
9
|
+
};
|
|
10
|
+
function createRespCacheProvider(options) {
|
|
11
|
+
return {
|
|
12
|
+
id: options.id,
|
|
13
|
+
settings: options.settings,
|
|
14
|
+
capability() {
|
|
15
|
+
return { placement: "shared" };
|
|
16
|
+
},
|
|
17
|
+
async create(config, context) {
|
|
18
|
+
let lastErrorLoggedAt = 0;
|
|
19
|
+
const extra = options.clientOptions ? options.clientOptions(config, context) : {};
|
|
20
|
+
for (const warning of respTransportWarnings(config, { externalCredentials: extra.credentialsProvider !== void 0 })) {
|
|
21
|
+
context.logger.warn(TRANSPORT_WARNING_MESSAGES[warning]);
|
|
22
|
+
}
|
|
23
|
+
const factory = createIoredisClientFactory(config, {
|
|
24
|
+
...extra,
|
|
25
|
+
onError: (error) => {
|
|
26
|
+
extra.onError?.(error);
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
if (now - lastErrorLoggedAt < ERROR_LOG_INTERVAL_MS) return;
|
|
29
|
+
lastErrorLoggedAt = now;
|
|
30
|
+
context.logger.warn("connection error; the client is reconnecting", { error });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
const managed = await factory();
|
|
34
|
+
const strategy = await createRespCacheStrategy(() => managed, {
|
|
35
|
+
namespace: context.namespace,
|
|
36
|
+
helpers: context.helpers,
|
|
37
|
+
logger: context.logger,
|
|
38
|
+
...context.defaultTtl !== void 0 ? { defaultTtl: context.defaultTtl } : {},
|
|
39
|
+
batchSize: config.batchSize,
|
|
40
|
+
maxValueBytes: config.maxValueBytes,
|
|
41
|
+
timeouts: { connectMs: config.connectTimeoutMs }
|
|
42
|
+
});
|
|
43
|
+
if (options.expectedEngine) {
|
|
44
|
+
const server = await detectRespServer(managed.client);
|
|
45
|
+
if (server && server.engine !== options.expectedEngine) {
|
|
46
|
+
context.logger.warn("endpoint reports a different engine than this provider is qualified for", {
|
|
47
|
+
expected: options.expectedEngine,
|
|
48
|
+
reported: server.engine,
|
|
49
|
+
version: server.version
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return strategy;
|
|
54
|
+
},
|
|
55
|
+
redact(config) {
|
|
56
|
+
return redactRespSettings(config);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export {
|
|
61
|
+
createRespCacheProvider
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/provider.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n CacheProviderCapability,\n CacheProviderDefinition,\n CacheProviderHostContext,\n CacheProviderSettingsSchema,\n} from '@open-mercato/cache/provider'\nimport type { CacheStrategy } from '@open-mercato/cache/types'\nimport { createIoredisClientFactory } from './client'\nimport type { RespClientFactoryOptions } from './client'\nimport { detectRespServer } from './server'\nimport type { RespServerEngine } from './server'\nimport { redactRespSettings, respTransportWarnings } from './settings'\nimport type { RespSettings } from './settings'\nimport { createRespCacheStrategy } from './strategy'\n\nexport type RespCacheProviderOptions<TConfig extends RespSettings> = {\n id: string\n settings: CacheProviderSettingsSchema<TConfig>\n /** Engine the package is qualified against; a different engine behind the endpoint is logged once. */\n expectedEngine?: RespServerEngine\n clientOptions?: (config: TConfig, context: CacheProviderHostContext) => RespClientFactoryOptions\n}\n\nconst ERROR_LOG_INTERVAL_MS = 30_000\n\nconst TRANSPORT_WARNING_MESSAGES = {\n tls_verification_disabled: 'TLS server certificate verification is disabled (tls.rejectUnauthorized: false); the connection is open to interception',\n credentials_over_plaintext: 'credentials are sent over a plaintext connection; configure tls',\n} as const\n\n/**\n * Build everything a RESP cache provider definition needs except `apiVersion`,\n * so the provider package passes it to `defineCacheProvider` itself.\n */\nexport function createRespCacheProvider<TConfig extends RespSettings>(\n options: RespCacheProviderOptions<TConfig>,\n): Omit<CacheProviderDefinition<TConfig>, 'apiVersion'> {\n return {\n id: options.id,\n settings: options.settings,\n capability(): CacheProviderCapability {\n return { placement: 'shared' }\n },\n async create(config: TConfig, context: CacheProviderHostContext): Promise<CacheStrategy> {\n let lastErrorLoggedAt = 0\n const extra = options.clientOptions ? options.clientOptions(config, context) : {}\n for (const warning of respTransportWarnings(config, { externalCredentials: extra.credentialsProvider !== undefined })) {\n context.logger.warn(TRANSPORT_WARNING_MESSAGES[warning])\n }\n const factory = createIoredisClientFactory(config, {\n ...extra,\n onError: (error) => {\n extra.onError?.(error)\n const now = Date.now()\n if (now - lastErrorLoggedAt < ERROR_LOG_INTERVAL_MS) return\n lastErrorLoggedAt = now\n context.logger.warn('connection error; the client is reconnecting', { error })\n },\n })\n const managed = await factory()\n const strategy = await createRespCacheStrategy(() => managed, {\n namespace: context.namespace,\n helpers: context.helpers,\n logger: context.logger,\n ...(context.defaultTtl !== undefined ? { defaultTtl: context.defaultTtl } : {}),\n batchSize: config.batchSize,\n maxValueBytes: config.maxValueBytes,\n timeouts: { connectMs: config.connectTimeoutMs },\n })\n if (options.expectedEngine) {\n const server = await detectRespServer(managed.client)\n if (server && server.engine !== options.expectedEngine) {\n context.logger.warn('endpoint reports a different engine than this provider is qualified for', {\n expected: options.expectedEngine,\n reported: server.engine,\n version: server.version,\n })\n }\n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AAe,OAAO;AAAA,QACtB,UAAU,EAAE,WAAW,OAAO,iBAAiB;AAAA,MACjD,CAAC;AACD,UAAI,QAAQ,gBAAgB;AAC1B,cAAM,SAAS,MAAM,iBAAiB,QAAQ,MAAM;AACpD,YAAI,UAAU,OAAO,WAAW,QAAQ,gBAAgB;AACtD,kBAAQ,OAAO,KAAK,2EAA2E;AAAA,YAC7F,UAAU,QAAQ;AAAA,YAClB,UAAU,OAAO;AAAA,YACjB,SAAS,OAAO;AAAA,UAClB,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,OAAO,QAA0C;AAC/C,aAAO,mBAAmB,MAAM;AAAA,IAClC;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/scripts.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
function defineScript(name, source) {
|
|
3
|
+
return { name, source, sha: createHash("sha1").update(source).digest("hex") };
|
|
4
|
+
}
|
|
5
|
+
const DELETE_IF_UNCHANGED = defineScript("om_cache_delete_if_unchanged", `
|
|
6
|
+
local removed = 0
|
|
7
|
+
local keyIndex = 1
|
|
8
|
+
local argIndex = 1
|
|
9
|
+
while argIndex <= #ARGV do
|
|
10
|
+
local expected = ARGV[argIndex]
|
|
11
|
+
local member = ARGV[argIndex + 1]
|
|
12
|
+
local tagCount = tonumber(ARGV[argIndex + 2])
|
|
13
|
+
local current = redis.call('GET', KEYS[keyIndex])
|
|
14
|
+
if current and redis.sha1hex(current) == expected then
|
|
15
|
+
redis.call('DEL', KEYS[keyIndex])
|
|
16
|
+
for offset = 1, tagCount do
|
|
17
|
+
redis.call('SREM', KEYS[keyIndex + offset], member)
|
|
18
|
+
end
|
|
19
|
+
removed = removed + 1
|
|
20
|
+
end
|
|
21
|
+
keyIndex = keyIndex + 1 + tagCount
|
|
22
|
+
argIndex = argIndex + 3
|
|
23
|
+
end
|
|
24
|
+
return removed
|
|
25
|
+
`);
|
|
26
|
+
const REAP_TAG_MEMBERS = defineScript("om_cache_reap_tag_members", `
|
|
27
|
+
local removed = 0
|
|
28
|
+
for keyIndex = 2, #KEYS do
|
|
29
|
+
local argIndex = (keyIndex - 1) * 2 - 1
|
|
30
|
+
local member = ARGV[argIndex]
|
|
31
|
+
local expected = ARGV[argIndex + 1]
|
|
32
|
+
local current = redis.call('GET', KEYS[keyIndex])
|
|
33
|
+
local stale
|
|
34
|
+
if expected == '' then
|
|
35
|
+
stale = (current == false)
|
|
36
|
+
else
|
|
37
|
+
stale = (current ~= false and redis.sha1hex(current) == expected)
|
|
38
|
+
end
|
|
39
|
+
if stale then
|
|
40
|
+
removed = removed + redis.call('SREM', KEYS[1], member)
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
return removed
|
|
44
|
+
`);
|
|
45
|
+
const WRITE_ENTRY = defineScript("om_cache_write_entry", `
|
|
46
|
+
local ttl = tonumber(ARGV[2])
|
|
47
|
+
if ttl then
|
|
48
|
+
redis.call('SET', KEYS[1], ARGV[1], 'PX', ttl)
|
|
49
|
+
else
|
|
50
|
+
redis.call('SET', KEYS[1], ARGV[1])
|
|
51
|
+
end
|
|
52
|
+
for index = 2, #KEYS do
|
|
53
|
+
local tagKey = KEYS[index]
|
|
54
|
+
local current = redis.call('PTTL', tagKey)
|
|
55
|
+
redis.call('SADD', tagKey, ARGV[3])
|
|
56
|
+
if not ttl then
|
|
57
|
+
if current >= 0 then
|
|
58
|
+
redis.call('PERSIST', tagKey)
|
|
59
|
+
end
|
|
60
|
+
elseif current == -2 or (current >= 0 and current < ttl) then
|
|
61
|
+
redis.call('PEXPIRE', tagKey, ttl)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
return 1
|
|
65
|
+
`);
|
|
66
|
+
const RESP_SCRIPTS = [DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, WRITE_ENTRY];
|
|
67
|
+
function sha1Hex(raw) {
|
|
68
|
+
return createHash("sha1").update(raw).digest("hex");
|
|
69
|
+
}
|
|
70
|
+
export {
|
|
71
|
+
DELETE_IF_UNCHANGED,
|
|
72
|
+
REAP_TAG_MEMBERS,
|
|
73
|
+
RESP_SCRIPTS,
|
|
74
|
+
WRITE_ENTRY,
|
|
75
|
+
sha1Hex
|
|
76
|
+
};
|
|
77
|
+
//# sourceMappingURL=scripts.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/scripts.ts"],
|
|
4
|
+
"sourcesContent": ["import { createHash } from 'node:crypto'\n\nexport type RespScript = {\n name: string\n source: string\n sha: string\n}\n\nfunction defineScript(name: string, source: string): RespScript {\n return { name, source, sha: createHash('sha1').update(source).digest('hex') }\n}\n\n/**\n * Compare-and-delete a batch of entries. For every entry ARGV carries\n * `(sha1 of the observed value bytes, member, tag-key count)` and KEYS carries\n * the value key followed by that many tag keys. An entry is deleted, and its\n * member removed from those tag sets, only while its stored bytes still hash to\n * the observed digest; a concurrent rewrite or retag is left untouched.\n */\nexport const DELETE_IF_UNCHANGED = defineScript('om_cache_delete_if_unchanged', `\nlocal removed = 0\nlocal keyIndex = 1\nlocal argIndex = 1\nwhile argIndex <= #ARGV do\n local expected = ARGV[argIndex]\n local member = ARGV[argIndex + 1]\n local tagCount = tonumber(ARGV[argIndex + 2])\n local current = redis.call('GET', KEYS[keyIndex])\n if current and redis.sha1hex(current) == expected then\n redis.call('DEL', KEYS[keyIndex])\n for offset = 1, tagCount do\n redis.call('SREM', KEYS[keyIndex + offset], member)\n end\n removed = removed + 1\n end\n keyIndex = keyIndex + 1 + tagCount\n argIndex = argIndex + 3\nend\nreturn removed\n`)\n\n/**\n * Drop stale members from ONE tag set. KEYS[1] is the tag key, KEYS[2..] the\n * member value keys; ARGV holds `(member, expected digest)` pairs where an empty\n * digest means \"value key must be absent\". A member is removed only while its\n * value is still absent or still the observed bytes whose tags exclude this tag,\n * so a concurrent write that re-adds the tag keeps its membership.\n */\nexport const REAP_TAG_MEMBERS = defineScript('om_cache_reap_tag_members', `\nlocal removed = 0\nfor keyIndex = 2, #KEYS do\n local argIndex = (keyIndex - 1) * 2 - 1\n local member = ARGV[argIndex]\n local expected = ARGV[argIndex + 1]\n local current = redis.call('GET', KEYS[keyIndex])\n local stale\n if expected == '' then\n stale = (current == false)\n else\n stale = (current ~= false and redis.sha1hex(current) == expected)\n end\n if stale then\n removed = removed + redis.call('SREM', KEYS[1], member)\n end\nend\nreturn removed\n`)\n\n/**\n * Write one entry and its tag memberships atomically. KEYS[1] is the value key,\n * KEYS[2..] the tag keys; ARGV is `(payload, ttl ms or '' for no TTL, member)`.\n * A tag set lives at least as long as its longest-lived member: a fresh set\n * takes the entry TTL, an existing volatile set only ever extends, and a\n * member without TTL makes the set persistent. Plain Lua instead of\n * `PEXPIRE \u2026 GT` because KeyDB 6.3 (Redis 6.2 base) has no GT flag.\n */\nexport const WRITE_ENTRY = defineScript('om_cache_write_entry', `\nlocal ttl = tonumber(ARGV[2])\nif ttl then\n redis.call('SET', KEYS[1], ARGV[1], 'PX', ttl)\nelse\n redis.call('SET', KEYS[1], ARGV[1])\nend\nfor index = 2, #KEYS do\n local tagKey = KEYS[index]\n local current = redis.call('PTTL', tagKey)\n redis.call('SADD', tagKey, ARGV[3])\n if not ttl then\n if current >= 0 then\n redis.call('PERSIST', tagKey)\n end\n elseif current == -2 or (current >= 0 and current < ttl) then\n redis.call('PEXPIRE', tagKey, ttl)\n end\nend\nreturn 1\n`)\n\nexport const RESP_SCRIPTS: ReadonlyArray<RespScript> = [DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, WRITE_ENTRY]\n\nexport function sha1Hex(raw: Buffer | string): string {\n return createHash('sha1').update(raw).digest('hex')\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAQ3B,SAAS,aAAa,MAAc,QAA4B;AAC9D,SAAO,EAAE,MAAM,QAAQ,KAAK,WAAW,MAAM,EAAE,OAAO,MAAM,EAAE,OAAO,KAAK,EAAE;AAC9E;AASO,MAAM,sBAAsB,aAAa,gCAAgC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAoB/E;AASM,MAAM,mBAAmB,aAAa,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAkBzE;AAUM,MAAM,cAAc,aAAa,wBAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAoB/D;AAEM,MAAM,eAA0C,CAAC,qBAAqB,kBAAkB,WAAW;AAEnG,SAAS,QAAQ,KAA8B;AACpD,SAAO,WAAW,MAAM,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK;AACpD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|