@geekmidas/cache 10.0.0-alpha.98 → 10.0.0

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.
Files changed (96) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/{rolldown-runtime-VH7oDXx4.cjs → chunk-CUT6urMc.cjs} +10 -8
  3. package/dist/expo.cjs +10 -10
  4. package/dist/expo.cjs.map +1 -1
  5. package/dist/expo.d.cts +6 -2
  6. package/dist/expo.d.cts.map +1 -1
  7. package/dist/expo.d.mts +6 -2
  8. package/dist/expo.d.mts.map +1 -1
  9. package/dist/expo.mjs +6 -4
  10. package/dist/expo.mjs.map +1 -1
  11. package/dist/file.cjs +19 -16
  12. package/dist/file.cjs.map +1 -1
  13. package/dist/file.d.cts +6 -3
  14. package/dist/file.d.cts.map +1 -1
  15. package/dist/file.d.mts +6 -3
  16. package/dist/file.d.mts.map +1 -1
  17. package/dist/file.mjs +12 -7
  18. package/dist/file.mjs.map +1 -1
  19. package/dist/index-BSYYdwRm.d.cts +36 -0
  20. package/dist/index-BSYYdwRm.d.cts.map +1 -0
  21. package/dist/index-Dx96gr-9.d.mts +36 -0
  22. package/dist/index-Dx96gr-9.d.mts.map +1 -0
  23. package/dist/index.cjs +2 -17
  24. package/dist/index.d.cts +2 -2
  25. package/dist/index.d.mts +2 -2
  26. package/dist/index.mjs +2 -12
  27. package/dist/memory.cjs +11 -8
  28. package/dist/memory.cjs.map +1 -1
  29. package/dist/memory.d.cts +6 -2
  30. package/dist/memory.d.cts.map +1 -1
  31. package/dist/memory.d.mts +6 -2
  32. package/dist/memory.d.mts.map +1 -1
  33. package/dist/memory.mjs +8 -5
  34. package/dist/memory.mjs.map +1 -1
  35. package/dist/src-CrE4Nl5T.mjs +14 -0
  36. package/dist/src-CrE4Nl5T.mjs.map +1 -0
  37. package/dist/src-zfYb7mdS.cjs +20 -0
  38. package/dist/src-zfYb7mdS.cjs.map +1 -0
  39. package/dist/upstash.cjs +6 -46
  40. package/dist/upstash.cjs.map +1 -1
  41. package/dist/upstash.d.cts +6 -27
  42. package/dist/upstash.d.cts.map +1 -1
  43. package/dist/upstash.d.mts +6 -27
  44. package/dist/upstash.d.mts.map +1 -1
  45. package/dist/upstash.mjs +4 -41
  46. package/dist/upstash.mjs.map +1 -1
  47. package/package.json +6 -53
  48. package/src/__benchmarks__/memory.bench.ts +51 -0
  49. package/src/__tests__/cache.spec.ts +144 -0
  50. package/src/__tests__/file.spec.ts +192 -0
  51. package/src/__tests__/integration.spec.ts +282 -0
  52. package/src/__tests__/memory.spec.ts +134 -0
  53. package/src/__tests__/upstash.spec.ts +276 -0
  54. package/src/expo.ts +50 -0
  55. package/src/file.ts +126 -0
  56. package/src/index.ts +48 -0
  57. package/src/memory.ts +38 -0
  58. package/src/upstash.ts +41 -0
  59. package/tsconfig.json +9 -0
  60. package/tsdown.config.ts +5 -0
  61. package/dist/index-BbdGhmWP.d.cts +0 -62
  62. package/dist/index-BbdGhmWP.d.cts.map +0 -1
  63. package/dist/index-BbdGhmWP.d.mts +0 -62
  64. package/dist/index-BbdGhmWP.d.mts.map +0 -1
  65. package/dist/index.cjs.map +0 -1
  66. package/dist/index.mjs.map +0 -1
  67. package/dist/postgres.cjs +0 -185
  68. package/dist/postgres.cjs.map +0 -1
  69. package/dist/postgres.d.cts +0 -71
  70. package/dist/postgres.d.cts.map +0 -1
  71. package/dist/postgres.d.mts +0 -71
  72. package/dist/postgres.d.mts.map +0 -1
  73. package/dist/postgres.mjs +0 -180
  74. package/dist/postgres.mjs.map +0 -1
  75. package/dist/redis.cjs +0 -88
  76. package/dist/redis.cjs.map +0 -1
  77. package/dist/redis.d.cts +0 -27
  78. package/dist/redis.d.cts.map +0 -1
  79. package/dist/redis.d.mts +0 -27
  80. package/dist/redis.d.mts.map +0 -1
  81. package/dist/redis.mjs +0 -85
  82. package/dist/redis.mjs.map +0 -1
  83. package/dist/registry.cjs +0 -48
  84. package/dist/registry.cjs.map +0 -1
  85. package/dist/registry.d.cts +0 -2
  86. package/dist/registry.d.mts +0 -2
  87. package/dist/registry.mjs +0 -44
  88. package/dist/registry.mjs.map +0 -1
  89. package/dist/telemetry.cjs +0 -38
  90. package/dist/telemetry.cjs.map +0 -1
  91. package/dist/telemetry.d.cts +0 -6
  92. package/dist/telemetry.d.cts.map +0 -1
  93. package/dist/telemetry.d.mts +0 -6
  94. package/dist/telemetry.d.mts.map +0 -1
  95. package/dist/telemetry.mjs +0 -37
  96. package/dist/telemetry.mjs.map +0 -1
package/dist/postgres.mjs DELETED
@@ -1,180 +0,0 @@
1
- import { traceCache } from "./telemetry.mjs";
2
- import pg from "pg";
3
- //#region src/postgres.ts
4
- /**
5
- * A cache that lives in a database you already have.
6
- *
7
- * The backend with no infrastructure. A cache is a table; the database is the
8
- * one the application already declared, so an idle stage costs nothing extra
9
- * and there is one fewer thing to provision, secure and pay for. It is slower
10
- * than Redis and that is the trade: for session lookups, rate-limit counters and
11
- * memoised API responses at ordinary volumes, a primary-key hit on a small table
12
- * is not the thing that will be slow.
13
- *
14
- * **The table is provisioned, not created on first use.** That is the one place
15
- * this differs from pg-boss, and the reason is the role split: a handler
16
- * connects as a role that may read and write rows and may not create anything,
17
- * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where
18
- * the roles are doing their job. The DDL is exported instead — see
19
- * {@link cacheTableStatements} — and applied by whatever applies the rest.
20
- *
21
- * Reads filter on expiry and delete lazily, so an expired row is never returned
22
- * even if nothing has swept it; a sweep is an optimisation, not a correctness
23
- * requirement.
24
- */
25
- const DEFAULT_TABLE = "cache";
26
- var PostgresCache = class {
27
- pool;
28
- table;
29
- constructor(pool, options = {}) {
30
- this.pool = pool;
31
- this.table = options.table ?? DEFAULT_TABLE;
32
- }
33
- async get(key) {
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
- });
39
- }
40
- async set(key, value, ttl) {
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
- });
51
- }
52
- async delete(key) {
53
- return traceCache("postgresql", "delete", async () => {
54
- await this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);
55
- });
56
- }
57
- async ttl(key) {
58
- const { rows } = await this.query(`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds
59
- FROM ${this.identifier()}
60
- WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
61
- const row = rows[0];
62
- if (!row) return 0;
63
- return row.seconds ?? 0;
64
- }
65
- /**
66
- * Delete every expired entry.
67
- *
68
- * Optional: reads already ignore them. Worth running occasionally so the
69
- * table does not grow without bound in a workload that writes many keys once.
70
- */
71
- async sweep() {
72
- const { rowCount } = await this.query(`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`);
73
- return rowCount ?? 0;
74
- }
75
- async query(sql, values = []) {
76
- const result = await this.pool.query(sql, values);
77
- return {
78
- rows: result.rows,
79
- rowCount: result.rowCount
80
- };
81
- }
82
- /**
83
- * The table name as an identifier.
84
- *
85
- * Quoted per segment so a schema-qualified name stays two identifiers rather
86
- * than becoming one with a dot in it. The name comes from configuration
87
- * rather than from a request, so this is defence rather than sanitisation.
88
- */
89
- identifier() {
90
- return quote(this.table);
91
- }
92
- };
93
- /**
94
- * The `postgres://` driver.
95
- *
96
- * One pool per URL, cached for the life of the process: a cache that opened a
97
- * connection per call would be slower than the thing it exists to speed up, and
98
- * a Lambda reusing a warm container should reuse the pool with it.
99
- *
100
- * `pg` is imported at the top of this module rather than lazily, because the
101
- * *module* is the lazy boundary — an app caching in Redis never imports
102
- * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
103
- * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
104
- */
105
- const postgresCacheDriver = {
106
- scheme: "postgres:",
107
- create(url) {
108
- const { connectionString, table } = split(url);
109
- const existing = pools.get(connectionString);
110
- const pool = existing ?? new pg.Pool({ connectionString });
111
- if (!existing) pools.set(connectionString, pool);
112
- return new PostgresCache(pool, table ? { table } : {});
113
- }
114
- };
115
- /**
116
- * A cache URL as its two facts: where to connect, and what to read.
117
- *
118
- * `table` is removed from the string handed to `pg` rather than left on it,
119
- * because a Postgres connection string carries libpq parameters and an unknown
120
- * one is not guaranteed to be ignored — and because the pool should be shared
121
- * by every cache in the database, which only works if the key does not vary
122
- * per cache.
123
- */
124
- function split(url) {
125
- try {
126
- const parsed = new URL(url);
127
- const table = parsed.searchParams.get("table") ?? void 0;
128
- if (!table) return { connectionString: url };
129
- parsed.searchParams.delete("table");
130
- return {
131
- connectionString: parsed.toString(),
132
- table
133
- };
134
- } catch {
135
- return { connectionString: url };
136
- }
137
- }
138
- const pools = /* @__PURE__ */ new Map();
139
- /**
140
- * The DDL a Postgres-backed cache needs, for whoever applies DDL.
141
- *
142
- * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
143
- * statements run in-process from `gkm dev` and from a provisioner inside a VPC,
144
- * and one implementation is what stops "works locally, fails deployed".
145
- *
146
- * Run as the schema's **owner**. The role a handler connects as cannot create a
147
- * table, which is the point of the split and the reason this is not done lazily.
148
- */
149
- function cacheTableStatements(options = {}) {
150
- const table = options.table ?? DEFAULT_TABLE;
151
- const [schema, name] = table.includes(".") ? table.split(".") : [void 0, table];
152
- const qualified = quote(table);
153
- return [{
154
- describe: `cache table ${table}`,
155
- exists: {
156
- sql: schema ? "SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2" : "SELECT 1 FROM information_schema.tables WHERE table_name = $1",
157
- values: schema ? [schema, name] : [name]
158
- },
159
- sql: `CREATE TABLE ${qualified} (
160
- key text PRIMARY KEY,
161
- value jsonb NOT NULL,
162
- expires_at timestamptz
163
- )`
164
- }, {
165
- describe: `cache expiry index on ${table}`,
166
- sql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}
167
- ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`
168
- }];
169
- }
170
- /** A possibly schema-qualified name, quoted per segment. */
171
- function quote(table) {
172
- return table.split(".").map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(".");
173
- }
174
- function indexName(table) {
175
- return `"${table.replace(/[^a-zA-Z0-9]/g, "_")}_expires_at_idx"`;
176
- }
177
- //#endregion
178
- export { PostgresCache, cacheTableStatements, postgresCacheDriver };
179
-
180
- //# sourceMappingURL=postgres.mjs.map
@@ -1 +0,0 @@
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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SAAS,UAAU,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;AAChD"}
package/dist/redis.cjs DELETED
@@ -1,88 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_telemetry = require("./telemetry.cjs");
3
- let ioredis = require("ioredis");
4
- //#region src/redis.ts
5
- /**
6
- * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.
7
- *
8
- * The sibling of the Upstash client rather than a replacement for it. Upstash
9
- * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and
10
- * no connection pool; this speaks the wire protocol, which is what ElastiCache
11
- * offers and what a container next to your app is cheapest on.
12
- *
13
- * Choosing one is a deployment decision, and the local target follows it: pick
14
- * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP
15
- * proxy in front of it. Either way dev and prod speak the same protocol, which
16
- * is the property that matters — a cache that behaves differently in the two
17
- * places is worse than a slower one.
18
- */
19
- var RedisCache = class {
20
- client;
21
- constructor(client) {
22
- this.client = client;
23
- }
24
- async get(key) {
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
- });
34
- }
35
- async set(key, value, ttl) {
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
- });
44
- }
45
- async delete(key) {
46
- return require_telemetry.traceCache("redis", "delete", async () => {
47
- await this.client.del(key);
48
- });
49
- }
50
- async ttl(key) {
51
- const seconds = await this.client.ttl(key);
52
- return seconds < 0 ? 0 : seconds;
53
- }
54
- };
55
- /**
56
- * The `redis://` and `rediss://` driver.
57
- *
58
- * One client per URL for the life of the process — a Redis connection is a
59
- * socket, and opening one per cache call is the thing that makes people
60
- * conclude a cache is not worth having.
61
- *
62
- * `ioredis` is imported at the top of this module because the *module* is the
63
- * lazy boundary: an app caching in Postgres never imports
64
- * `@geekmidas/cache/redis`, and so never resolves it.
65
- */
66
- const redisCacheDriver = {
67
- scheme: "redis:",
68
- create: (url) => new RedisCache(clientFor(url))
69
- };
70
- /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
71
- const redissCacheDriver = {
72
- scheme: "rediss:",
73
- create: (url) => new RedisCache(clientFor(url))
74
- };
75
- const clients = /* @__PURE__ */ new Map();
76
- function clientFor(url) {
77
- const existing = clients.get(url);
78
- if (existing) return existing;
79
- const client = new ioredis.Redis(url, { maxRetriesPerRequest: 2 });
80
- clients.set(url, client);
81
- return client;
82
- }
83
- //#endregion
84
- exports.RedisCache = RedisCache;
85
- exports.redisCacheDriver = redisCacheDriver;
86
- exports.redissCacheDriver = redissCacheDriver;
87
-
88
- //# sourceMappingURL=redis.cjs.map
@@ -1 +0,0 @@
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 DELETED
@@ -1,27 +0,0 @@
1
- import { r as CacheDriver, t as Cache } from "./index-BbdGhmWP.cjs";
2
- import { Redis } from "ioredis";
3
- //#region src/redis.d.ts
4
- export declare class RedisCache implements Cache {
5
- private readonly client;
6
- constructor(client: Redis);
7
- get<T>(key: string): Promise<T | undefined>;
8
- set<T>(key: string, value: T, ttl?: number): Promise<void>;
9
- delete(key: string): Promise<void>;
10
- ttl(key: string): Promise<number>;
11
- }
12
- /**
13
- * The `redis://` and `rediss://` driver.
14
- *
15
- * One client per URL for the life of the process — a Redis connection is a
16
- * socket, and opening one per cache call is the thing that makes people
17
- * conclude a cache is not worth having.
18
- *
19
- * `ioredis` is imported at the top of this module because the *module* is the
20
- * lazy boundary: an app caching in Postgres never imports
21
- * `@geekmidas/cache/redis`, and so never resolves it.
22
- */
23
- export declare const redisCacheDriver: CacheDriver;
24
- /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
25
- export declare const redissCacheDriver: CacheDriver;
26
- //#endregion
27
- //# sourceMappingURL=redis.d.cts.map
@@ -1 +0,0 @@
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 DELETED
@@ -1,27 +0,0 @@
1
- import { r as CacheDriver, t as Cache } from "./index-BbdGhmWP.mjs";
2
- import { Redis } from "ioredis";
3
- //#region src/redis.d.ts
4
- export declare class RedisCache implements Cache {
5
- private readonly client;
6
- constructor(client: Redis);
7
- get<T>(key: string): Promise<T | undefined>;
8
- set<T>(key: string, value: T, ttl?: number): Promise<void>;
9
- delete(key: string): Promise<void>;
10
- ttl(key: string): Promise<number>;
11
- }
12
- /**
13
- * The `redis://` and `rediss://` driver.
14
- *
15
- * One client per URL for the life of the process — a Redis connection is a
16
- * socket, and opening one per cache call is the thing that makes people
17
- * conclude a cache is not worth having.
18
- *
19
- * `ioredis` is imported at the top of this module because the *module* is the
20
- * lazy boundary: an app caching in Postgres never imports
21
- * `@geekmidas/cache/redis`, and so never resolves it.
22
- */
23
- export declare const redisCacheDriver: CacheDriver;
24
- /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
25
- export declare const redissCacheDriver: CacheDriver;
26
- //#endregion
27
- //# sourceMappingURL=redis.d.mts.map
@@ -1 +0,0 @@
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 DELETED
@@ -1,85 +0,0 @@
1
- import { traceCache } from "./telemetry.mjs";
2
- import { Redis } from "ioredis";
3
- //#region src/redis.ts
4
- /**
5
- * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.
6
- *
7
- * The sibling of the Upstash client rather than a replacement for it. Upstash
8
- * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and
9
- * no connection pool; this speaks the wire protocol, which is what ElastiCache
10
- * offers and what a container next to your app is cheapest on.
11
- *
12
- * Choosing one is a deployment decision, and the local target follows it: pick
13
- * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP
14
- * proxy in front of it. Either way dev and prod speak the same protocol, which
15
- * is the property that matters — a cache that behaves differently in the two
16
- * places is worse than a slower one.
17
- */
18
- var RedisCache = class {
19
- client;
20
- constructor(client) {
21
- this.client = client;
22
- }
23
- async get(key) {
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
- });
33
- }
34
- async set(key, value, ttl) {
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
- });
43
- }
44
- async delete(key) {
45
- return traceCache("redis", "delete", async () => {
46
- await this.client.del(key);
47
- });
48
- }
49
- async ttl(key) {
50
- const seconds = await this.client.ttl(key);
51
- return seconds < 0 ? 0 : seconds;
52
- }
53
- };
54
- /**
55
- * The `redis://` and `rediss://` driver.
56
- *
57
- * One client per URL for the life of the process — a Redis connection is a
58
- * socket, and opening one per cache call is the thing that makes people
59
- * conclude a cache is not worth having.
60
- *
61
- * `ioredis` is imported at the top of this module because the *module* is the
62
- * lazy boundary: an app caching in Postgres never imports
63
- * `@geekmidas/cache/redis`, and so never resolves it.
64
- */
65
- const redisCacheDriver = {
66
- scheme: "redis:",
67
- create: (url) => new RedisCache(clientFor(url))
68
- };
69
- /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
70
- const redissCacheDriver = {
71
- scheme: "rediss:",
72
- create: (url) => new RedisCache(clientFor(url))
73
- };
74
- const clients = /* @__PURE__ */ new Map();
75
- function clientFor(url) {
76
- const existing = clients.get(url);
77
- if (existing) return existing;
78
- const client = new Redis(url, { maxRetriesPerRequest: 2 });
79
- clients.set(url, client);
80
- return client;
81
- }
82
- //#endregion
83
- export { RedisCache, redisCacheDriver, redissCacheDriver };
84
-
85
- //# sourceMappingURL=redis.mjs.map
@@ -1 +0,0 @@
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":";;;;;;;;;;;;;;;;;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AAO;AACR"}
package/dist/registry.cjs DELETED
@@ -1,48 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/registry.ts
3
- const drivers = /* @__PURE__ */ new Map();
4
- /** Make a driver available to {@link createCacheClient}. Idempotent. */
5
- function registerCacheDriver(driver) {
6
- drivers.set(driver.scheme, driver);
7
- }
8
- /** Which schemes are currently registered — the useful half of a failure. */
9
- function registeredCacheSchemes() {
10
- return [...drivers.keys()].sort();
11
- }
12
- /**
13
- * Build a client for a URL.
14
- *
15
- * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in
16
- * practice means the entry point registered a different one — the backend and
17
- * the build disagreeing, caught at the first cache call rather than never.
18
- */
19
- function createCacheClient(url) {
20
- const scheme = schemeOf(url);
21
- const driver = drivers.get(scheme);
22
- if (!driver) throw new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());
23
- return driver.create(url);
24
- }
25
- /** No driver handles the scheme in a cache URL. */
26
- var UnregisteredCacheScheme = class extends Error {
27
- url;
28
- scheme;
29
- registered;
30
- constructor(url, scheme, registered) {
31
- super(`No cache driver handles '${scheme}'. ` + (registered.length ? `Registered: ${registered.join(", ")}.` : "Nothing is registered.") + " The scheme comes from the backend the target provisioned, so this is usually a build that registered a different one.");
32
- this.url = url;
33
- this.scheme = scheme;
34
- this.registered = registered;
35
- this.name = "UnregisteredCacheScheme";
36
- }
37
- };
38
- function schemeOf(url) {
39
- const separator = url.indexOf(":");
40
- return separator === -1 ? "" : url.slice(0, separator + 1);
41
- }
42
- //#endregion
43
- exports.UnregisteredCacheScheme = UnregisteredCacheScheme;
44
- exports.createCacheClient = createCacheClient;
45
- exports.registerCacheDriver = registerCacheDriver;
46
- exports.registeredCacheSchemes = registeredCacheSchemes;
47
-
48
- //# sourceMappingURL=registry.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry.cjs","names":[],"sources":["../src/registry.ts"],"sourcesContent":["/**\n * Cache drivers, keyed by URL scheme.\n *\n * The same shape `@geekmidas/storage` uses, for the same reason: a construct is\n * handed one URL and the scheme in it picks the client. That is what lets the\n * *backend* be a deployment choice rather than an application one — an app\n * caching in Postgres and an app caching in Upstash are the same code.\n *\n * Registration is explicit rather than an import side effect, because a\n * side-effecting module is exactly what a bundler is entitled to drop — and\n * because an app that caches in Postgres should never resolve a Redis client.\n */\n\nimport type { Cache } from './index';\n\n/** What a driver has to supply: a scheme it answers to, and a client for a URL. */\nexport interface CacheDriver {\n\t/** Including the colon, as `URL.protocol` reports it — `redis:`, `https:`. */\n\tscheme: string;\n\tcreate(url: string): Cache;\n}\n\nconst drivers = new Map<string, CacheDriver>();\n\n/** Make a driver available to {@link createCacheClient}. Idempotent. */\nexport function registerCacheDriver(driver: CacheDriver): void {\n\tdrivers.set(driver.scheme, driver);\n}\n\n/** Which schemes are currently registered — the useful half of a failure. */\nexport function registeredCacheSchemes(): string[] {\n\treturn [...drivers.keys()].sort();\n}\n\n/**\n * Build a client for a URL.\n *\n * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in\n * practice means the entry point registered a different one — the backend and\n * the build disagreeing, caught at the first cache call rather than never.\n */\nexport function createCacheClient(url: string): Cache {\n\tconst scheme = schemeOf(url);\n\tconst driver = drivers.get(scheme);\n\n\tif (!driver) {\n\t\tthrow new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());\n\t}\n\n\treturn driver.create(url);\n}\n\n/** No driver handles the scheme in a cache URL. */\nexport class UnregisteredCacheScheme extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly scheme: string,\n\t\treadonly registered: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`No cache driver handles '${scheme}'. ` +\n\t\t\t\t(registered.length\n\t\t\t\t\t? `Registered: ${registered.join(', ')}.`\n\t\t\t\t\t: 'Nothing is registered.') +\n\t\t\t\t' The scheme comes from the backend the target provisioned, so this ' +\n\t\t\t\t'is usually a build that registered a different one.',\n\t\t);\n\t\tthis.name = 'UnregisteredCacheScheme';\n\t}\n}\n\nfunction schemeOf(url: string): string {\n\tconst separator = url.indexOf(':');\n\treturn separator === -1 ? '' : url.slice(0, separator + 1);\n}\n"],"mappings":";;AAsBA,MAAM,0BAAU,IAAI,IAAyB;;AAG7C,SAAgB,oBAAoB,QAA2B;CAC9D,QAAQ,IAAI,OAAO,QAAQ,MAAM;AAClC;;AAGA,SAAgB,yBAAmC;CAClD,OAAO,CAAC,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,KAAK;AACjC;;;;;;;;AASA,SAAgB,kBAAkB,KAAoB;CACrD,MAAM,SAAS,SAAS,GAAG;CAC3B,MAAM,SAAS,QAAQ,IAAI,MAAM;CAEjC,IAAI,CAAC,QACJ,MAAM,IAAI,wBAAwB,KAAK,QAAQ,uBAAuB,CAAC;CAGxE,OAAO,OAAO,OAAO,GAAG;AACzB;;AAGA,IAAa,0BAAb,cAA6C,MAAM;CAExC;CACA;CACA;CAHV,YACC,KACA,QACA,YACC;EACD,MACC,4BAA4B,OAAO,QACjC,WAAW,SACT,eAAe,WAAW,KAAK,IAAI,EAAE,KACrC,4BACH,wHAEF;EAXS,KAAA,MAAA;EACA,KAAA,SAAA;EACA,KAAA,aAAA;EAUT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,SAAS,KAAqB;CACtC,MAAM,YAAY,IAAI,QAAQ,GAAG;CACjC,OAAO,cAAc,KAAK,KAAK,IAAI,MAAM,GAAG,YAAY,CAAC;AAC1D"}
@@ -1,2 +0,0 @@
1
- import { a as createCacheClient, i as UnregisteredCacheScheme, o as registerCacheDriver, r as CacheDriver, s as registeredCacheSchemes } from "./index-BbdGhmWP.cjs";
2
- export { CacheDriver, UnregisteredCacheScheme, createCacheClient, registerCacheDriver, registeredCacheSchemes };
@@ -1,2 +0,0 @@
1
- import { a as createCacheClient, i as UnregisteredCacheScheme, o as registerCacheDriver, r as CacheDriver, s as registeredCacheSchemes } from "./index-BbdGhmWP.mjs";
2
- export { CacheDriver, UnregisteredCacheScheme, createCacheClient, registerCacheDriver, registeredCacheSchemes };
package/dist/registry.mjs DELETED
@@ -1,44 +0,0 @@
1
- //#region src/registry.ts
2
- const drivers = /* @__PURE__ */ new Map();
3
- /** Make a driver available to {@link createCacheClient}. Idempotent. */
4
- function registerCacheDriver(driver) {
5
- drivers.set(driver.scheme, driver);
6
- }
7
- /** Which schemes are currently registered — the useful half of a failure. */
8
- function registeredCacheSchemes() {
9
- return [...drivers.keys()].sort();
10
- }
11
- /**
12
- * Build a client for a URL.
13
- *
14
- * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in
15
- * practice means the entry point registered a different one — the backend and
16
- * the build disagreeing, caught at the first cache call rather than never.
17
- */
18
- function createCacheClient(url) {
19
- const scheme = schemeOf(url);
20
- const driver = drivers.get(scheme);
21
- if (!driver) throw new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());
22
- return driver.create(url);
23
- }
24
- /** No driver handles the scheme in a cache URL. */
25
- var UnregisteredCacheScheme = class extends Error {
26
- url;
27
- scheme;
28
- registered;
29
- constructor(url, scheme, registered) {
30
- super(`No cache driver handles '${scheme}'. ` + (registered.length ? `Registered: ${registered.join(", ")}.` : "Nothing is registered.") + " The scheme comes from the backend the target provisioned, so this is usually a build that registered a different one.");
31
- this.url = url;
32
- this.scheme = scheme;
33
- this.registered = registered;
34
- this.name = "UnregisteredCacheScheme";
35
- }
36
- };
37
- function schemeOf(url) {
38
- const separator = url.indexOf(":");
39
- return separator === -1 ? "" : url.slice(0, separator + 1);
40
- }
41
- //#endregion
42
- export { UnregisteredCacheScheme, createCacheClient, registerCacheDriver, registeredCacheSchemes };
43
-
44
- //# sourceMappingURL=registry.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry.mjs","names":[],"sources":["../src/registry.ts"],"sourcesContent":["/**\n * Cache drivers, keyed by URL scheme.\n *\n * The same shape `@geekmidas/storage` uses, for the same reason: a construct is\n * handed one URL and the scheme in it picks the client. That is what lets the\n * *backend* be a deployment choice rather than an application one — an app\n * caching in Postgres and an app caching in Upstash are the same code.\n *\n * Registration is explicit rather than an import side effect, because a\n * side-effecting module is exactly what a bundler is entitled to drop — and\n * because an app that caches in Postgres should never resolve a Redis client.\n */\n\nimport type { Cache } from './index';\n\n/** What a driver has to supply: a scheme it answers to, and a client for a URL. */\nexport interface CacheDriver {\n\t/** Including the colon, as `URL.protocol` reports it — `redis:`, `https:`. */\n\tscheme: string;\n\tcreate(url: string): Cache;\n}\n\nconst drivers = new Map<string, CacheDriver>();\n\n/** Make a driver available to {@link createCacheClient}. Idempotent. */\nexport function registerCacheDriver(driver: CacheDriver): void {\n\tdrivers.set(driver.scheme, driver);\n}\n\n/** Which schemes are currently registered — the useful half of a failure. */\nexport function registeredCacheSchemes(): string[] {\n\treturn [...drivers.keys()].sort();\n}\n\n/**\n * Build a client for a URL.\n *\n * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in\n * practice means the entry point registered a different one — the backend and\n * the build disagreeing, caught at the first cache call rather than never.\n */\nexport function createCacheClient(url: string): Cache {\n\tconst scheme = schemeOf(url);\n\tconst driver = drivers.get(scheme);\n\n\tif (!driver) {\n\t\tthrow new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());\n\t}\n\n\treturn driver.create(url);\n}\n\n/** No driver handles the scheme in a cache URL. */\nexport class UnregisteredCacheScheme extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly scheme: string,\n\t\treadonly registered: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`No cache driver handles '${scheme}'. ` +\n\t\t\t\t(registered.length\n\t\t\t\t\t? `Registered: ${registered.join(', ')}.`\n\t\t\t\t\t: 'Nothing is registered.') +\n\t\t\t\t' The scheme comes from the backend the target provisioned, so this ' +\n\t\t\t\t'is usually a build that registered a different one.',\n\t\t);\n\t\tthis.name = 'UnregisteredCacheScheme';\n\t}\n}\n\nfunction schemeOf(url: string): string {\n\tconst separator = url.indexOf(':');\n\treturn separator === -1 ? '' : url.slice(0, separator + 1);\n}\n"],"mappings":";AAsBA,MAAM,0BAAU,IAAI,IAAyB;;AAG7C,SAAgB,oBAAoB,QAA2B;CAC9D,QAAQ,IAAI,OAAO,QAAQ,MAAM;AAClC;;AAGA,SAAgB,yBAAmC;CAClD,OAAO,CAAC,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,KAAK;AACjC;;;;;;;;AASA,SAAgB,kBAAkB,KAAoB;CACrD,MAAM,SAAS,SAAS,GAAG;CAC3B,MAAM,SAAS,QAAQ,IAAI,MAAM;CAEjC,IAAI,CAAC,QACJ,MAAM,IAAI,wBAAwB,KAAK,QAAQ,uBAAuB,CAAC;CAGxE,OAAO,OAAO,OAAO,GAAG;AACzB;;AAGA,IAAa,0BAAb,cAA6C,MAAM;CAExC;CACA;CACA;CAHV,YACC,KACA,QACA,YACC;EACD,MACC,4BAA4B,OAAO,QACjC,WAAW,SACT,eAAe,WAAW,KAAK,IAAI,EAAE,KACrC,4BACH,wHAEF;EAXS,KAAA,MAAA;EACA,KAAA,SAAA;EACA,KAAA,aAAA;EAUT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,SAAS,KAAqB;CACtC,MAAM,YAAY,IAAI,QAAQ,GAAG;CACjC,OAAO,cAAc,KAAK,KAAK,IAAI,MAAM,GAAG,YAAY,CAAC;AAC1D"}
@@ -1,38 +0,0 @@
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
@@ -1 +0,0 @@
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"}
@@ -1,6 +0,0 @@
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
@@ -1 +0,0 @@
1
- {"version":3,"file":"telemetry.d.cts","names":[],"sources":["../src/telemetry.ts"],"mappings":";YAYY;;wBAGU,WAAW,GAChC,gBACA,WAAW,gBACX,UAAU,QAAQ,KAChB,QAAQ"}