@fedify/postgres 0.3.0-dev.22 → 0.4.0-dev.30

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/mod.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/mod.ts";
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@fedify/postgres",
3
- "version": "0.3.0-dev.22+7bce50b9",
3
+ "version": "0.4.0-dev.30",
4
4
  "description": "PostgreSQL drivers for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
7
7
  "postgresql",
8
8
  "postgres"
9
9
  ],
10
+ "license": "MIT",
10
11
  "author": {
11
12
  "name": "Hong Minhee",
12
13
  "email": "hong@minhee.org",
@@ -17,58 +18,46 @@
17
18
  "type": "git",
18
19
  "url": "git+https://github.com/fedify-dev/postgres.git"
19
20
  },
20
- "license": "MIT",
21
21
  "bugs": {
22
22
  "url": "https://github.com/fedify-dev/postgres/issues"
23
23
  },
24
- "main": "./script/mod.js",
25
- "module": "./esm/mod.js",
26
- "types": "./types/mod.d.ts",
24
+ "funding": [
25
+ "https://opencollective.com/fedify",
26
+ "https://github.com/sponsors/dahlia"
27
+ ],
28
+ "type": "module",
27
29
  "exports": {
28
- ".": {
29
- "import": {
30
- "types": "./types/mod.d.ts",
31
- "default": "./esm/mod.js"
32
- },
33
- "require": {
34
- "types": "./types/mod.d.ts",
35
- "default": "./script/mod.js"
36
- }
30
+ "./mod": {
31
+ "types": "./dist/mod.d.ts",
32
+ "import": "./dist/mod.js"
37
33
  },
38
34
  "./kv": {
39
- "import": {
40
- "types": "./types/src/kv.d.ts",
41
- "default": "./esm/src/kv.js"
42
- },
43
- "require": {
44
- "types": "./types/src/kv.d.ts",
45
- "default": "./script/src/kv.js"
46
- }
35
+ "types": "./dist/src/kv.d.ts",
36
+ "import": "./dist/src/kv.js"
47
37
  },
48
38
  "./mq": {
49
- "import": {
50
- "types": "./types/src/mq.d.ts",
51
- "default": "./esm/src/mq.js"
52
- },
53
- "require": {
54
- "types": "./types/src/mq.d.ts",
55
- "default": "./script/src/mq.js"
56
- }
57
- }
39
+ "types": "./dist/src/mq.d.ts",
40
+ "import": "./dist/src/mq.js"
41
+ },
42
+ "./package.json": "./package.json"
58
43
  },
59
- "funding": [
60
- "https://opencollective.com/fedify",
61
- "https://github.com/sponsors/dahlia"
62
- ],
63
44
  "dependencies": {
64
- "@fedify/fedify": "1.5.0-dev.750",
65
- "@logtape/logtape": "^0.9.0",
66
- "postgres": "^3.4.5",
67
- "@deno/shim-deno": "~0.18.0",
68
- "@js-temporal/polyfill": "^0.5.0"
45
+ "@js-temporal/polyfill": "^0.5.1",
46
+ "@logtape/logtape": "^1.0.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@fedify/fedify": "^1.7.2",
50
+ "postgres": "^3.4.7"
69
51
  },
70
52
  "devDependencies": {
71
- "@types/node": "^20.9.0"
53
+ "@std/async": "npm:@jsr/std__async@^1.0.5",
54
+ "tsdown": "^0.12.9",
55
+ "typescript": "^5.8.3"
72
56
  },
73
- "_generatedBy": "dnt@dev"
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "prepublish": "tsdown",
60
+ "test": "tsdown && node --experimental-transform-types --test",
61
+ "test:bun": "tsdown && bun test --timeout=10000"
62
+ }
74
63
  }
package/src/kv.test.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { PostgresKvStore } from "@fedify/postgres/kv";
2
+ import * as temporal from "@js-temporal/polyfill";
3
+ import { delay } from "@std/async/delay";
4
+ import assert from "node:assert/strict";
5
+ import process from "node:process";
6
+ import { test } from "node:test";
7
+ import postgres from "postgres";
8
+
9
+ let Temporal: typeof temporal.Temporal;
10
+ if ("Temporal" in globalThis) {
11
+ Temporal = globalThis.Temporal;
12
+ } else {
13
+ Temporal = temporal.Temporal;
14
+ }
15
+
16
+ const dbUrl = process.env.DATABASE_URL;
17
+
18
+ function getStore(): {
19
+ // deno-lint-ignore no-explicit-any
20
+ sql: postgres.Sql<any>;
21
+ tableName: string;
22
+ store: PostgresKvStore;
23
+ } {
24
+ const sql = postgres(dbUrl!);
25
+ const tableName = `fedify_kv_test_${Math.random().toString(36).slice(5)}`;
26
+ return {
27
+ sql,
28
+ tableName,
29
+ store: new PostgresKvStore(sql, { tableName }),
30
+ };
31
+ }
32
+
33
+ test("PostgresKvStore.initialize()", { skip: dbUrl == null }, async () => {
34
+ const { sql, tableName, store } = getStore();
35
+ try {
36
+ await store.initialize();
37
+ const result = await sql`
38
+ SELECT to_regclass(${tableName}) IS NOT NULL AS exists;
39
+ `;
40
+ assert(result[0].exists);
41
+ } finally {
42
+ await store.drop();
43
+ await sql.end();
44
+ }
45
+ });
46
+
47
+ test("PostgresKvStore.get()", { skip: dbUrl == null }, async () => {
48
+ const { sql, tableName, store } = getStore();
49
+ try {
50
+ await store.initialize();
51
+ await sql`
52
+ INSERT INTO ${sql(tableName)} (key, value)
53
+ VALUES (${["foo", "bar"]}, ${["foobar"]})
54
+ `;
55
+ assert.deepStrictEqual(await store.get(["foo", "bar"]), ["foobar"]);
56
+
57
+ await sql`
58
+ INSERT INTO ${sql(tableName)} (key, value, ttl)
59
+ VALUES (${["foo", "bar", "ttl"]}, ${["foobar"]}, ${"0 seconds"})
60
+ `;
61
+ await delay(500);
62
+ assert.strictEqual(await store.get(["foo", "bar", "ttl"]), undefined);
63
+ } finally {
64
+ await store.drop();
65
+ await sql.end();
66
+ }
67
+ });
68
+
69
+ test("PostgresKvStore.set()", { skip: dbUrl == null }, async () => {
70
+ const { sql, tableName, store } = getStore();
71
+ try {
72
+ await store.set(["foo", "baz"], "baz");
73
+ const result = await sql`
74
+ SELECT * FROM ${sql(tableName)}
75
+ WHERE key = ${["foo", "baz"]}
76
+ `;
77
+ assert.strictEqual(result.length, 1);
78
+ assert.deepStrictEqual(result[0].key, ["foo", "baz"]);
79
+ assert.strictEqual(result[0].value, "baz");
80
+ assert.strictEqual(result[0].ttl, null);
81
+
82
+ await store.set(["foo", "qux"], "qux", {
83
+ ttl: Temporal.Duration.from({ days: 1 }),
84
+ });
85
+ const result2 = await sql`
86
+ SELECT * FROM ${sql(tableName)}
87
+ WHERE key = ${["foo", "qux"]}
88
+ `;
89
+ assert.strictEqual(result2.length, 1);
90
+ assert.deepStrictEqual(result2[0].key, ["foo", "qux"]);
91
+ assert.strictEqual(result2[0].value, "qux");
92
+ assert.strictEqual(result2[0].ttl, "1 day");
93
+
94
+ await store.set(["foo", "quux"], true);
95
+ const result3 = await sql`
96
+ SELECT * FROM ${sql(tableName)}
97
+ WHERE key = ${["foo", "quux"]}
98
+ `;
99
+ assert.strictEqual(result3.length, 1);
100
+ assert.deepStrictEqual(result3[0].key, ["foo", "quux"]);
101
+ assert.strictEqual(result3[0].value, true);
102
+ assert.strictEqual(result3[0].ttl, null);
103
+ } finally {
104
+ await store.drop();
105
+ await sql.end();
106
+ }
107
+ });
108
+
109
+ test("PostgresKvStore.delete()", { skip: dbUrl == null }, async () => {
110
+ const { sql, tableName, store } = getStore();
111
+ try {
112
+ await store.delete(["foo", "bar"]);
113
+ const result = await sql`
114
+ SELECT * FROM ${sql(tableName)}
115
+ WHERE key = ${["foo", "bar"]}
116
+ `;
117
+ assert.strictEqual(result.length, 0);
118
+ } finally {
119
+ await store.drop();
120
+ await sql.end();
121
+ }
122
+ });
123
+
124
+ test("PostgresKvStore.drop()", { skip: dbUrl == null }, async () => {
125
+ const { sql, tableName, store } = getStore();
126
+ try {
127
+ await store.drop();
128
+ const result2 = await sql`
129
+ SELECT to_regclass(${tableName}) IS NOT NULL AS exists;
130
+ `;
131
+ assert.ok(!result2[0].exists);
132
+ } finally {
133
+ await sql.end();
134
+ }
135
+ });
136
+
137
+ // cSpell: ignore regclass
package/src/kv.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { KvKey, KvStore, KvStoreSetOptions } from "@fedify/fedify";
2
+ import { getLogger } from "@logtape/logtape";
3
+ import type { JSONValue, Parameter, Sql } from "postgres";
4
+ import { driverSerializesJson } from "./utils.ts";
5
+
6
+ const logger = getLogger(["fedify", "postgres", "kv"]);
7
+
8
+ /**
9
+ * Options for the PostgreSQL key-value store.
10
+ */
11
+ export interface PostgresKvStoreOptions {
12
+ /**
13
+ * The table name to use for the key-value store.
14
+ * `"fedify_kv_v2"` by default.
15
+ * @default `"fedify_kv_v2"`
16
+ */
17
+ tableName?: string;
18
+
19
+ /**
20
+ * Whether the table has been initialized. `false` by default.
21
+ * @default `false`
22
+ */
23
+ initialized?: boolean;
24
+ }
25
+
26
+ /**
27
+ * A key-value store that uses PostgreSQL as the underlying storage.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { createFederation } from "@fedify/fedify";
32
+ * import { PostgresKvStore } from "@fedify/postgres";
33
+ * import postgres from "postgres";
34
+ *
35
+ * const federation = createFederation({
36
+ * // ...
37
+ * kv: new PostgresKvStore(postgres("postgres://user:pass@localhost/db")),
38
+ * });
39
+ * ```
40
+ */
41
+ export class PostgresKvStore implements KvStore {
42
+ // deno-lint-ignore ban-types
43
+ readonly #sql: Sql<{}>;
44
+ readonly #tableName: string;
45
+ #initialized: boolean;
46
+ #driverSerializesJson = false;
47
+
48
+ /**
49
+ * Creates a new PostgreSQL key-value store.
50
+ * @param sql The PostgreSQL client to use.
51
+ * @param options The options for the key-value store.
52
+ */
53
+ constructor(
54
+ // deno-lint-ignore ban-types
55
+ sql: Sql<{}>,
56
+ options: PostgresKvStoreOptions = {},
57
+ ) {
58
+ this.#sql = sql;
59
+ this.#tableName = options.tableName ?? "fedify_kv_v2";
60
+ this.#initialized = options.initialized ?? false;
61
+ }
62
+
63
+ async #expire(): Promise<void> {
64
+ await this.#sql`
65
+ DELETE FROM ${this.#sql(this.#tableName)}
66
+ WHERE ttl IS NOT NULL AND created + ttl < CURRENT_TIMESTAMP;
67
+ `;
68
+ }
69
+
70
+ async get<T = unknown>(key: KvKey): Promise<T | undefined> {
71
+ await this.initialize();
72
+ const result = await this.#sql`
73
+ SELECT value
74
+ FROM ${this.#sql(this.#tableName)}
75
+ WHERE key = ${key} AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);
76
+ `;
77
+ if (result.length < 1) return undefined;
78
+ return result[0].value as T;
79
+ }
80
+
81
+ async set(
82
+ key: KvKey,
83
+ value: unknown,
84
+ options?: KvStoreSetOptions | undefined,
85
+ ): Promise<void> {
86
+ await this.initialize();
87
+ const ttl = options?.ttl == null ? null : options.ttl.toString();
88
+ await this.#sql`
89
+ INSERT INTO ${this.#sql(this.#tableName)} (key, value, ttl)
90
+ VALUES (
91
+ ${key},
92
+ ${this.#json(value)},
93
+ ${ttl}
94
+ )
95
+ ON CONFLICT (key)
96
+ DO UPDATE SET value = EXCLUDED.value, ttl = EXCLUDED.ttl;
97
+ `;
98
+ await this.#expire();
99
+ }
100
+
101
+ async delete(key: KvKey): Promise<void> {
102
+ await this.initialize();
103
+ await this.#sql`
104
+ DELETE FROM ${this.#sql(this.#tableName)}
105
+ WHERE key = ${key};
106
+ `;
107
+ await this.#expire();
108
+ }
109
+
110
+ /**
111
+ * Creates the table used by the key-value store if it does not already exist.
112
+ * Does nothing if the table already exists.
113
+ */
114
+ async initialize(): Promise<void> {
115
+ if (this.#initialized) return;
116
+ logger.debug("Initializing the key-value store table {tableName}...", {
117
+ tableName: this.#tableName,
118
+ });
119
+ await this.#sql`
120
+ CREATE UNLOGGED TABLE IF NOT EXISTS ${this.#sql(this.#tableName)} (
121
+ key text[] PRIMARY KEY,
122
+ value jsonb NOT NULL,
123
+ created timestamp with time zone DEFAULT CURRENT_TIMESTAMP,
124
+ ttl interval
125
+ );
126
+ `;
127
+ this.#driverSerializesJson = await driverSerializesJson(this.#sql);
128
+ this.#initialized = true;
129
+ logger.debug("Initialized the key-value store table {tableName}.", {
130
+ tableName: this.#tableName,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Drops the table used by the key-value store. Does nothing if the table
136
+ * does not exist.
137
+ */
138
+ async drop(): Promise<void> {
139
+ await this.#sql`DROP TABLE IF EXISTS ${this.#sql(this.#tableName)};`;
140
+ }
141
+
142
+ #json(value: unknown): Parameter {
143
+ if (this.#driverSerializesJson) return this.#sql.json(value as JSONValue);
144
+ return this.#sql.json(JSON.stringify(value));
145
+ }
146
+ }
package/src/mod.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./kv.ts";
2
+ export * from "./mq.ts";
package/src/mq.test.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { PostgresMessageQueue } from "@fedify/postgres/mq";
2
+ import * as temporal from "@js-temporal/polyfill";
3
+ import { delay } from "@std/async/delay";
4
+ import process from "node:process";
5
+ import assert from "node:assert/strict";
6
+ import { test } from "node:test";
7
+ import postgres from "postgres";
8
+
9
+ let Temporal: typeof temporal.Temporal;
10
+ if ("Temporal" in globalThis) {
11
+ Temporal = globalThis.Temporal;
12
+ } else {
13
+ Temporal = temporal.Temporal;
14
+ }
15
+
16
+ const dbUrl = process.env.DATABASE_URL;
17
+
18
+ test("PostgresMessageQueue", { skip: dbUrl == null }, async () => {
19
+ const sql = postgres(dbUrl!);
20
+ const sql2 = postgres(dbUrl!);
21
+ const tableName = `fedify_message_test_${
22
+ Math.random().toString(36).slice(5)
23
+ }`;
24
+ const channelName = `fedify_channel_test_${
25
+ Math.random().toString(36).slice(5)
26
+ }`;
27
+ const mq = new PostgresMessageQueue(sql, { tableName, channelName });
28
+ const mq2 = new PostgresMessageQueue(sql2, { tableName, channelName });
29
+
30
+ try {
31
+ const messages: string[] = [];
32
+ const controller = new AbortController();
33
+ const listening = mq.listen((message: string) => {
34
+ messages.push(message);
35
+ }, { signal: controller.signal });
36
+ const listening2 = mq2.listen((message: string) => {
37
+ messages.push(message);
38
+ }, { signal: controller.signal });
39
+
40
+ // enqueue()
41
+ await mq.enqueue("Hello, world!");
42
+
43
+ await waitFor(() => messages.length > 0, 15_000);
44
+
45
+ // listen()
46
+ assert.deepStrictEqual(messages, ["Hello, world!"]);
47
+
48
+ // enqueue() with delay
49
+ let started = 0;
50
+ started = Date.now();
51
+ await mq.enqueue(
52
+ { msg: "Delayed message" },
53
+ { delay: Temporal.Duration.from({ seconds: 3 }) },
54
+ );
55
+
56
+ await waitFor(() => messages.length > 1, 15_000);
57
+
58
+ // listen() with delay
59
+ assert.deepStrictEqual(messages, ["Hello, world!", {
60
+ msg: "Delayed message",
61
+ }]);
62
+ assert.ok(Date.now() - started > 3_000);
63
+
64
+ // enqueueMany()
65
+ while (messages.length > 0) messages.pop();
66
+ const batchMessages = [
67
+ "First batch message",
68
+ { text: "Second batch message" },
69
+ { text: "Third batch message", priority: "high" },
70
+ ];
71
+ await mq.enqueueMany(batchMessages);
72
+ await waitFor(() => messages.length === batchMessages.length, 15_000);
73
+ assert.deepStrictEqual(messages, batchMessages);
74
+
75
+ // enqueueMany() with delay
76
+ while (messages.length > 0) messages.pop();
77
+ started = Date.now();
78
+ const delayedBatchMessages = [
79
+ "Delayed batch 1",
80
+ "Delayed batch 2",
81
+ ];
82
+ await mq.enqueueMany(
83
+ delayedBatchMessages,
84
+ { delay: Temporal.Duration.from({ seconds: 2 }) },
85
+ );
86
+ await waitFor(
87
+ () => messages.length === delayedBatchMessages.length,
88
+ 15_000,
89
+ );
90
+ assert.deepStrictEqual(messages, delayedBatchMessages);
91
+ assert.ok(Date.now() - started > 2_000);
92
+
93
+ controller.abort();
94
+ await listening;
95
+ await listening2;
96
+ } finally {
97
+ await mq.drop();
98
+ await sql.end();
99
+ await sql2.end();
100
+ }
101
+ });
102
+
103
+ async function waitFor(
104
+ predicate: () => boolean,
105
+ timeoutMs: number,
106
+ ): Promise<void> {
107
+ const started = Date.now();
108
+ while (!predicate()) {
109
+ await delay(500);
110
+ if (Date.now() - started > timeoutMs) {
111
+ throw new Error("Timeout");
112
+ }
113
+ }
114
+ }