@geekmidas/cache 10.0.0-alpha.99 → 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.
- package/CHANGELOG.md +52 -0
- package/dist/{rolldown-runtime-VH7oDXx4.cjs → chunk-CUT6urMc.cjs} +10 -8
- package/dist/expo.cjs +10 -10
- package/dist/expo.cjs.map +1 -1
- package/dist/expo.d.cts +6 -2
- package/dist/expo.d.cts.map +1 -1
- package/dist/expo.d.mts +6 -2
- package/dist/expo.d.mts.map +1 -1
- package/dist/expo.mjs +6 -4
- package/dist/expo.mjs.map +1 -1
- package/dist/file.cjs +19 -16
- package/dist/file.cjs.map +1 -1
- package/dist/file.d.cts +6 -3
- package/dist/file.d.cts.map +1 -1
- package/dist/file.d.mts +6 -3
- package/dist/file.d.mts.map +1 -1
- package/dist/file.mjs +12 -7
- package/dist/file.mjs.map +1 -1
- package/dist/index-BSYYdwRm.d.cts +36 -0
- package/dist/index-BSYYdwRm.d.cts.map +1 -0
- package/dist/index-Dx96gr-9.d.mts +36 -0
- package/dist/index-Dx96gr-9.d.mts.map +1 -0
- package/dist/index.cjs +2 -17
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -12
- package/dist/memory.cjs +11 -8
- package/dist/memory.cjs.map +1 -1
- package/dist/memory.d.cts +6 -2
- package/dist/memory.d.cts.map +1 -1
- package/dist/memory.d.mts +6 -2
- package/dist/memory.d.mts.map +1 -1
- package/dist/memory.mjs +8 -5
- package/dist/memory.mjs.map +1 -1
- package/dist/src-CrE4Nl5T.mjs +14 -0
- package/dist/src-CrE4Nl5T.mjs.map +1 -0
- package/dist/src-zfYb7mdS.cjs +20 -0
- package/dist/src-zfYb7mdS.cjs.map +1 -0
- package/dist/upstash.cjs +6 -46
- package/dist/upstash.cjs.map +1 -1
- package/dist/upstash.d.cts +6 -27
- package/dist/upstash.d.cts.map +1 -1
- package/dist/upstash.d.mts +6 -27
- package/dist/upstash.d.mts.map +1 -1
- package/dist/upstash.mjs +4 -41
- package/dist/upstash.mjs.map +1 -1
- package/package.json +6 -53
- package/src/__benchmarks__/memory.bench.ts +51 -0
- package/src/__tests__/cache.spec.ts +144 -0
- package/src/__tests__/file.spec.ts +192 -0
- package/src/__tests__/integration.spec.ts +282 -0
- package/src/__tests__/memory.spec.ts +134 -0
- package/src/__tests__/upstash.spec.ts +276 -0
- package/src/expo.ts +50 -0
- package/src/file.ts +126 -0
- package/src/index.ts +48 -0
- package/src/memory.ts +38 -0
- package/src/upstash.ts +41 -0
- package/tsconfig.json +9 -0
- package/tsdown.config.ts +5 -0
- package/dist/index-BbdGhmWP.d.cts +0 -62
- package/dist/index-BbdGhmWP.d.cts.map +0 -1
- package/dist/index-BbdGhmWP.d.mts +0 -62
- package/dist/index-BbdGhmWP.d.mts.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/postgres.cjs +0 -185
- package/dist/postgres.cjs.map +0 -1
- package/dist/postgres.d.cts +0 -71
- package/dist/postgres.d.cts.map +0 -1
- package/dist/postgres.d.mts +0 -71
- package/dist/postgres.d.mts.map +0 -1
- package/dist/postgres.mjs +0 -180
- package/dist/postgres.mjs.map +0 -1
- package/dist/redis.cjs +0 -88
- package/dist/redis.cjs.map +0 -1
- package/dist/redis.d.cts +0 -27
- package/dist/redis.d.cts.map +0 -1
- package/dist/redis.d.mts +0 -27
- package/dist/redis.d.mts.map +0 -1
- package/dist/redis.mjs +0 -85
- package/dist/redis.mjs.map +0 -1
- package/dist/registry.cjs +0 -48
- package/dist/registry.cjs.map +0 -1
- package/dist/registry.d.cts +0 -2
- package/dist/registry.d.mts +0 -2
- package/dist/registry.mjs +0 -44
- package/dist/registry.mjs.map +0 -1
- package/dist/telemetry.cjs +0 -38
- package/dist/telemetry.cjs.map +0 -1
- package/dist/telemetry.d.cts +0 -6
- package/dist/telemetry.d.cts.map +0 -1
- package/dist/telemetry.d.mts +0 -6
- package/dist/telemetry.d.mts.map +0 -1
- package/dist/telemetry.mjs +0 -37
- package/dist/telemetry.mjs.map +0 -1
package/src/upstash.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Redis } from '@upstash/redis';
|
|
2
|
+
import type { Cache } from './';
|
|
3
|
+
|
|
4
|
+
export class UpstashCache implements Cache {
|
|
5
|
+
private client: Redis;
|
|
6
|
+
|
|
7
|
+
constructor(url: string, token: string) {
|
|
8
|
+
this.client = new Redis({
|
|
9
|
+
url,
|
|
10
|
+
token,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async ttl(key: string): Promise<number> {
|
|
15
|
+
const ttl = await this.client.ttl(key);
|
|
16
|
+
|
|
17
|
+
if (ttl === -2) {
|
|
18
|
+
return 0; // Key does not exist
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return ttl; // Returns TTL in seconds
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async get<T>(key: string): Promise<T | undefined> {
|
|
25
|
+
const v = await this.client.get(key);
|
|
26
|
+
|
|
27
|
+
if (v === null) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return v as T;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async set<T>(key: string, value: T, ttl = 3600): Promise<void> {
|
|
35
|
+
await this.client.set(key, value, { ex: ttl });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async delete(key: string): Promise<void> {
|
|
39
|
+
await this.client.del(key);
|
|
40
|
+
}
|
|
41
|
+
}
|
package/tsconfig.json
ADDED
package/tsdown.config.ts
ADDED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
//#region src/registry.d.ts
|
|
2
|
-
/** What a driver has to supply: a scheme it answers to, and a client for a URL. */
|
|
3
|
-
interface CacheDriver {
|
|
4
|
-
/** Including the colon, as `URL.protocol` reports it — `redis:`, `https:`. */
|
|
5
|
-
scheme: string;
|
|
6
|
-
create(url: string): Cache;
|
|
7
|
-
}
|
|
8
|
-
/** Make a driver available to {@link createCacheClient}. Idempotent. */
|
|
9
|
-
declare function registerCacheDriver(driver: CacheDriver): void;
|
|
10
|
-
/** Which schemes are currently registered — the useful half of a failure. */
|
|
11
|
-
declare function registeredCacheSchemes(): string[];
|
|
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
|
-
declare function createCacheClient(url: string): Cache;
|
|
20
|
-
/** No driver handles the scheme in a cache URL. */
|
|
21
|
-
declare class UnregisteredCacheScheme extends Error {
|
|
22
|
-
readonly url: string;
|
|
23
|
-
readonly scheme: string;
|
|
24
|
-
readonly registered: readonly string[];
|
|
25
|
-
constructor(url: string, scheme: string, registered: readonly string[]);
|
|
26
|
-
}
|
|
27
|
-
//#endregion
|
|
28
|
-
//#region src/index.d.ts
|
|
29
|
-
declare const getExpirationInSeconds: (expiresAt: string | number | Date | undefined | null) => number;
|
|
30
|
-
interface Cache {
|
|
31
|
-
/**
|
|
32
|
-
* Retrieves a value from the cache.
|
|
33
|
-
*
|
|
34
|
-
* @param key The key to retrieve the value for.
|
|
35
|
-
* @returns The cached value, or undefined if not found.
|
|
36
|
-
*/
|
|
37
|
-
get<T>(key: string): Promise<T | undefined>;
|
|
38
|
-
/**
|
|
39
|
-
* Sets a value in the cache.
|
|
40
|
-
*
|
|
41
|
-
* @param key The key to set the value for.
|
|
42
|
-
* @param value The value to cache.
|
|
43
|
-
* @param ttl Optional time-to-live in seconds. If not provided, the value will not expire.
|
|
44
|
-
*/
|
|
45
|
-
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
46
|
-
/**
|
|
47
|
-
* Deletes a value from the cache.
|
|
48
|
-
*
|
|
49
|
-
* @param key The key to delete from the cache.
|
|
50
|
-
*/
|
|
51
|
-
delete(key: string): Promise<void>;
|
|
52
|
-
/**
|
|
53
|
-
* Retrieves the time-to-live (TTL) for a cached value.
|
|
54
|
-
*
|
|
55
|
-
* @param key The key to retrieve the TTL for.
|
|
56
|
-
* @returns The TTL in seconds, or 0 if the key does not exist.
|
|
57
|
-
*/
|
|
58
|
-
ttl(key: string): Promise<number>;
|
|
59
|
-
}
|
|
60
|
-
//#endregion
|
|
61
|
-
export { createCacheClient as a, UnregisteredCacheScheme as i, getExpirationInSeconds as n, registerCacheDriver as o, CacheDriver as r, registeredCacheSchemes as s, Cache as t };
|
|
62
|
-
//# sourceMappingURL=index-BbdGhmWP.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-BbdGhmWP.d.cts","names":[],"sources":["../src/registry.ts","../src/index.ts"],"mappings":";;UAgBiB;;EAEhB;EACA,OAAO,cAAc;;;iBAMN,oBAAoB,QAAQ;;iBAK5B;;;;;;;;iBAWA,kBAAkB,cAAc;;cAYnC,gCAAgC;WAElC;WACA;WACA;EAHV,YACU,aACA,gBACA;;;;cCvDE,yBAAsB,6BACL;UAcb;;;;;;;EAOhB,IAAI,GAAG,cAAc,QAAQ;;;;;;;;EAQ7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;;;;;;EAM7C,OAAO,cAAc;;;;;;;EAQrB,IAAI,cAAc"}
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
//#region src/registry.d.ts
|
|
2
|
-
/** What a driver has to supply: a scheme it answers to, and a client for a URL. */
|
|
3
|
-
interface CacheDriver {
|
|
4
|
-
/** Including the colon, as `URL.protocol` reports it — `redis:`, `https:`. */
|
|
5
|
-
scheme: string;
|
|
6
|
-
create(url: string): Cache;
|
|
7
|
-
}
|
|
8
|
-
/** Make a driver available to {@link createCacheClient}. Idempotent. */
|
|
9
|
-
declare function registerCacheDriver(driver: CacheDriver): void;
|
|
10
|
-
/** Which schemes are currently registered — the useful half of a failure. */
|
|
11
|
-
declare function registeredCacheSchemes(): string[];
|
|
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
|
-
declare function createCacheClient(url: string): Cache;
|
|
20
|
-
/** No driver handles the scheme in a cache URL. */
|
|
21
|
-
declare class UnregisteredCacheScheme extends Error {
|
|
22
|
-
readonly url: string;
|
|
23
|
-
readonly scheme: string;
|
|
24
|
-
readonly registered: readonly string[];
|
|
25
|
-
constructor(url: string, scheme: string, registered: readonly string[]);
|
|
26
|
-
}
|
|
27
|
-
//#endregion
|
|
28
|
-
//#region src/index.d.ts
|
|
29
|
-
declare const getExpirationInSeconds: (expiresAt: string | number | Date | undefined | null) => number;
|
|
30
|
-
interface Cache {
|
|
31
|
-
/**
|
|
32
|
-
* Retrieves a value from the cache.
|
|
33
|
-
*
|
|
34
|
-
* @param key The key to retrieve the value for.
|
|
35
|
-
* @returns The cached value, or undefined if not found.
|
|
36
|
-
*/
|
|
37
|
-
get<T>(key: string): Promise<T | undefined>;
|
|
38
|
-
/**
|
|
39
|
-
* Sets a value in the cache.
|
|
40
|
-
*
|
|
41
|
-
* @param key The key to set the value for.
|
|
42
|
-
* @param value The value to cache.
|
|
43
|
-
* @param ttl Optional time-to-live in seconds. If not provided, the value will not expire.
|
|
44
|
-
*/
|
|
45
|
-
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
46
|
-
/**
|
|
47
|
-
* Deletes a value from the cache.
|
|
48
|
-
*
|
|
49
|
-
* @param key The key to delete from the cache.
|
|
50
|
-
*/
|
|
51
|
-
delete(key: string): Promise<void>;
|
|
52
|
-
/**
|
|
53
|
-
* Retrieves the time-to-live (TTL) for a cached value.
|
|
54
|
-
*
|
|
55
|
-
* @param key The key to retrieve the TTL for.
|
|
56
|
-
* @returns The TTL in seconds, or 0 if the key does not exist.
|
|
57
|
-
*/
|
|
58
|
-
ttl(key: string): Promise<number>;
|
|
59
|
-
}
|
|
60
|
-
//#endregion
|
|
61
|
-
export { createCacheClient as a, UnregisteredCacheScheme as i, getExpirationInSeconds as n, registerCacheDriver as o, CacheDriver as r, registeredCacheSchemes as s, Cache as t };
|
|
62
|
-
//# sourceMappingURL=index-BbdGhmWP.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-BbdGhmWP.d.mts","names":[],"sources":["../src/registry.ts","../src/index.ts"],"mappings":";;UAgBiB;;EAEhB;EACA,OAAO,cAAc;;;iBAMN,oBAAoB,QAAQ;;iBAK5B;;;;;;;;iBAWA,kBAAkB,cAAc;;cAYnC,gCAAgC;WAElC;WACA;WACA;EAHV,YACU,aACA,gBACA;;;;cCvDE,yBAAsB,6BACL;UAcb;;;;;;;EAOhB,IAAI,GAAG,cAAc,QAAQ;;;;;;;;EAQ7B,IAAI,GAAG,aAAa,OAAO,GAAG,eAAe;;;;;;EAM7C,OAAO,cAAc;;;;;;;EAQrB,IAAI,cAAc"}
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["differenceInSeconds"],"sources":["../src/index.ts"],"sourcesContent":["import { differenceInSeconds } from 'date-fns';\n\nexport const getExpirationInSeconds = (\n\texpiresAt: string | number | Date | undefined | null,\n): number => {\n\tif (!expiresAt) {\n\t\treturn 0;\n\t}\n\n\tconst expirationDate = new Date(expiresAt);\n\tconst now = new Date();\n\n\tconst secondsLeft = differenceInSeconds(expirationDate, now);\n\n\treturn Math.max(secondsLeft, 0);\n};\n\nexport interface Cache {\n\t/**\n\t * Retrieves a value from the cache.\n\t *\n\t * @param key The key to retrieve the value for.\n\t * @returns The cached value, or undefined if not found.\n\t */\n\tget<T>(key: string): Promise<T | undefined>;\n\t/**\n\t * Sets a value in the cache.\n\t *\n\t * @param key The key to set the value for.\n\t * @param value The value to cache.\n\t * @param ttl Optional time-to-live in seconds. If not provided, the value will not expire.\n\t */\n\tset<T>(key: string, value: T, ttl?: number): Promise<void>;\n\t/**\n\t * Deletes a value from the cache.\n\t *\n\t * @param key The key to delete from the cache.\n\t */\n\tdelete(key: string): Promise<void>;\n\n\t/**\n\t * Retrieves the time-to-live (TTL) for a cached value.\n\t *\n\t * @param key The key to retrieve the TTL for.\n\t * @returns The TTL in seconds, or 0 if the key does not exist.\n\t */\n\tttl(key: string): Promise<number>;\n}\n\nexport type { CacheDriver } from './registry';\nexport {\n\tcreateCacheClient,\n\tregisterCacheDriver,\n\tregisteredCacheSchemes,\n\tUnregisteredCacheScheme,\n} from './registry';\n"],"mappings":";;;;AAEA,MAAa,0BACZ,cACY;CACZ,IAAI,CAAC,WACJ,OAAO;CAGR,MAAM,iBAAiB,IAAI,KAAK,SAAS;CAGzC,MAAM,eAAA,GAAcA,SAAAA,oBAAAA,CAAoB,gCAAgB,IAFxC,KAE0C,CAAC;CAE3D,OAAO,KAAK,IAAI,aAAa,CAAC;AAC/B"}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { differenceInSeconds } from 'date-fns';\n\nexport const getExpirationInSeconds = (\n\texpiresAt: string | number | Date | undefined | null,\n): number => {\n\tif (!expiresAt) {\n\t\treturn 0;\n\t}\n\n\tconst expirationDate = new Date(expiresAt);\n\tconst now = new Date();\n\n\tconst secondsLeft = differenceInSeconds(expirationDate, now);\n\n\treturn Math.max(secondsLeft, 0);\n};\n\nexport interface Cache {\n\t/**\n\t * Retrieves a value from the cache.\n\t *\n\t * @param key The key to retrieve the value for.\n\t * @returns The cached value, or undefined if not found.\n\t */\n\tget<T>(key: string): Promise<T | undefined>;\n\t/**\n\t * Sets a value in the cache.\n\t *\n\t * @param key The key to set the value for.\n\t * @param value The value to cache.\n\t * @param ttl Optional time-to-live in seconds. If not provided, the value will not expire.\n\t */\n\tset<T>(key: string, value: T, ttl?: number): Promise<void>;\n\t/**\n\t * Deletes a value from the cache.\n\t *\n\t * @param key The key to delete from the cache.\n\t */\n\tdelete(key: string): Promise<void>;\n\n\t/**\n\t * Retrieves the time-to-live (TTL) for a cached value.\n\t *\n\t * @param key The key to retrieve the TTL for.\n\t * @returns The TTL in seconds, or 0 if the key does not exist.\n\t */\n\tttl(key: string): Promise<number>;\n}\n\nexport type { CacheDriver } from './registry';\nexport {\n\tcreateCacheClient,\n\tregisterCacheDriver,\n\tregisteredCacheSchemes,\n\tUnregisteredCacheScheme,\n} from './registry';\n"],"mappings":";;;AAEA,MAAa,0BACZ,cACY;CACZ,IAAI,CAAC,WACJ,OAAO;CAGR,MAAM,iBAAiB,IAAI,KAAK,SAAS;CAGzC,MAAM,cAAc,oBAAoB,gCAAgB,IAFxC,KAE0C,CAAC;CAE3D,OAAO,KAAK,IAAI,aAAa,CAAC;AAC/B"}
|
package/dist/postgres.cjs
DELETED
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
|
|
3
|
-
const require_telemetry = require("./telemetry.cjs");
|
|
4
|
-
let pg = require("pg");
|
|
5
|
-
pg = require_rolldown_runtime.__toESM(pg, 1);
|
|
6
|
-
//#region src/postgres.ts
|
|
7
|
-
/**
|
|
8
|
-
* A cache that lives in a database you already have.
|
|
9
|
-
*
|
|
10
|
-
* The backend with no infrastructure. A cache is a table; the database is the
|
|
11
|
-
* one the application already declared, so an idle stage costs nothing extra
|
|
12
|
-
* and there is one fewer thing to provision, secure and pay for. It is slower
|
|
13
|
-
* than Redis and that is the trade: for session lookups, rate-limit counters and
|
|
14
|
-
* memoised API responses at ordinary volumes, a primary-key hit on a small table
|
|
15
|
-
* is not the thing that will be slow.
|
|
16
|
-
*
|
|
17
|
-
* **The table is provisioned, not created on first use.** That is the one place
|
|
18
|
-
* this differs from pg-boss, and the reason is the role split: a handler
|
|
19
|
-
* connects as a role that may read and write rows and may not create anything,
|
|
20
|
-
* so a driver issuing `CREATE TABLE` would fail on exactly the deployment where
|
|
21
|
-
* the roles are doing their job. The DDL is exported instead — see
|
|
22
|
-
* {@link cacheTableStatements} — and applied by whatever applies the rest.
|
|
23
|
-
*
|
|
24
|
-
* Reads filter on expiry and delete lazily, so an expired row is never returned
|
|
25
|
-
* even if nothing has swept it; a sweep is an optimisation, not a correctness
|
|
26
|
-
* requirement.
|
|
27
|
-
*/
|
|
28
|
-
const DEFAULT_TABLE = "cache";
|
|
29
|
-
var PostgresCache = class {
|
|
30
|
-
pool;
|
|
31
|
-
table;
|
|
32
|
-
constructor(pool, options = {}) {
|
|
33
|
-
this.pool = pool;
|
|
34
|
-
this.table = options.table ?? DEFAULT_TABLE;
|
|
35
|
-
}
|
|
36
|
-
async get(key) {
|
|
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
|
-
});
|
|
42
|
-
}
|
|
43
|
-
async set(key, value, ttl) {
|
|
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
|
-
});
|
|
54
|
-
}
|
|
55
|
-
async delete(key) {
|
|
56
|
-
return require_telemetry.traceCache("postgresql", "delete", async () => {
|
|
57
|
-
await this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
async ttl(key) {
|
|
61
|
-
const { rows } = await this.query(`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds
|
|
62
|
-
FROM ${this.identifier()}
|
|
63
|
-
WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
|
|
64
|
-
const row = rows[0];
|
|
65
|
-
if (!row) return 0;
|
|
66
|
-
return row.seconds ?? 0;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Delete every expired entry.
|
|
70
|
-
*
|
|
71
|
-
* Optional: reads already ignore them. Worth running occasionally so the
|
|
72
|
-
* table does not grow without bound in a workload that writes many keys once.
|
|
73
|
-
*/
|
|
74
|
-
async sweep() {
|
|
75
|
-
const { rowCount } = await this.query(`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`);
|
|
76
|
-
return rowCount ?? 0;
|
|
77
|
-
}
|
|
78
|
-
async query(sql, values = []) {
|
|
79
|
-
const result = await this.pool.query(sql, values);
|
|
80
|
-
return {
|
|
81
|
-
rows: result.rows,
|
|
82
|
-
rowCount: result.rowCount
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* The table name as an identifier.
|
|
87
|
-
*
|
|
88
|
-
* Quoted per segment so a schema-qualified name stays two identifiers rather
|
|
89
|
-
* than becoming one with a dot in it. The name comes from configuration
|
|
90
|
-
* rather than from a request, so this is defence rather than sanitisation.
|
|
91
|
-
*/
|
|
92
|
-
identifier() {
|
|
93
|
-
return quote(this.table);
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
/**
|
|
97
|
-
* The `postgres://` driver.
|
|
98
|
-
*
|
|
99
|
-
* One pool per URL, cached for the life of the process: a cache that opened a
|
|
100
|
-
* connection per call would be slower than the thing it exists to speed up, and
|
|
101
|
-
* a Lambda reusing a warm container should reuse the pool with it.
|
|
102
|
-
*
|
|
103
|
-
* `pg` is imported at the top of this module rather than lazily, because the
|
|
104
|
-
* *module* is the lazy boundary — an app caching in Redis never imports
|
|
105
|
-
* `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
|
|
106
|
-
* arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
|
|
107
|
-
*/
|
|
108
|
-
const postgresCacheDriver = {
|
|
109
|
-
scheme: "postgres:",
|
|
110
|
-
create(url) {
|
|
111
|
-
const { connectionString, table } = split(url);
|
|
112
|
-
const existing = pools.get(connectionString);
|
|
113
|
-
const pool = existing ?? new pg.default.Pool({ connectionString });
|
|
114
|
-
if (!existing) pools.set(connectionString, pool);
|
|
115
|
-
return new PostgresCache(pool, table ? { table } : {});
|
|
116
|
-
}
|
|
117
|
-
};
|
|
118
|
-
/**
|
|
119
|
-
* A cache URL as its two facts: where to connect, and what to read.
|
|
120
|
-
*
|
|
121
|
-
* `table` is removed from the string handed to `pg` rather than left on it,
|
|
122
|
-
* because a Postgres connection string carries libpq parameters and an unknown
|
|
123
|
-
* one is not guaranteed to be ignored — and because the pool should be shared
|
|
124
|
-
* by every cache in the database, which only works if the key does not vary
|
|
125
|
-
* per cache.
|
|
126
|
-
*/
|
|
127
|
-
function split(url) {
|
|
128
|
-
try {
|
|
129
|
-
const parsed = new URL(url);
|
|
130
|
-
const table = parsed.searchParams.get("table") ?? void 0;
|
|
131
|
-
if (!table) return { connectionString: url };
|
|
132
|
-
parsed.searchParams.delete("table");
|
|
133
|
-
return {
|
|
134
|
-
connectionString: parsed.toString(),
|
|
135
|
-
table
|
|
136
|
-
};
|
|
137
|
-
} catch {
|
|
138
|
-
return { connectionString: url };
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
const pools = /* @__PURE__ */ new Map();
|
|
142
|
-
/**
|
|
143
|
-
* The DDL a Postgres-backed cache needs, for whoever applies DDL.
|
|
144
|
-
*
|
|
145
|
-
* Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
|
|
146
|
-
* statements run in-process from `gkm dev` and from a provisioner inside a VPC,
|
|
147
|
-
* and one implementation is what stops "works locally, fails deployed".
|
|
148
|
-
*
|
|
149
|
-
* Run as the schema's **owner**. The role a handler connects as cannot create a
|
|
150
|
-
* table, which is the point of the split and the reason this is not done lazily.
|
|
151
|
-
*/
|
|
152
|
-
function cacheTableStatements(options = {}) {
|
|
153
|
-
const table = options.table ?? DEFAULT_TABLE;
|
|
154
|
-
const [schema, name] = table.includes(".") ? table.split(".") : [void 0, table];
|
|
155
|
-
const qualified = quote(table);
|
|
156
|
-
return [{
|
|
157
|
-
describe: `cache table ${table}`,
|
|
158
|
-
exists: {
|
|
159
|
-
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",
|
|
160
|
-
values: schema ? [schema, name] : [name]
|
|
161
|
-
},
|
|
162
|
-
sql: `CREATE TABLE ${qualified} (
|
|
163
|
-
key text PRIMARY KEY,
|
|
164
|
-
value jsonb NOT NULL,
|
|
165
|
-
expires_at timestamptz
|
|
166
|
-
)`
|
|
167
|
-
}, {
|
|
168
|
-
describe: `cache expiry index on ${table}`,
|
|
169
|
-
sql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}
|
|
170
|
-
ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`
|
|
171
|
-
}];
|
|
172
|
-
}
|
|
173
|
-
/** A possibly schema-qualified name, quoted per segment. */
|
|
174
|
-
function quote(table) {
|
|
175
|
-
return table.split(".").map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(".");
|
|
176
|
-
}
|
|
177
|
-
function indexName(table) {
|
|
178
|
-
return `"${table.replace(/[^a-zA-Z0-9]/g, "_")}_expires_at_idx"`;
|
|
179
|
-
}
|
|
180
|
-
//#endregion
|
|
181
|
-
exports.PostgresCache = PostgresCache;
|
|
182
|
-
exports.cacheTableStatements = cacheTableStatements;
|
|
183
|
-
exports.postgresCacheDriver = postgresCacheDriver;
|
|
184
|
-
|
|
185
|
-
//# sourceMappingURL=postgres.cjs.map
|
package/dist/postgres.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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":"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"}
|
package/dist/postgres.d.cts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { r as CacheDriver, t as Cache } from "./index-BbdGhmWP.cjs";
|
|
2
|
-
import { Pool } from "pg";
|
|
3
|
-
//#region src/postgres.d.ts
|
|
4
|
-
export interface PostgresCacheOptions {
|
|
5
|
-
/**
|
|
6
|
-
* The table to keep entries in, schema-qualified if it needs to be.
|
|
7
|
-
*
|
|
8
|
-
* Defaults to `cache`. It resolves against the connection's `search_path`,
|
|
9
|
-
* which the role carries — so a tenant's cache lands in the tenant's schema
|
|
10
|
-
* without anything here knowing the schema's name.
|
|
11
|
-
*/
|
|
12
|
-
table?: string;
|
|
13
|
-
}
|
|
14
|
-
export declare class PostgresCache implements Cache {
|
|
15
|
-
private readonly pool;
|
|
16
|
-
private readonly table;
|
|
17
|
-
constructor(pool: Pool, options?: PostgresCacheOptions);
|
|
18
|
-
get<T>(key: string): Promise<T | undefined>;
|
|
19
|
-
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
20
|
-
delete(key: string): Promise<void>;
|
|
21
|
-
ttl(key: string): Promise<number>;
|
|
22
|
-
/**
|
|
23
|
-
* Delete every expired entry.
|
|
24
|
-
*
|
|
25
|
-
* Optional: reads already ignore them. Worth running occasionally so the
|
|
26
|
-
* table does not grow without bound in a workload that writes many keys once.
|
|
27
|
-
*/
|
|
28
|
-
sweep(): Promise<number>;
|
|
29
|
-
private query;
|
|
30
|
-
/**
|
|
31
|
-
* The table name as an identifier.
|
|
32
|
-
*
|
|
33
|
-
* Quoted per segment so a schema-qualified name stays two identifiers rather
|
|
34
|
-
* than becoming one with a dot in it. The name comes from configuration
|
|
35
|
-
* rather than from a request, so this is defence rather than sanitisation.
|
|
36
|
-
*/
|
|
37
|
-
private identifier;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* The `postgres://` driver.
|
|
41
|
-
*
|
|
42
|
-
* One pool per URL, cached for the life of the process: a cache that opened a
|
|
43
|
-
* connection per call would be slower than the thing it exists to speed up, and
|
|
44
|
-
* a Lambda reusing a warm container should reuse the pool with it.
|
|
45
|
-
*
|
|
46
|
-
* `pg` is imported at the top of this module rather than lazily, because the
|
|
47
|
-
* *module* is the lazy boundary — an app caching in Redis never imports
|
|
48
|
-
* `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
|
|
49
|
-
* arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
|
|
50
|
-
*/
|
|
51
|
-
export declare const postgresCacheDriver: CacheDriver;
|
|
52
|
-
/**
|
|
53
|
-
* The DDL a Postgres-backed cache needs, for whoever applies DDL.
|
|
54
|
-
*
|
|
55
|
-
* Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
|
|
56
|
-
* statements run in-process from `gkm dev` and from a provisioner inside a VPC,
|
|
57
|
-
* and one implementation is what stops "works locally, fails deployed".
|
|
58
|
-
*
|
|
59
|
-
* Run as the schema's **owner**. The role a handler connects as cannot create a
|
|
60
|
-
* table, which is the point of the split and the reason this is not done lazily.
|
|
61
|
-
*/
|
|
62
|
-
export declare function cacheTableStatements(options?: PostgresCacheOptions): {
|
|
63
|
-
describe: string;
|
|
64
|
-
exists?: {
|
|
65
|
-
sql: string;
|
|
66
|
-
values: unknown[];
|
|
67
|
-
};
|
|
68
|
-
sql: string;
|
|
69
|
-
}[];
|
|
70
|
-
//#endregion
|
|
71
|
-
//# sourceMappingURL=postgres.d.cts.map
|
package/dist/postgres.d.cts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { r as CacheDriver, t as Cache } from "./index-BbdGhmWP.mjs";
|
|
2
|
-
import { Pool } from "pg";
|
|
3
|
-
//#region src/postgres.d.ts
|
|
4
|
-
export interface PostgresCacheOptions {
|
|
5
|
-
/**
|
|
6
|
-
* The table to keep entries in, schema-qualified if it needs to be.
|
|
7
|
-
*
|
|
8
|
-
* Defaults to `cache`. It resolves against the connection's `search_path`,
|
|
9
|
-
* which the role carries — so a tenant's cache lands in the tenant's schema
|
|
10
|
-
* without anything here knowing the schema's name.
|
|
11
|
-
*/
|
|
12
|
-
table?: string;
|
|
13
|
-
}
|
|
14
|
-
export declare class PostgresCache implements Cache {
|
|
15
|
-
private readonly pool;
|
|
16
|
-
private readonly table;
|
|
17
|
-
constructor(pool: Pool, options?: PostgresCacheOptions);
|
|
18
|
-
get<T>(key: string): Promise<T | undefined>;
|
|
19
|
-
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
20
|
-
delete(key: string): Promise<void>;
|
|
21
|
-
ttl(key: string): Promise<number>;
|
|
22
|
-
/**
|
|
23
|
-
* Delete every expired entry.
|
|
24
|
-
*
|
|
25
|
-
* Optional: reads already ignore them. Worth running occasionally so the
|
|
26
|
-
* table does not grow without bound in a workload that writes many keys once.
|
|
27
|
-
*/
|
|
28
|
-
sweep(): Promise<number>;
|
|
29
|
-
private query;
|
|
30
|
-
/**
|
|
31
|
-
* The table name as an identifier.
|
|
32
|
-
*
|
|
33
|
-
* Quoted per segment so a schema-qualified name stays two identifiers rather
|
|
34
|
-
* than becoming one with a dot in it. The name comes from configuration
|
|
35
|
-
* rather than from a request, so this is defence rather than sanitisation.
|
|
36
|
-
*/
|
|
37
|
-
private identifier;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* The `postgres://` driver.
|
|
41
|
-
*
|
|
42
|
-
* One pool per URL, cached for the life of the process: a cache that opened a
|
|
43
|
-
* connection per call would be slower than the thing it exists to speed up, and
|
|
44
|
-
* a Lambda reusing a warm container should reuse the pool with it.
|
|
45
|
-
*
|
|
46
|
-
* `pg` is imported at the top of this module rather than lazily, because the
|
|
47
|
-
* *module* is the lazy boundary — an app caching in Redis never imports
|
|
48
|
-
* `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
|
|
49
|
-
* arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
|
|
50
|
-
*/
|
|
51
|
-
export declare const postgresCacheDriver: CacheDriver;
|
|
52
|
-
/**
|
|
53
|
-
* The DDL a Postgres-backed cache needs, for whoever applies DDL.
|
|
54
|
-
*
|
|
55
|
-
* Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
|
|
56
|
-
* statements run in-process from `gkm dev` and from a provisioner inside a VPC,
|
|
57
|
-
* and one implementation is what stops "works locally, fails deployed".
|
|
58
|
-
*
|
|
59
|
-
* Run as the schema's **owner**. The role a handler connects as cannot create a
|
|
60
|
-
* table, which is the point of the split and the reason this is not done lazily.
|
|
61
|
-
*/
|
|
62
|
-
export declare function cacheTableStatements(options?: PostgresCacheOptions): {
|
|
63
|
-
describe: string;
|
|
64
|
-
exists?: {
|
|
65
|
-
sql: string;
|
|
66
|
-
values: unknown[];
|
|
67
|
-
};
|
|
68
|
-
sql: string;
|
|
69
|
-
}[];
|
|
70
|
-
//#endregion
|
|
71
|
-
//# sourceMappingURL=postgres.d.mts.map
|
package/dist/postgres.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|