@geekmidas/cache 10.0.0-alpha.79 → 10.0.0-alpha.81
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/dist/postgres.cjs +19 -12
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.d.cts.map +1 -1
- package/dist/postgres.d.mts.map +1 -1
- package/dist/postgres.mjs +19 -12
- package/dist/postgres.mjs.map +1 -1
- package/dist/redis.cjs +21 -14
- package/dist/redis.cjs.map +1 -1
- package/dist/redis.d.cts.map +1 -1
- package/dist/redis.d.mts.map +1 -1
- package/dist/redis.mjs +21 -14
- package/dist/redis.mjs.map +1 -1
- package/dist/telemetry.cjs +38 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +6 -0
- package/dist/telemetry.d.cts.map +1 -0
- package/dist/telemetry.d.mts +6 -0
- package/dist/telemetry.d.mts.map +1 -0
- package/dist/telemetry.mjs +37 -0
- package/dist/telemetry.mjs.map +1 -0
- package/package.json +3 -1
package/dist/postgres.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
|
|
3
|
+
const require_telemetry = require("./telemetry.cjs");
|
|
3
4
|
let pg = require("pg");
|
|
4
5
|
pg = require_rolldown_runtime.__toESM(pg, 1);
|
|
5
6
|
//#region src/postgres.ts
|
|
@@ -33,22 +34,28 @@ var PostgresCache = class {
|
|
|
33
34
|
this.table = options.table ?? DEFAULT_TABLE;
|
|
34
35
|
}
|
|
35
36
|
async get(key) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
return require_telemetry.traceCache("postgresql", "get", async () => {
|
|
38
|
+
const { rows } = await this.query(`SELECT value FROM ${this.identifier()}
|
|
39
|
+
WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
|
|
40
|
+
return rows[0]?.value;
|
|
41
|
+
});
|
|
39
42
|
}
|
|
40
43
|
async set(key, value, ttl) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
return require_telemetry.traceCache("postgresql", "set", async () => {
|
|
45
|
+
await this.query(`INSERT INTO ${this.identifier()} (key, value, expires_at)
|
|
46
|
+
VALUES ($1, $2::jsonb, ${ttl === void 0 ? "NULL" : "now() + ($3 || ' seconds')::interval"})
|
|
47
|
+
ON CONFLICT (key) DO UPDATE
|
|
48
|
+
SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`, ttl === void 0 ? [key, JSON.stringify(value)] : [
|
|
49
|
+
key,
|
|
50
|
+
JSON.stringify(value),
|
|
51
|
+
String(ttl)
|
|
52
|
+
]);
|
|
53
|
+
});
|
|
49
54
|
}
|
|
50
55
|
async delete(key) {
|
|
51
|
-
|
|
56
|
+
return require_telemetry.traceCache("postgresql", "delete", async () => {
|
|
57
|
+
await this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);
|
|
58
|
+
});
|
|
52
59
|
}
|
|
53
60
|
async ttl(key) {
|
|
54
61
|
const { rows } = await this.query(`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds
|
package/dist/postgres.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.cjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["/**\n * A cache that lives in a database you already have.\n *\n * The backend with no infrastructure. A cache is a table; the database is the\n * one the application already declared, so an idle stage costs nothing extra\n * and there is one fewer thing to provision, secure and pay for. It is slower\n * than Redis and that is the trade: for session lookups, rate-limit counters and\n * memoised API responses at ordinary volumes, a primary-key hit on a small table\n * is not the thing that will be slow.\n *\n * **The table is provisioned, not created on first use.** That is the one place\n * this differs from pg-boss, and the reason is the role split: a handler\n * connects as a role that may read and write rows and may not create anything,\n * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where\n * the roles are doing their job. The DDL is exported instead — see\n * {@link cacheTableStatements} — and applied by whatever applies the rest.\n *\n * Reads filter on expiry and delete lazily, so an expired row is never returned\n * even if nothing has swept it; a sweep is an optimisation, not a correctness\n * requirement.\n */\n\nimport pg, { type Pool } from 'pg';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport interface PostgresCacheOptions {\n\t/**\n\t * The table to keep entries in, schema-qualified if it needs to be.\n\t *\n\t * Defaults to `cache`. It resolves against the connection's `search_path`,\n\t * which the role carries — so a tenant's cache lands in the tenant's schema\n\t * without anything here knowing the schema's name.\n\t */\n\ttable?: string;\n}\n\nconst DEFAULT_TABLE = 'cache';\n\nexport class PostgresCache implements Cache {\n\tprivate readonly table: string;\n\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\toptions: PostgresCacheOptions = {},\n\t) {\n\t\tthis.table = options.table ?? DEFAULT_TABLE;\n\t}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst { rows } = await this.query<{ value: T }>(\n\t\t\t`SELECT value FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\treturn rows[0]?.value;\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\t// `now() + interval` computed by the server, not by this process: a\n\t\t// client whose clock is minutes off would otherwise write entries that\n\t\t// expire early or late, and clock skew is not a thing to debug through a\n\t\t// cache.\n\t\tawait this.query(\n\t\t\t`INSERT INTO ${this.identifier()} (key, value, expires_at)\n\t\t\t VALUES ($1, $2::jsonb, ${ttl === undefined ? 'NULL' : \"now() + ($3 || ' seconds')::interval\"})\n\t\t\t ON CONFLICT (key) DO UPDATE\n\t\t\t SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`,\n\t\t\tttl === undefined\n\t\t\t\t? [key, JSON.stringify(value)]\n\t\t\t\t: [key, JSON.stringify(value), String(ttl)],\n\t\t);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst { rows } = await this.query<{ seconds: number | null }>(\n\t\t\t`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds\n\t\t\t FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\tconst row = rows[0];\n\t\tif (!row) return 0;\n\n\t\t// A row with no expiry has no time *left* to report. Zero is what the\n\t\t// interface says a missing key returns, and \"never expires\" is closer to\n\t\t// that than to any number this could invent.\n\t\treturn row.seconds ?? 0;\n\t}\n\n\t/**\n\t * Delete every expired entry.\n\t *\n\t * Optional: reads already ignore them. Worth running occasionally so the\n\t * table does not grow without bound in a workload that writes many keys once.\n\t */\n\tasync sweep(): Promise<number> {\n\t\tconst { rowCount } = await this.query(\n\t\t\t`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`,\n\t\t);\n\n\t\treturn rowCount ?? 0;\n\t}\n\n\tprivate async query<T>(\n\t\tsql: string,\n\t\tvalues: unknown[] = [],\n\t): Promise<{ rows: T[]; rowCount: number | null }> {\n\t\tconst result = await this.pool.query(sql, values);\n\n\t\treturn { rows: result.rows as T[], rowCount: result.rowCount };\n\t}\n\n\t/**\n\t * The table name as an identifier.\n\t *\n\t * Quoted per segment so a schema-qualified name stays two identifiers rather\n\t * than becoming one with a dot in it. The name comes from configuration\n\t * rather than from a request, so this is defence rather than sanitisation.\n\t */\n\tprivate identifier(): string {\n\t\treturn quote(this.table);\n\t}\n}\n\n/**\n * The `postgres://` driver.\n *\n * One pool per URL, cached for the life of the process: a cache that opened a\n * connection per call would be slower than the thing it exists to speed up, and\n * a Lambda reusing a warm container should reuse the pool with it.\n *\n * `pg` is imported at the top of this module rather than lazily, because the\n * *module* is the lazy boundary — an app caching in Redis never imports\n * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same\n * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.\n */\nexport const postgresCacheDriver: CacheDriver = {\n\tscheme: 'postgres:',\n\tcreate(url) {\n\t\t// The table travels in the URL, the way pg-boss's schema does.\n\t\t//\n\t\t// It has to, because a database-backed cache has no address of its own:\n\t\t// two caches in one database resolve the *same* connection string, so a\n\t\t// client built from the URL alone cannot tell them apart and both would\n\t\t// read and write one table — sharing a keyspace and evicting each other's\n\t\t// keys. The parameter is what makes the address identify the cache.\n\t\tconst { connectionString, table } = split(url);\n\n\t\tconst existing = pools.get(connectionString);\n\t\tconst pool = existing ?? new pg.Pool({ connectionString });\n\t\tif (!existing) pools.set(connectionString, pool);\n\n\t\t// One pool per database, shared by every cache in it — the table is the\n\t\t// client's, not the pool's.\n\t\treturn new PostgresCache(pool, table ? { table } : {});\n\t},\n};\n\n/**\n * A cache URL as its two facts: where to connect, and what to read.\n *\n * `table` is removed from the string handed to `pg` rather than left on it,\n * because a Postgres connection string carries libpq parameters and an unknown\n * one is not guaranteed to be ignored — and because the pool should be shared\n * by every cache in the database, which only works if the key does not vary\n * per cache.\n */\nfunction split(url: string): { connectionString: string; table?: string } {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tconst table = parsed.searchParams.get('table') ?? undefined;\n\n\t\tif (!table) return { connectionString: url };\n\n\t\tparsed.searchParams.delete('table');\n\n\t\treturn { connectionString: parsed.toString(), table };\n\t} catch {\n\t\t// Not a URL `URL` can parse. The driver's job is not to validate one, so\n\t\t// this hands it to `pg` unchanged and lets that failure be the one\n\t\t// reported.\n\t\treturn { connectionString: url };\n\t}\n}\n\nconst pools = new Map<string, Pool>();\n\n/**\n * The DDL a Postgres-backed cache needs, for whoever applies DDL.\n *\n * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same\n * statements run in-process from `gkm dev` and from a provisioner inside a VPC,\n * and one implementation is what stops \"works locally, fails deployed\".\n *\n * Run as the schema's **owner**. The role a handler connects as cannot create a\n * table, which is the point of the split and the reason this is not done lazily.\n */\nexport function cacheTableStatements(options: PostgresCacheOptions = {}): {\n\tdescribe: string;\n\texists?: { sql: string; values: unknown[] };\n\tsql: string;\n}[] {\n\tconst table = options.table ?? DEFAULT_TABLE;\n\tconst [schema, name] = table.includes('.')\n\t\t? (table.split('.') as [string, string])\n\t\t: [undefined, table];\n\tconst qualified = quote(table);\n\n\treturn [\n\t\t{\n\t\t\tdescribe: `cache table ${table}`,\n\t\t\texists: {\n\t\t\t\tsql: schema\n\t\t\t\t\t? 'SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2'\n\t\t\t\t\t: 'SELECT 1 FROM information_schema.tables WHERE table_name = $1',\n\t\t\t\tvalues: schema ? [schema, name] : [name],\n\t\t\t},\n\t\t\tsql: `CREATE TABLE ${qualified} (\n\t\t\t\tkey text PRIMARY KEY,\n\t\t\t\tvalue jsonb NOT NULL,\n\t\t\t\texpires_at timestamptz\n\t\t\t)`,\n\t\t},\n\t\t{\n\t\t\t// Only the expiring rows: a partial index stays small in a cache whose\n\t\t\t// entries mostly never expire, and the sweep only ever looks at those.\n\t\t\tdescribe: `cache expiry index on ${table}`,\n\t\t\tsql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}\n\t\t\t ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`,\n\t\t},\n\t];\n}\n\n/** A possibly schema-qualified name, quoted per segment. */\nfunction quote(table: string): string {\n\treturn table\n\t\t.split('.')\n\t\t.map((part) => `\"${part.replace(/\"/g, '\"\"')}\"`)\n\t\t.join('.');\n}\n\nfunction indexName(table: string): string {\n\treturn `\"${table.replace(/[^a-zA-Z0-9]/g, '_')}_expires_at_idx\"`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,gBAAgB;AAEtB,IAAa,gBAAb,MAA4C;CAIzB;CAHlB;CAEA,YACC,MACA,UAAgC,CAAC,GAChC;EAFgB,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,GAAG;AACX;AAEA,SAAS,UAAU,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;AAChD"}
|
|
1
|
+
{"version":3,"file":"postgres.cjs","names":["traceCache"],"sources":["../src/postgres.ts"],"sourcesContent":["/**\n * A cache that lives in a database you already have.\n *\n * The backend with no infrastructure. A cache is a table; the database is the\n * one the application already declared, so an idle stage costs nothing extra\n * and there is one fewer thing to provision, secure and pay for. It is slower\n * than Redis and that is the trade: for session lookups, rate-limit counters and\n * memoised API responses at ordinary volumes, a primary-key hit on a small table\n * is not the thing that will be slow.\n *\n * **The table is provisioned, not created on first use.** That is the one place\n * this differs from pg-boss, and the reason is the role split: a handler\n * connects as a role that may read and write rows and may not create anything,\n * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where\n * the roles are doing their job. The DDL is exported instead — see\n * {@link cacheTableStatements} — and applied by whatever applies the rest.\n *\n * Reads filter on expiry and delete lazily, so an expired row is never returned\n * even if nothing has swept it; a sweep is an optimisation, not a correctness\n * requirement.\n */\n\nimport pg, { type Pool } from 'pg';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\nimport { traceCache } from './telemetry';\n\nexport interface PostgresCacheOptions {\n\t/**\n\t * The table to keep entries in, schema-qualified if it needs to be.\n\t *\n\t * Defaults to `cache`. It resolves against the connection's `search_path`,\n\t * which the role carries — so a tenant's cache lands in the tenant's schema\n\t * without anything here knowing the schema's name.\n\t */\n\ttable?: string;\n}\n\nconst DEFAULT_TABLE = 'cache';\n\nexport class PostgresCache implements Cache {\n\tprivate readonly table: string;\n\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\toptions: PostgresCacheOptions = {},\n\t) {\n\t\tthis.table = options.table ?? DEFAULT_TABLE;\n\t}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\treturn traceCache('postgresql', 'get', async () => {\n\t\t\tconst { rows } = await this.query<{ value: T }>(\n\t\t\t\t`SELECT value FROM ${this.identifier()}\n\t\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t\t[key],\n\t\t\t);\n\n\t\t\treturn rows[0]?.value;\n\t\t});\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\treturn traceCache('postgresql', 'set', async () => {\n\t\t\t// `now() + interval` computed by the server, not by this process: a\n\t\t\t// client whose clock is minutes off would otherwise write entries that\n\t\t\t// expire early or late, and clock skew is not a thing to debug through a\n\t\t\t// cache.\n\t\t\tawait this.query(\n\t\t\t\t`INSERT INTO ${this.identifier()} (key, value, expires_at)\n\t\t\t\t VALUES ($1, $2::jsonb, ${ttl === undefined ? 'NULL' : \"now() + ($3 || ' seconds')::interval\"})\n\t\t\t\t ON CONFLICT (key) DO UPDATE\n\t\t\t\t SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`,\n\t\t\t\tttl === undefined\n\t\t\t\t\t? [key, JSON.stringify(value)]\n\t\t\t\t\t: [key, JSON.stringify(value), String(ttl)],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\treturn traceCache('postgresql', 'delete', async () => {\n\t\t\tawait this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [\n\t\t\t\tkey,\n\t\t\t]);\n\t\t});\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst { rows } = await this.query<{ seconds: number | null }>(\n\t\t\t`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds\n\t\t\t FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\tconst row = rows[0];\n\t\tif (!row) return 0;\n\n\t\t// A row with no expiry has no time *left* to report. Zero is what the\n\t\t// interface says a missing key returns, and \"never expires\" is closer to\n\t\t// that than to any number this could invent.\n\t\treturn row.seconds ?? 0;\n\t}\n\n\t/**\n\t * Delete every expired entry.\n\t *\n\t * Optional: reads already ignore them. Worth running occasionally so the\n\t * table does not grow without bound in a workload that writes many keys once.\n\t */\n\tasync sweep(): Promise<number> {\n\t\tconst { rowCount } = await this.query(\n\t\t\t`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`,\n\t\t);\n\n\t\treturn rowCount ?? 0;\n\t}\n\n\tprivate async query<T>(\n\t\tsql: string,\n\t\tvalues: unknown[] = [],\n\t): Promise<{ rows: T[]; rowCount: number | null }> {\n\t\tconst result = await this.pool.query(sql, values);\n\n\t\treturn { rows: result.rows as T[], rowCount: result.rowCount };\n\t}\n\n\t/**\n\t * The table name as an identifier.\n\t *\n\t * Quoted per segment so a schema-qualified name stays two identifiers rather\n\t * than becoming one with a dot in it. The name comes from configuration\n\t * rather than from a request, so this is defence rather than sanitisation.\n\t */\n\tprivate identifier(): string {\n\t\treturn quote(this.table);\n\t}\n}\n\n/**\n * The `postgres://` driver.\n *\n * One pool per URL, cached for the life of the process: a cache that opened a\n * connection per call would be slower than the thing it exists to speed up, and\n * a Lambda reusing a warm container should reuse the pool with it.\n *\n * `pg` is imported at the top of this module rather than lazily, because the\n * *module* is the lazy boundary — an app caching in Redis never imports\n * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same\n * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.\n */\nexport const postgresCacheDriver: CacheDriver = {\n\tscheme: 'postgres:',\n\tcreate(url) {\n\t\t// The table travels in the URL, the way pg-boss's schema does.\n\t\t//\n\t\t// It has to, because a database-backed cache has no address of its own:\n\t\t// two caches in one database resolve the *same* connection string, so a\n\t\t// client built from the URL alone cannot tell them apart and both would\n\t\t// read and write one table — sharing a keyspace and evicting each other's\n\t\t// keys. The parameter is what makes the address identify the cache.\n\t\tconst { connectionString, table } = split(url);\n\n\t\tconst existing = pools.get(connectionString);\n\t\tconst pool = existing ?? new pg.Pool({ connectionString });\n\t\tif (!existing) pools.set(connectionString, pool);\n\n\t\t// One pool per database, shared by every cache in it — the table is the\n\t\t// client's, not the pool's.\n\t\treturn new PostgresCache(pool, table ? { table } : {});\n\t},\n};\n\n/**\n * A cache URL as its two facts: where to connect, and what to read.\n *\n * `table` is removed from the string handed to `pg` rather than left on it,\n * because a Postgres connection string carries libpq parameters and an unknown\n * one is not guaranteed to be ignored — and because the pool should be shared\n * by every cache in the database, which only works if the key does not vary\n * per cache.\n */\nfunction split(url: string): { connectionString: string; table?: string } {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tconst table = parsed.searchParams.get('table') ?? undefined;\n\n\t\tif (!table) return { connectionString: url };\n\n\t\tparsed.searchParams.delete('table');\n\n\t\treturn { connectionString: parsed.toString(), table };\n\t} catch {\n\t\t// Not a URL `URL` can parse. The driver's job is not to validate one, so\n\t\t// this hands it to `pg` unchanged and lets that failure be the one\n\t\t// reported.\n\t\treturn { connectionString: url };\n\t}\n}\n\nconst pools = new Map<string, Pool>();\n\n/**\n * The DDL a Postgres-backed cache needs, for whoever applies DDL.\n *\n * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same\n * statements run in-process from `gkm dev` and from a provisioner inside a VPC,\n * and one implementation is what stops \"works locally, fails deployed\".\n *\n * Run as the schema's **owner**. The role a handler connects as cannot create a\n * table, which is the point of the split and the reason this is not done lazily.\n */\nexport function cacheTableStatements(options: PostgresCacheOptions = {}): {\n\tdescribe: string;\n\texists?: { sql: string; values: unknown[] };\n\tsql: string;\n}[] {\n\tconst table = options.table ?? DEFAULT_TABLE;\n\tconst [schema, name] = table.includes('.')\n\t\t? (table.split('.') as [string, string])\n\t\t: [undefined, table];\n\tconst qualified = quote(table);\n\n\treturn [\n\t\t{\n\t\t\tdescribe: `cache table ${table}`,\n\t\t\texists: {\n\t\t\t\tsql: schema\n\t\t\t\t\t? 'SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2'\n\t\t\t\t\t: 'SELECT 1 FROM information_schema.tables WHERE table_name = $1',\n\t\t\t\tvalues: schema ? [schema, name] : [name],\n\t\t\t},\n\t\t\tsql: `CREATE TABLE ${qualified} (\n\t\t\t\tkey text PRIMARY KEY,\n\t\t\t\tvalue jsonb NOT NULL,\n\t\t\t\texpires_at timestamptz\n\t\t\t)`,\n\t\t},\n\t\t{\n\t\t\t// Only the expiring rows: a partial index stays small in a cache whose\n\t\t\t// entries mostly never expire, and the sweep only ever looks at those.\n\t\t\tdescribe: `cache expiry index on ${table}`,\n\t\t\tsql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}\n\t\t\t ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`,\n\t\t},\n\t];\n}\n\n/** A possibly schema-qualified name, quoted per segment. */\nfunction quote(table: string): string {\n\treturn table\n\t\t.split('.')\n\t\t.map((part) => `\"${part.replace(/\"/g, '\"\"')}\"`)\n\t\t.join('.');\n}\n\nfunction indexName(table: string): string {\n\treturn `\"${table.replace(/[^a-zA-Z0-9]/g, '_')}_expires_at_idx\"`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,gBAAgB;AAEtB,IAAa,gBAAb,MAA4C;CAIzB;CAHlB;CAEA,YACC,MACA,UAAgC,CAAC,GAChC;EAFgB,KAAA,OAAA;EAGjB,KAAK,QAAQ,QAAQ,SAAS;CAC/B;CAEA,MAAM,IAAO,KAAqC;EACjD,OAAOA,kBAAAA,WAAW,cAAc,OAAO,YAAY;GAClD,MAAM,EAAE,SAAS,MAAM,KAAK,MAC3B,qBAAqB,KAAK,WAAW,EAAE;qEAEvC,CAAC,GAAG,CACL;GAEA,OAAO,KAAK,EAAE,EAAE;EACjB,CAAC;CACF;CAEA,MAAM,IAAO,KAAa,OAAU,KAA6B;EAChE,OAAOA,kBAAAA,WAAW,cAAc,OAAO,YAAY;GAKlD,MAAM,KAAK,MACV,eAAe,KAAK,WAAW,EAAE;8BACP,QAAQ,KAAA,IAAY,SAAS,uCAAuC;;oEAG9F,QAAQ,KAAA,IACL,CAAC,KAAK,KAAK,UAAU,KAAK,CAAC,IAC3B;IAAC;IAAK,KAAK,UAAU,KAAK;IAAG,OAAO,GAA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EAElD,IAAI,CAAC,OAAO,OAAO,EAAE,kBAAkB,IAAI;EAE3C,OAAO,aAAa,OAAO,OAAO;EAElC,OAAO;GAAE,kBAAkB,OAAO,SAAS;GAAG;EAAM;CACrD,QAAQ;EAIP,OAAO,EAAE,kBAAkB,IAAI;CAChC;AACD;AAEA,MAAM,wBAAQ,IAAI,IAAkB;;;;;;;;;;;AAYpC,SAAgB,qBAAqB,UAAgC,CAAC,GAIlE;CACH,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,CAAC,QAAQ,QAAQ,MAAM,SAAS,GAAG,IACrC,MAAM,MAAM,GAAG,IAChB,CAAC,KAAA,GAAW,KAAK;CACpB,MAAM,YAAY,MAAM,KAAK;CAE7B,OAAO,CACN;EACC,UAAU,eAAe;EACzB,QAAQ;GACP,KAAK,SACF,wFACA;GACH,QAAQ,SAAS,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI;EACxC;EACA,KAAK,gBAAgB,UAAU;;;;;CAKhC,GACA;EAGC,UAAU,yBAAyB;EACnC,KAAK,8BAA8B,UAAU,KAAK,EAAE;cACzC,UAAU;CACtB,CACD;AACD;;AAGA,SAAS,MAAM,OAAuB;CACrC,OAAO,MACL,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,IAAI,KAAK,QAAQ,MAAM,MAAI,EAAE,EAAE,CAAC,CAC9C,KAAK,GAAG;AACX;AAEA,SAAS,UAAU,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;AAChD"}
|
package/dist/postgres.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.cts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"postgres.d.cts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;iBA2BiB;;;;;;;;EAQhB;;qBAKY,yBAAyB;mBAInB;mBAHD;EAEjB,YACkB,MAAM,MACvB,UAAS;EAKJ,IAAI,GAAG,cAAc,QAAQ;EAY7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;EAkB7C,OAAO,cAAc;EAQrB,IAAI,cAAc;;;;;;;EAuBlB,SAAS;UAQD;;;;;;;;UAgBN;;;;;;;;;;;;;;qBAiBI,qBAAqB;;;;;;;;;;;wBA6DlB,qBAAqB,UAAS;EAC7C;EACA;IAAW;IAAa;;EACxB"}
|
package/dist/postgres.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.mts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"postgres.d.mts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;iBA2BiB;;;;;;;;EAQhB;;qBAKY,yBAAyB;mBAInB;mBAHD;EAEjB,YACkB,MAAM,MACvB,UAAS;EAKJ,IAAI,GAAG,cAAc,QAAQ;EAY7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;EAkB7C,OAAO,cAAc;EAQrB,IAAI,cAAc;;;;;;;EAuBlB,SAAS;UAQD;;;;;;;;UAgBN;;;;;;;;;;;;;;qBAiBI,qBAAqB;;;;;;;;;;;wBA6DlB,qBAAqB,UAAS;EAC7C;EACA;IAAW;IAAa;;EACxB"}
|
package/dist/postgres.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { traceCache } from "./telemetry.mjs";
|
|
1
2
|
import pg from "pg";
|
|
2
3
|
//#region src/postgres.ts
|
|
3
4
|
/**
|
|
@@ -30,22 +31,28 @@ var PostgresCache = class {
|
|
|
30
31
|
this.table = options.table ?? DEFAULT_TABLE;
|
|
31
32
|
}
|
|
32
33
|
async get(key) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
return traceCache("postgresql", "get", async () => {
|
|
35
|
+
const { rows } = await this.query(`SELECT value FROM ${this.identifier()}
|
|
36
|
+
WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
|
|
37
|
+
return rows[0]?.value;
|
|
38
|
+
});
|
|
36
39
|
}
|
|
37
40
|
async set(key, value, ttl) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
41
|
+
return traceCache("postgresql", "set", async () => {
|
|
42
|
+
await this.query(`INSERT INTO ${this.identifier()} (key, value, expires_at)
|
|
43
|
+
VALUES ($1, $2::jsonb, ${ttl === void 0 ? "NULL" : "now() + ($3 || ' seconds')::interval"})
|
|
44
|
+
ON CONFLICT (key) DO UPDATE
|
|
45
|
+
SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`, ttl === void 0 ? [key, JSON.stringify(value)] : [
|
|
46
|
+
key,
|
|
47
|
+
JSON.stringify(value),
|
|
48
|
+
String(ttl)
|
|
49
|
+
]);
|
|
50
|
+
});
|
|
46
51
|
}
|
|
47
52
|
async delete(key) {
|
|
48
|
-
|
|
53
|
+
return traceCache("postgresql", "delete", async () => {
|
|
54
|
+
await this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);
|
|
55
|
+
});
|
|
49
56
|
}
|
|
50
57
|
async ttl(key) {
|
|
51
58
|
const { rows } = await this.query(`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds
|
package/dist/postgres.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["/**\n * A cache that lives in a database you already have.\n *\n * The backend with no infrastructure. A cache is a table; the database is the\n * one the application already declared, so an idle stage costs nothing extra\n * and there is one fewer thing to provision, secure and pay for. It is slower\n * than Redis and that is the trade: for session lookups, rate-limit counters and\n * memoised API responses at ordinary volumes, a primary-key hit on a small table\n * is not the thing that will be slow.\n *\n * **The table is provisioned, not created on first use.** That is the one place\n * this differs from pg-boss, and the reason is the role split: a handler\n * connects as a role that may read and write rows and may not create anything,\n * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where\n * the roles are doing their job. The DDL is exported instead — see\n * {@link cacheTableStatements} — and applied by whatever applies the rest.\n *\n * Reads filter on expiry and delete lazily, so an expired row is never returned\n * even if nothing has swept it; a sweep is an optimisation, not a correctness\n * requirement.\n */\n\nimport pg, { type Pool } from 'pg';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport interface PostgresCacheOptions {\n\t/**\n\t * The table to keep entries in, schema-qualified if it needs to be.\n\t *\n\t * Defaults to `cache`. It resolves against the connection's `search_path`,\n\t * which the role carries — so a tenant's cache lands in the tenant's schema\n\t * without anything here knowing the schema's name.\n\t */\n\ttable?: string;\n}\n\nconst DEFAULT_TABLE = 'cache';\n\nexport class PostgresCache implements Cache {\n\tprivate readonly table: string;\n\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\toptions: PostgresCacheOptions = {},\n\t) {\n\t\tthis.table = options.table ?? DEFAULT_TABLE;\n\t}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst { rows } = await this.query<{ value: T }>(\n\t\t\t`SELECT value FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\treturn rows[0]?.value;\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\t// `now() + interval` computed by the server, not by this process: a\n\t\t// client whose clock is minutes off would otherwise write entries that\n\t\t// expire early or late, and clock skew is not a thing to debug through a\n\t\t// cache.\n\t\tawait this.query(\n\t\t\t`INSERT INTO ${this.identifier()} (key, value, expires_at)\n\t\t\t VALUES ($1, $2::jsonb, ${ttl === undefined ? 'NULL' : \"now() + ($3 || ' seconds')::interval\"})\n\t\t\t ON CONFLICT (key) DO UPDATE\n\t\t\t SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`,\n\t\t\tttl === undefined\n\t\t\t\t? [key, JSON.stringify(value)]\n\t\t\t\t: [key, JSON.stringify(value), String(ttl)],\n\t\t);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst { rows } = await this.query<{ seconds: number | null }>(\n\t\t\t`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds\n\t\t\t FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\tconst row = rows[0];\n\t\tif (!row) return 0;\n\n\t\t// A row with no expiry has no time *left* to report. Zero is what the\n\t\t// interface says a missing key returns, and \"never expires\" is closer to\n\t\t// that than to any number this could invent.\n\t\treturn row.seconds ?? 0;\n\t}\n\n\t/**\n\t * Delete every expired entry.\n\t *\n\t * Optional: reads already ignore them. Worth running occasionally so the\n\t * table does not grow without bound in a workload that writes many keys once.\n\t */\n\tasync sweep(): Promise<number> {\n\t\tconst { rowCount } = await this.query(\n\t\t\t`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`,\n\t\t);\n\n\t\treturn rowCount ?? 0;\n\t}\n\n\tprivate async query<T>(\n\t\tsql: string,\n\t\tvalues: unknown[] = [],\n\t): Promise<{ rows: T[]; rowCount: number | null }> {\n\t\tconst result = await this.pool.query(sql, values);\n\n\t\treturn { rows: result.rows as T[], rowCount: result.rowCount };\n\t}\n\n\t/**\n\t * The table name as an identifier.\n\t *\n\t * Quoted per segment so a schema-qualified name stays two identifiers rather\n\t * than becoming one with a dot in it. The name comes from configuration\n\t * rather than from a request, so this is defence rather than sanitisation.\n\t */\n\tprivate identifier(): string {\n\t\treturn quote(this.table);\n\t}\n}\n\n/**\n * The `postgres://` driver.\n *\n * One pool per URL, cached for the life of the process: a cache that opened a\n * connection per call would be slower than the thing it exists to speed up, and\n * a Lambda reusing a warm container should reuse the pool with it.\n *\n * `pg` is imported at the top of this module rather than lazily, because the\n * *module* is the lazy boundary — an app caching in Redis never imports\n * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same\n * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.\n */\nexport const postgresCacheDriver: CacheDriver = {\n\tscheme: 'postgres:',\n\tcreate(url) {\n\t\t// The table travels in the URL, the way pg-boss's schema does.\n\t\t//\n\t\t// It has to, because a database-backed cache has no address of its own:\n\t\t// two caches in one database resolve the *same* connection string, so a\n\t\t// client built from the URL alone cannot tell them apart and both would\n\t\t// read and write one table — sharing a keyspace and evicting each other's\n\t\t// keys. The parameter is what makes the address identify the cache.\n\t\tconst { connectionString, table } = split(url);\n\n\t\tconst existing = pools.get(connectionString);\n\t\tconst pool = existing ?? new pg.Pool({ connectionString });\n\t\tif (!existing) pools.set(connectionString, pool);\n\n\t\t// One pool per database, shared by every cache in it — the table is the\n\t\t// client's, not the pool's.\n\t\treturn new PostgresCache(pool, table ? { table } : {});\n\t},\n};\n\n/**\n * A cache URL as its two facts: where to connect, and what to read.\n *\n * `table` is removed from the string handed to `pg` rather than left on it,\n * because a Postgres connection string carries libpq parameters and an unknown\n * one is not guaranteed to be ignored — and because the pool should be shared\n * by every cache in the database, which only works if the key does not vary\n * per cache.\n */\nfunction split(url: string): { connectionString: string; table?: string } {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tconst table = parsed.searchParams.get('table') ?? undefined;\n\n\t\tif (!table) return { connectionString: url };\n\n\t\tparsed.searchParams.delete('table');\n\n\t\treturn { connectionString: parsed.toString(), table };\n\t} catch {\n\t\t// Not a URL `URL` can parse. The driver's job is not to validate one, so\n\t\t// this hands it to `pg` unchanged and lets that failure be the one\n\t\t// reported.\n\t\treturn { connectionString: url };\n\t}\n}\n\nconst pools = new Map<string, Pool>();\n\n/**\n * The DDL a Postgres-backed cache needs, for whoever applies DDL.\n *\n * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same\n * statements run in-process from `gkm dev` and from a provisioner inside a VPC,\n * and one implementation is what stops \"works locally, fails deployed\".\n *\n * Run as the schema's **owner**. The role a handler connects as cannot create a\n * table, which is the point of the split and the reason this is not done lazily.\n */\nexport function cacheTableStatements(options: PostgresCacheOptions = {}): {\n\tdescribe: string;\n\texists?: { sql: string; values: unknown[] };\n\tsql: string;\n}[] {\n\tconst table = options.table ?? DEFAULT_TABLE;\n\tconst [schema, name] = table.includes('.')\n\t\t? (table.split('.') as [string, string])\n\t\t: [undefined, table];\n\tconst qualified = quote(table);\n\n\treturn [\n\t\t{\n\t\t\tdescribe: `cache table ${table}`,\n\t\t\texists: {\n\t\t\t\tsql: schema\n\t\t\t\t\t? 'SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2'\n\t\t\t\t\t: 'SELECT 1 FROM information_schema.tables WHERE table_name = $1',\n\t\t\t\tvalues: schema ? [schema, name] : [name],\n\t\t\t},\n\t\t\tsql: `CREATE TABLE ${qualified} (\n\t\t\t\tkey text PRIMARY KEY,\n\t\t\t\tvalue jsonb NOT NULL,\n\t\t\t\texpires_at timestamptz\n\t\t\t)`,\n\t\t},\n\t\t{\n\t\t\t// Only the expiring rows: a partial index stays small in a cache whose\n\t\t\t// entries mostly never expire, and the sweep only ever looks at those.\n\t\t\tdescribe: `cache expiry index on ${table}`,\n\t\t\tsql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}\n\t\t\t ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`,\n\t\t},\n\t];\n}\n\n/** A possibly schema-qualified name, quoted per segment. */\nfunction quote(table: string): string {\n\treturn table\n\t\t.split('.')\n\t\t.map((part) => `\"${part.replace(/\"/g, '\"\"')}\"`)\n\t\t.join('.');\n}\n\nfunction indexName(table: string): string {\n\treturn `\"${table.replace(/[^a-zA-Z0-9]/g, '_')}_expires_at_idx\"`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,gBAAgB;AAEtB,IAAa,gBAAb,MAA4C;CAIzB;CAHlB;CAEA,YACC,MACA,UAAgC,CAAC,GAChC;EAFgB,KAAA,OAAA;EAGjB,KAA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,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;AAChD"}
|
|
1
|
+
{"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["/**\n * A cache that lives in a database you already have.\n *\n * The backend with no infrastructure. A cache is a table; the database is the\n * one the application already declared, so an idle stage costs nothing extra\n * and there is one fewer thing to provision, secure and pay for. It is slower\n * than Redis and that is the trade: for session lookups, rate-limit counters and\n * memoised API responses at ordinary volumes, a primary-key hit on a small table\n * is not the thing that will be slow.\n *\n * **The table is provisioned, not created on first use.** That is the one place\n * this differs from pg-boss, and the reason is the role split: a handler\n * connects as a role that may read and write rows and may not create anything,\n * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where\n * the roles are doing their job. The DDL is exported instead — see\n * {@link cacheTableStatements} — and applied by whatever applies the rest.\n *\n * Reads filter on expiry and delete lazily, so an expired row is never returned\n * even if nothing has swept it; a sweep is an optimisation, not a correctness\n * requirement.\n */\n\nimport pg, { type Pool } from 'pg';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\nimport { traceCache } from './telemetry';\n\nexport interface PostgresCacheOptions {\n\t/**\n\t * The table to keep entries in, schema-qualified if it needs to be.\n\t *\n\t * Defaults to `cache`. It resolves against the connection's `search_path`,\n\t * which the role carries — so a tenant's cache lands in the tenant's schema\n\t * without anything here knowing the schema's name.\n\t */\n\ttable?: string;\n}\n\nconst DEFAULT_TABLE = 'cache';\n\nexport class PostgresCache implements Cache {\n\tprivate readonly table: string;\n\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\toptions: PostgresCacheOptions = {},\n\t) {\n\t\tthis.table = options.table ?? DEFAULT_TABLE;\n\t}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\treturn traceCache('postgresql', 'get', async () => {\n\t\t\tconst { rows } = await this.query<{ value: T }>(\n\t\t\t\t`SELECT value FROM ${this.identifier()}\n\t\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t\t[key],\n\t\t\t);\n\n\t\t\treturn rows[0]?.value;\n\t\t});\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\treturn traceCache('postgresql', 'set', async () => {\n\t\t\t// `now() + interval` computed by the server, not by this process: a\n\t\t\t// client whose clock is minutes off would otherwise write entries that\n\t\t\t// expire early or late, and clock skew is not a thing to debug through a\n\t\t\t// cache.\n\t\t\tawait this.query(\n\t\t\t\t`INSERT INTO ${this.identifier()} (key, value, expires_at)\n\t\t\t\t VALUES ($1, $2::jsonb, ${ttl === undefined ? 'NULL' : \"now() + ($3 || ' seconds')::interval\"})\n\t\t\t\t ON CONFLICT (key) DO UPDATE\n\t\t\t\t SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`,\n\t\t\t\tttl === undefined\n\t\t\t\t\t? [key, JSON.stringify(value)]\n\t\t\t\t\t: [key, JSON.stringify(value), String(ttl)],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\treturn traceCache('postgresql', 'delete', async () => {\n\t\t\tawait this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [\n\t\t\t\tkey,\n\t\t\t]);\n\t\t});\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst { rows } = await this.query<{ seconds: number | null }>(\n\t\t\t`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds\n\t\t\t FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\tconst row = rows[0];\n\t\tif (!row) return 0;\n\n\t\t// A row with no expiry has no time *left* to report. Zero is what the\n\t\t// interface says a missing key returns, and \"never expires\" is closer to\n\t\t// that than to any number this could invent.\n\t\treturn row.seconds ?? 0;\n\t}\n\n\t/**\n\t * Delete every expired entry.\n\t *\n\t * Optional: reads already ignore them. Worth running occasionally so the\n\t * table does not grow without bound in a workload that writes many keys once.\n\t */\n\tasync sweep(): Promise<number> {\n\t\tconst { rowCount } = await this.query(\n\t\t\t`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`,\n\t\t);\n\n\t\treturn rowCount ?? 0;\n\t}\n\n\tprivate async query<T>(\n\t\tsql: string,\n\t\tvalues: unknown[] = [],\n\t): Promise<{ rows: T[]; rowCount: number | null }> {\n\t\tconst result = await this.pool.query(sql, values);\n\n\t\treturn { rows: result.rows as T[], rowCount: result.rowCount };\n\t}\n\n\t/**\n\t * The table name as an identifier.\n\t *\n\t * Quoted per segment so a schema-qualified name stays two identifiers rather\n\t * than becoming one with a dot in it. The name comes from configuration\n\t * rather than from a request, so this is defence rather than sanitisation.\n\t */\n\tprivate identifier(): string {\n\t\treturn quote(this.table);\n\t}\n}\n\n/**\n * The `postgres://` driver.\n *\n * One pool per URL, cached for the life of the process: a cache that opened a\n * connection per call would be slower than the thing it exists to speed up, and\n * a Lambda reusing a warm container should reuse the pool with it.\n *\n * `pg` is imported at the top of this module rather than lazily, because the\n * *module* is the lazy boundary — an app caching in Redis never imports\n * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same\n * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.\n */\nexport const postgresCacheDriver: CacheDriver = {\n\tscheme: 'postgres:',\n\tcreate(url) {\n\t\t// The table travels in the URL, the way pg-boss's schema does.\n\t\t//\n\t\t// It has to, because a database-backed cache has no address of its own:\n\t\t// two caches in one database resolve the *same* connection string, so a\n\t\t// client built from the URL alone cannot tell them apart and both would\n\t\t// read and write one table — sharing a keyspace and evicting each other's\n\t\t// keys. The parameter is what makes the address identify the cache.\n\t\tconst { connectionString, table } = split(url);\n\n\t\tconst existing = pools.get(connectionString);\n\t\tconst pool = existing ?? new pg.Pool({ connectionString });\n\t\tif (!existing) pools.set(connectionString, pool);\n\n\t\t// One pool per database, shared by every cache in it — the table is the\n\t\t// client's, not the pool's.\n\t\treturn new PostgresCache(pool, table ? { table } : {});\n\t},\n};\n\n/**\n * A cache URL as its two facts: where to connect, and what to read.\n *\n * `table` is removed from the string handed to `pg` rather than left on it,\n * because a Postgres connection string carries libpq parameters and an unknown\n * one is not guaranteed to be ignored — and because the pool should be shared\n * by every cache in the database, which only works if the key does not vary\n * per cache.\n */\nfunction split(url: string): { connectionString: string; table?: string } {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tconst table = parsed.searchParams.get('table') ?? undefined;\n\n\t\tif (!table) return { connectionString: url };\n\n\t\tparsed.searchParams.delete('table');\n\n\t\treturn { connectionString: parsed.toString(), table };\n\t} catch {\n\t\t// Not a URL `URL` can parse. The driver's job is not to validate one, so\n\t\t// this hands it to `pg` unchanged and lets that failure be the one\n\t\t// reported.\n\t\treturn { connectionString: url };\n\t}\n}\n\nconst pools = new Map<string, Pool>();\n\n/**\n * The DDL a Postgres-backed cache needs, for whoever applies DDL.\n *\n * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same\n * statements run in-process from `gkm dev` and from a provisioner inside a VPC,\n * and one implementation is what stops \"works locally, fails deployed\".\n *\n * Run as the schema's **owner**. The role a handler connects as cannot create a\n * table, which is the point of the split and the reason this is not done lazily.\n */\nexport function cacheTableStatements(options: PostgresCacheOptions = {}): {\n\tdescribe: string;\n\texists?: { sql: string; values: unknown[] };\n\tsql: string;\n}[] {\n\tconst table = options.table ?? DEFAULT_TABLE;\n\tconst [schema, name] = table.includes('.')\n\t\t? (table.split('.') as [string, string])\n\t\t: [undefined, table];\n\tconst qualified = quote(table);\n\n\treturn [\n\t\t{\n\t\t\tdescribe: `cache table ${table}`,\n\t\t\texists: {\n\t\t\t\tsql: schema\n\t\t\t\t\t? 'SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2'\n\t\t\t\t\t: 'SELECT 1 FROM information_schema.tables WHERE table_name = $1',\n\t\t\t\tvalues: schema ? [schema, name] : [name],\n\t\t\t},\n\t\t\tsql: `CREATE TABLE ${qualified} (\n\t\t\t\tkey text PRIMARY KEY,\n\t\t\t\tvalue jsonb NOT NULL,\n\t\t\t\texpires_at timestamptz\n\t\t\t)`,\n\t\t},\n\t\t{\n\t\t\t// Only the expiring rows: a partial index stays small in a cache whose\n\t\t\t// entries mostly never expire, and the sweep only ever looks at those.\n\t\t\tdescribe: `cache expiry index on ${table}`,\n\t\t\tsql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}\n\t\t\t ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`,\n\t\t},\n\t];\n}\n\n/** A possibly schema-qualified name, quoted per segment. */\nfunction quote(table: string): string {\n\treturn table\n\t\t.split('.')\n\t\t.map((part) => `\"${part.replace(/\"/g, '\"\"')}\"`)\n\t\t.join('.');\n}\n\nfunction indexName(table: string): string {\n\treturn `\"${table.replace(/[^a-zA-Z0-9]/g, '_')}_expires_at_idx\"`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,gBAAgB;AAEtB,IAAa,gBAAb,MAA4C;CAIzB;CAHlB;CAEA,YACC,MACA,UAAgC,CAAC,GAChC;EAFgB,KAAA,OAAA;EAGjB,KAAK,QAAQ,QAAQ,SAAS;CAC/B;CAEA,MAAM,IAAO,KAAqC;EACjD,OAAO,WAAW,cAAc,OAAO,YAAY;GAClD,MAAM,EAAE,SAAS,MAAM,KAAK,MAC3B,qBAAqB,KAAK,WAAW,EAAE;qEAEvC,CAAC,GAAG,CACL;GAEA,OAAO,KAAK,EAAE,EAAE;EACjB,CAAC;CACF;CAEA,MAAM,IAAO,KAAa,OAAU,KAA6B;EAChE,OAAO,WAAW,cAAc,OAAO,YAAY;GAKlD,MAAM,KAAK,MACV,eAAe,KAAK,WAAW,EAAE;8BACP,QAAQ,KAAA,IAAY,SAAS,uCAAuC;;oEAG9F,QAAQ,KAAA,IACL,CAAC,KAAK,KAAK,UAAU,KAAK,CAAC,IAC3B;IAAC;IAAK,KAAK,UAAU,KAAK;IAAG,OAAO,GAAG;GAAC,CAC5C;EACD,CAAC;CACF;CAEA,MAAM,OAAO,KAA4B;E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O,OAAO;EAElC,OAAO;GAAE,kBAAkB,OAAO,SAAS;GAAG;EAAM;CACrD,QAAQ;EAIP,OAAO,EAAE,kBAAkB,IAAI;CAChC;AACD;AAEA,MAAM,wBAAQ,IAAI,IAAkB;;;;;;;;;;;AAYpC,SAAgB,qBAAqB,UAAgC,CAAC,GAIlE;CACH,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,CAAC,QAAQ,QAAQ,MAAM,SAAS,GAAG,IACrC,MAAM,MAAM,GAAG,IAChB,CAAC,KAAA,GAAW,KAAK;CACpB,MAAM,YAAY,MAAM,KAAK;CAE7B,OAAO,CACN;EACC,UAAU,eAAe;EACzB,QAAQ;GACP,KAAK,SACF,wFACA;GACH,QAAQ,SAAS,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI;EACxC;EACA,KAAK,gBAAgB,UAAU;;;;;CAKhC,GACA;EAGC,UAAU,yBAAyB;EACnC,KAAK,8BAA8B,UAAU,KAAK,EAAE;cACzC,UAAU;CACtB,CACD;AACD;;AAGA,SAAS,MAAM,OAAuB;CACrC,OAAO,MACL,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,IAAI,KAAK,QAAQ,MAAM,MAAI,EAAE,EAAE,CAAC,CAC9C,KAAK,GAAG;AACX;AAEA,SAAS,UAAU,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;AAChD"}
|
package/dist/redis.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_telemetry = require("./telemetry.cjs");
|
|
2
3
|
let ioredis = require("ioredis");
|
|
3
4
|
//#region src/redis.ts
|
|
4
5
|
/**
|
|
@@ -21,24 +22,30 @@ var RedisCache = class {
|
|
|
21
22
|
this.client = client;
|
|
22
23
|
}
|
|
23
24
|
async get(key) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
return require_telemetry.traceCache("redis", "get", async () => {
|
|
26
|
+
const value = await this.client.get(key);
|
|
27
|
+
if (value === null) return void 0;
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(value);
|
|
30
|
+
} catch {
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
31
34
|
}
|
|
32
35
|
async set(key, value, ttl) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
return require_telemetry.traceCache("redis", "set", async () => {
|
|
37
|
+
const encoded = JSON.stringify(value);
|
|
38
|
+
if (ttl === void 0) {
|
|
39
|
+
await this.client.set(key, encoded);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await this.client.set(key, encoded, "EX", ttl);
|
|
43
|
+
});
|
|
39
44
|
}
|
|
40
45
|
async delete(key) {
|
|
41
|
-
|
|
46
|
+
return require_telemetry.traceCache("redis", "delete", async () => {
|
|
47
|
+
await this.client.del(key);
|
|
48
|
+
});
|
|
42
49
|
}
|
|
43
50
|
async ttl(key) {
|
|
44
51
|
const seconds = await this.client.ttl(key);
|
package/dist/redis.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.cjs","names":["Redis"],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst value = await this.client.get(key);\n\t\tif (value === null) return undefined;\n\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t// there on purpose.\n\t\t\treturn value as unknown as T;\n\t\t}\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\tconst encoded = JSON.stringify(value);\n\n\t\tif (ttl === undefined) {\n\t\t\tawait this.client.set(key, encoded);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.client.del(key);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\t//\n\t\t// The offline queue stays on: the socket connects after the constructor\n\t\t// returns, so without it the first command of every fresh client — every\n\t\t// cold start — is rejected before the connection has had a chance. The\n\t\t// retry bound above is what keeps a queued command from waiting forever.\n\t\tmaxRetriesPerRequest: 2,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"redis.cjs","names":["traceCache","Redis"],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\nimport { traceCache } from './telemetry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\treturn traceCache('redis', 'get', async () => {\n\t\t\tconst value = await this.client.get(key);\n\t\t\tif (value === null) return undefined;\n\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(value) as T;\n\t\t\t} catch {\n\t\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t\t// there on purpose.\n\t\t\t\treturn value as unknown as T;\n\t\t\t}\n\t\t});\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\treturn traceCache('redis', 'set', async () => {\n\t\t\tconst encoded = JSON.stringify(value);\n\n\t\t\tif (ttl === undefined) {\n\t\t\t\tawait this.client.set(key, encoded);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t\t});\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\treturn traceCache('redis', 'delete', async () => {\n\t\t\tawait this.client.del(key);\n\t\t});\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\t//\n\t\t// The offline queue stays on: the socket connects after the constructor\n\t\t// returns, so without it the first command of every fresh client — every\n\t\t// cold start — is rejected before the connection has had a chance. The\n\t\t// retry bound above is what keeps a queued command from waiting forever.\n\t\tmaxRetriesPerRequest: 2,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,IAAa,aAAb,MAAyC;CACX;CAA7B,YAAY,QAAgC;EAAf,KAAA,SAAA;CAAgB;CAE7C,MAAM,IAAO,KAAqC;EACjD,OAAOA,kBAAAA,WAAW,SAAS,OAAO,YAAY;GAC7C,MAAM,QAAQ,MAAM,KAAK,OAAO,IAAI,GAAG;GACvC,IAAI,UAAU,MAAM,OAAO,KAAA;GAE3B,IAAI;IACH,OAAO,KAAK,MAAM,KAAK;GACxB,QAAQ;IAIP,OAAO;GACR;EACD,CAAC;CACF;CAEA,MAAM,IAAO,KAAa,OAAU,KAA6B;EAChE,OAAOA,kBAAAA,WAAW,SAAS,OAAO,YAAY;GAC7C,MAAM,UAAU,KAAK,UAAU,KAAK;GAEpC,IAAI,QAAQ,KAAA,GAAW;IACtB,MAAM,KAAK,OAAO,IAAI,KAAK,OAAO;IAClC;GACD;GAEA,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,MAAM,GAAG;EAC9C,CAAC;CACF;CAEA,MAAM,OAAO,KAA4B;EACxC,OAAOA,kBAAAA,WAAW,SAAS,UAAU,YAAY;GAChD,MAAM,KAAK,OAAO,IAAI,GAAG;EAC1B,CAAC;CACF;CAEA,MAAM,IAAI,KAA8B;EACvC,MAAM,UAAU,MAAM,KAAK,OAAO,IAAI,GAAG;EAMzC,OAAO,UAAU,IAAI,IAAI;CAC1B;AACD;;;;;;;;;;;;AAaA,MAAa,mBAAgC;CAC5C,QAAQ;CACR,SAAS,QAAQ,IAAI,WAAW,UAAU,GAAG,CAAC;AAC/C;;AAGA,MAAa,oBAAiC;CAC7C,QAAQ;CACR,SAAS,QAAQ,IAAI,WAAW,UAAU,GAAG,CAAC;AAC/C;AAEA,MAAM,0BAAU,IAAI,IAAmB;AAEvC,SAAS,UAAU,KAAoB;CACtC,MAAM,WAAW,QAAQ,IAAI,GAAG;CAChC,IAAI,UAAU,OAAO;CAErB,MAAM,SAAS,IAAIC,QAAAA,MAAM,KAAK,EAS7B,sBAAsB,EACvB,CAAC;CAED,QAAQ,IAAI,KAAK,MAAM;CAEvB,OAAO;AACR"}
|
package/dist/redis.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.d.cts","names":[],"sources":["../src/redis.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"redis.d.cts","names":[],"sources":["../src/redis.ts"],"mappings":";;;qBAoBa,sBAAsB;mBACL;EAA7B,YAA6B,QAAQ;EAE/B,IAAI,GAAG,cAAc,QAAQ;EAgB7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;EAa7C,OAAO,cAAc;EAMrB,IAAI,cAAc;;;;;;;;;;;;;qBAsBZ,kBAAkB;;qBAMlB,mBAAmB"}
|
package/dist/redis.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.d.mts","names":[],"sources":["../src/redis.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"redis.d.mts","names":[],"sources":["../src/redis.ts"],"mappings":";;;qBAoBa,sBAAsB;mBACL;EAA7B,YAA6B,QAAQ;EAE/B,IAAI,GAAG,cAAc,QAAQ;EAgB7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;EAa7C,OAAO,cAAc;EAMrB,IAAI,cAAc;;;;;;;;;;;;;qBAsBZ,kBAAkB;;qBAMlB,mBAAmB"}
|
package/dist/redis.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { traceCache } from "./telemetry.mjs";
|
|
1
2
|
import { Redis } from "ioredis";
|
|
2
3
|
//#region src/redis.ts
|
|
3
4
|
/**
|
|
@@ -20,24 +21,30 @@ var RedisCache = class {
|
|
|
20
21
|
this.client = client;
|
|
21
22
|
}
|
|
22
23
|
async get(key) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
24
|
+
return traceCache("redis", "get", async () => {
|
|
25
|
+
const value = await this.client.get(key);
|
|
26
|
+
if (value === null) return void 0;
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(value);
|
|
29
|
+
} catch {
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
});
|
|
30
33
|
}
|
|
31
34
|
async set(key, value, ttl) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
return traceCache("redis", "set", async () => {
|
|
36
|
+
const encoded = JSON.stringify(value);
|
|
37
|
+
if (ttl === void 0) {
|
|
38
|
+
await this.client.set(key, encoded);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
await this.client.set(key, encoded, "EX", ttl);
|
|
42
|
+
});
|
|
38
43
|
}
|
|
39
44
|
async delete(key) {
|
|
40
|
-
|
|
45
|
+
return traceCache("redis", "delete", async () => {
|
|
46
|
+
await this.client.del(key);
|
|
47
|
+
});
|
|
41
48
|
}
|
|
42
49
|
async ttl(key) {
|
|
43
50
|
const seconds = await this.client.ttl(key);
|
package/dist/redis.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.mjs","names":[],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst value = await this.client.get(key);\n\t\tif (value === null) return undefined;\n\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t// there on purpose.\n\t\t\treturn value as unknown as T;\n\t\t}\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\tconst encoded = JSON.stringify(value);\n\n\t\tif (ttl === undefined) {\n\t\t\tawait this.client.set(key, encoded);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.client.del(key);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\t//\n\t\t// The offline queue stays on: the socket connects after the constructor\n\t\t// returns, so without it the first command of every fresh client — every\n\t\t// cold start — is rejected before the connection has had a chance. The\n\t\t// retry bound above is what keeps a queued command from waiting forever.\n\t\tmaxRetriesPerRequest: 2,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"redis.mjs","names":[],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\nimport { traceCache } from './telemetry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\treturn traceCache('redis', 'get', async () => {\n\t\t\tconst value = await this.client.get(key);\n\t\t\tif (value === null) return undefined;\n\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(value) as T;\n\t\t\t} catch {\n\t\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t\t// there on purpose.\n\t\t\t\treturn value as unknown as T;\n\t\t\t}\n\t\t});\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\treturn traceCache('redis', 'set', async () => {\n\t\t\tconst encoded = JSON.stringify(value);\n\n\t\t\tif (ttl === undefined) {\n\t\t\t\tawait this.client.set(key, encoded);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t\t});\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\treturn traceCache('redis', 'delete', async () => {\n\t\t\tawait this.client.del(key);\n\t\t});\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\t//\n\t\t// The offline queue stays on: the socket connects after the constructor\n\t\t// returns, so without it the first command of every fresh client — every\n\t\t// cold start — is rejected before the connection has had a chance. The\n\t\t// retry bound above is what keeps a queued command from waiting forever.\n\t\tmaxRetriesPerRequest: 2,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,IAAa,aAAb,MAAyC;CACX;CAA7B,YAAY,QAAgC;EAAf,KAAA,SAAA;CAAgB;CAE7C,MAAM,IAAO,KAAqC;EACjD,OAAO,WAAW,SAAS,OAAO,YAAY;GAC7C,MAAM,QAAQ,MAAM,KAAK,OAAO,IAAI,GAAG;GACvC,IAAI,UAAU,MAAM,OAAO,KAAA;GAE3B,IAAI;IACH,OAAO,KAAK,MAAM,KAAK;GACxB,QAAQ;IAIP,OAAO;GACR;EACD,CAAC;CACF;CAEA,MAAM,IAAO,KAAa,OAAU,KAA6B;EAChE,OAAO,WAAW,SAAS,OAAO,YAAY;GAC7C,MAAM,UAAU,KAAK,UAAU,KAAK;GAEpC,IAAI,QAAQ,KAAA,GAAW;IACtB,MAAM,KAAK,OAAO,IAAI,KAAK,OAAO;IAClC;GACD;GAEA,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,MAAM,GAAG;EAC9C,CAAC;CACF;CAEA,MAAM,OAAO,KAA4B;EACxC,OAAO,WAAW,SAAS,UAAU,YAAY;GAChD,MAAM,KAAK,OAAO,IAAI,GAAG;EAC1B,CAAC;CACF;CAEA,MAAM,IAAI,KAA8B;EACvC,MAAM,UAAU,MAAM,KAAK,OAAO,IAAI,GAAG;EAMzC,OAAO,UAAU,IAAI,IAAI;CAC1B;AACD;;;;;;;;;;;;AAaA,MAAa,mBAAgC;CAC5C,QAAQ;CACR,SAAS,QAAQ,IAAI,WAAW,UAAU,GAAG,CAAC;AAC/C;;AAGA,MAAa,oBAAiC;CAC7C,QAAQ;CACR,SAAS,QAAQ,IAAI,WAAW,UAAU,GAAG,CAAC;AAC/C;AAEA,MAAM,0BAAU,IAAI,IAAmB;AAEvC,SAAS,UAAU,KAAoB;CACtC,MAAM,WAAW,QAAQ,IAAI,GAAG;CAChC,IAAI,UAAU,OAAO;CAErB,MAAM,SAAS,IAAI,MAAM,KAAK,EAS7B,sBAAsB,EACvB,CAAC;CAED,QAAQ,IAAI,KAAK,MAAM;CAEvB,OAAO;AACR"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _opentelemetry_api = require("@opentelemetry/api");
|
|
3
|
+
//#region src/telemetry.ts
|
|
4
|
+
/**
|
|
5
|
+
* A span per cache call, through the global OpenTelemetry tracer — a no-op
|
|
6
|
+
* without a registered provider.
|
|
7
|
+
*
|
|
8
|
+
* `cache.get`, `cache.set` and `cache.delete`, each with the backend as
|
|
9
|
+
* `db.system` and, on a read, whether it hit. Never the key or the value: a key
|
|
10
|
+
* often names a user, and a value is whatever was cached.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
/** Run `fn` inside a `cache.<operation>` span for a backend. */
|
|
15
|
+
async function traceCache(system, operation, fn) {
|
|
16
|
+
const span = _opentelemetry_api.trace.getTracer("@geekmidas/cache").startSpan(`cache.${operation}`, {
|
|
17
|
+
kind: _opentelemetry_api.SpanKind.CLIENT,
|
|
18
|
+
attributes: {
|
|
19
|
+
"db.system": system,
|
|
20
|
+
"cache.operation": operation
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
try {
|
|
24
|
+
const result = await fn();
|
|
25
|
+
if (operation === "get") span.setAttribute("cache.hit", result !== void 0);
|
|
26
|
+
return result;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof Error) span.recordException(error);
|
|
29
|
+
span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
|
|
30
|
+
throw error;
|
|
31
|
+
} finally {
|
|
32
|
+
span.end();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
exports.traceCache = traceCache;
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=telemetry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.cjs","names":["trace","SpanKind","SpanStatusCode"],"sources":["../src/telemetry.ts"],"sourcesContent":["/**\n * A span per cache call, through the global OpenTelemetry tracer — a no-op\n * without a registered provider.\n *\n * `cache.get`, `cache.set` and `cache.delete`, each with the backend as\n * `db.system` and, on a read, whether it hit. Never the key or the value: a key\n * often names a user, and a value is whatever was cached.\n *\n * @module\n */\nimport { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';\n\nexport type CacheOperation = 'get' | 'set' | 'delete';\n\n/** Run `fn` inside a `cache.<operation>` span for a backend. */\nexport async function traceCache<T>(\n\tsystem: string,\n\toperation: CacheOperation,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst span = trace\n\t\t.getTracer('@geekmidas/cache')\n\t\t.startSpan(`cache.${operation}`, {\n\t\t\tkind: SpanKind.CLIENT,\n\t\t\tattributes: { 'db.system': system, 'cache.operation': operation },\n\t\t});\n\ttry {\n\t\tconst result = await fn();\n\t\tif (operation === 'get')\n\t\t\tspan.setAttribute('cache.hit', result !== undefined);\n\t\treturn result;\n\t} catch (error) {\n\t\tif (error instanceof Error) span.recordException(error);\n\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,eAAsB,WACrB,QACA,WACA,IACa;CACb,MAAM,OAAOA,mBAAAA,MACX,UAAU,kBAAkB,CAAC,CAC7B,UAAU,SAAS,aAAa;EAChC,MAAMC,mBAAAA,SAAS;EACf,YAAY;GAAE,aAAa;GAAQ,mBAAmB;EAAU;CACjE,CAAC;CACF,IAAI;EACH,MAAM,SAAS,MAAM,GAAG;EACxB,IAAI,cAAc,OACjB,KAAK,aAAa,aAAa,WAAW,KAAA,CAAS;EACpD,OAAO;CACR,SAAS,OAAO;EACf,IAAI,iBAAiB,OAAO,KAAK,gBAAgB,KAAK;EACtD,KAAK,UAAU,EAAE,MAAMC,mBAAAA,eAAe,MAAM,CAAC;EAC7C,MAAM;CACP,UAAU;EACT,KAAK,IAAI;CACV;AACD"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/telemetry.d.ts
|
|
2
|
+
export type CacheOperation = 'get' | 'set' | 'delete';
|
|
3
|
+
/** Run `fn` inside a `cache.<operation>` span for a backend. */
|
|
4
|
+
export declare function traceCache<T>(system: string, operation: CacheOperation, fn: () => Promise<T>): Promise<T>;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=telemetry.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.d.cts","names":[],"sources":["../src/telemetry.ts"],"mappings":";YAYY;;wBAGU,WAAW,GAChC,gBACA,WAAW,gBACX,UAAU,QAAQ,KAChB,QAAQ"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/telemetry.d.ts
|
|
2
|
+
export type CacheOperation = 'get' | 'set' | 'delete';
|
|
3
|
+
/** Run `fn` inside a `cache.<operation>` span for a backend. */
|
|
4
|
+
export declare function traceCache<T>(system: string, operation: CacheOperation, fn: () => Promise<T>): Promise<T>;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=telemetry.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.d.mts","names":[],"sources":["../src/telemetry.ts"],"mappings":";YAYY;;wBAGU,WAAW,GAChC,gBACA,WAAW,gBACX,UAAU,QAAQ,KAChB,QAAQ"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
2
|
+
//#region src/telemetry.ts
|
|
3
|
+
/**
|
|
4
|
+
* A span per cache call, through the global OpenTelemetry tracer — a no-op
|
|
5
|
+
* without a registered provider.
|
|
6
|
+
*
|
|
7
|
+
* `cache.get`, `cache.set` and `cache.delete`, each with the backend as
|
|
8
|
+
* `db.system` and, on a read, whether it hit. Never the key or the value: a key
|
|
9
|
+
* often names a user, and a value is whatever was cached.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
/** Run `fn` inside a `cache.<operation>` span for a backend. */
|
|
14
|
+
async function traceCache(system, operation, fn) {
|
|
15
|
+
const span = trace.getTracer("@geekmidas/cache").startSpan(`cache.${operation}`, {
|
|
16
|
+
kind: SpanKind.CLIENT,
|
|
17
|
+
attributes: {
|
|
18
|
+
"db.system": system,
|
|
19
|
+
"cache.operation": operation
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
try {
|
|
23
|
+
const result = await fn();
|
|
24
|
+
if (operation === "get") span.setAttribute("cache.hit", result !== void 0);
|
|
25
|
+
return result;
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error instanceof Error) span.recordException(error);
|
|
28
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
29
|
+
throw error;
|
|
30
|
+
} finally {
|
|
31
|
+
span.end();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
export { traceCache };
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=telemetry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.mjs","names":[],"sources":["../src/telemetry.ts"],"sourcesContent":["/**\n * A span per cache call, through the global OpenTelemetry tracer — a no-op\n * without a registered provider.\n *\n * `cache.get`, `cache.set` and `cache.delete`, each with the backend as\n * `db.system` and, on a read, whether it hit. Never the key or the value: a key\n * often names a user, and a value is whatever was cached.\n *\n * @module\n */\nimport { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';\n\nexport type CacheOperation = 'get' | 'set' | 'delete';\n\n/** Run `fn` inside a `cache.<operation>` span for a backend. */\nexport async function traceCache<T>(\n\tsystem: string,\n\toperation: CacheOperation,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst span = trace\n\t\t.getTracer('@geekmidas/cache')\n\t\t.startSpan(`cache.${operation}`, {\n\t\t\tkind: SpanKind.CLIENT,\n\t\t\tattributes: { 'db.system': system, 'cache.operation': operation },\n\t\t});\n\ttry {\n\t\tconst result = await fn();\n\t\tif (operation === 'get')\n\t\t\tspan.setAttribute('cache.hit', result !== undefined);\n\t\treturn result;\n\t} catch (error) {\n\t\tif (error instanceof Error) span.recordException(error);\n\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,eAAsB,WACrB,QACA,WACA,IACa;CACb,MAAM,OAAO,MACX,UAAU,kBAAkB,CAAC,CAC7B,UAAU,SAAS,aAAa;EAChC,MAAM,SAAS;EACf,YAAY;GAAE,aAAa;GAAQ,mBAAmB;EAAU;CACjE,CAAC;CACF,IAAI;EACH,MAAM,SAAS,MAAM,GAAG;EACxB,IAAI,cAAc,OACjB,KAAK,aAAa,aAAa,WAAW,KAAA,CAAS;EACpD,OAAO;CACR,SAAS,OAAO;EACf,IAAI,iBAAiB,OAAO,KAAK,gBAAgB,KAAK;EACtD,KAAK,UAAU,EAAE,MAAM,eAAe,MAAM,CAAC;EAC7C,MAAM;CACP,UAAU;EACT,KAAK,IAAI;CACV;AACD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geekmidas/cache",
|
|
3
|
-
"version": "10.0.0-alpha.
|
|
3
|
+
"version": "10.0.0-alpha.81",
|
|
4
4
|
"description": "Unified cache interface with multiple storage implementations",
|
|
5
5
|
"private": false,
|
|
6
6
|
"type": "module",
|
|
@@ -88,6 +88,7 @@
|
|
|
88
88
|
"access": "public"
|
|
89
89
|
},
|
|
90
90
|
"dependencies": {
|
|
91
|
+
"@opentelemetry/api": "~1.9.1",
|
|
91
92
|
"date-fns": "~4.4.0",
|
|
92
93
|
"proper-lockfile": "~4.1.2"
|
|
93
94
|
},
|
|
@@ -98,6 +99,7 @@
|
|
|
98
99
|
"pg": ">=8.23.0"
|
|
99
100
|
},
|
|
100
101
|
"devDependencies": {
|
|
102
|
+
"@opentelemetry/sdk-trace-node": "~2.11.0",
|
|
101
103
|
"@types/pg": "~8.23.1",
|
|
102
104
|
"@types/proper-lockfile": "~4.1.4",
|
|
103
105
|
"ioredis": "~6.0.0",
|