@fedify/postgres 2.0.0-pr.433.1601 → 2.0.0-pr.434.1659

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.
@@ -0,0 +1,33 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ //#region rolldown:runtime
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
+ key = keys[i];
14
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
22
+ value: mod,
23
+ enumerable: true
24
+ }) : target, mod));
25
+
26
+ //#endregion
27
+
28
+ Object.defineProperty(exports, '__toESM', {
29
+ enumerable: true,
30
+ get: function () {
31
+ return __toESM;
32
+ }
33
+ });
package/dist/kv.cjs ADDED
@@ -0,0 +1,116 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
5
+ const require_utils = require('./utils.cjs');
6
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
7
+
8
+ //#region src/kv.ts
9
+ const logger = (0, __logtape_logtape.getLogger)([
10
+ "fedify",
11
+ "postgres",
12
+ "kv"
13
+ ]);
14
+ /**
15
+ * A key–value store that uses PostgreSQL as the underlying storage.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { createFederation } from "@fedify/fedify";
20
+ * import { PostgresKvStore } from "@fedify/postgres";
21
+ * import postgres from "postgres";
22
+ *
23
+ * const federation = createFederation({
24
+ * // ...
25
+ * kv: new PostgresKvStore(postgres("postgres://user:pass@localhost/db")),
26
+ * });
27
+ * ```
28
+ */
29
+ var PostgresKvStore = class {
30
+ #sql;
31
+ #tableName;
32
+ #initialized;
33
+ #driverSerializesJson = false;
34
+ /**
35
+ * Creates a new PostgreSQL key–value store.
36
+ * @param sql The PostgreSQL client to use.
37
+ * @param options The options for the key–value store.
38
+ */
39
+ constructor(sql, options = {}) {
40
+ this.#sql = sql;
41
+ this.#tableName = options.tableName ?? "fedify_kv_v2";
42
+ this.#initialized = options.initialized ?? false;
43
+ }
44
+ async #expire() {
45
+ await this.#sql`
46
+ DELETE FROM ${this.#sql(this.#tableName)}
47
+ WHERE ttl IS NOT NULL AND created + ttl < CURRENT_TIMESTAMP;
48
+ `;
49
+ }
50
+ async get(key) {
51
+ await this.initialize();
52
+ const result = await this.#sql`
53
+ SELECT value
54
+ FROM ${this.#sql(this.#tableName)}
55
+ WHERE key = ${key} AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);
56
+ `;
57
+ if (result.length < 1) return void 0;
58
+ return result[0].value;
59
+ }
60
+ async set(key, value, options) {
61
+ await this.initialize();
62
+ const ttl = options?.ttl == null ? null : options.ttl.toString();
63
+ await this.#sql`
64
+ INSERT INTO ${this.#sql(this.#tableName)} (key, value, ttl)
65
+ VALUES (
66
+ ${key},
67
+ ${this.#json(value)},
68
+ ${ttl}
69
+ )
70
+ ON CONFLICT (key)
71
+ DO UPDATE SET value = EXCLUDED.value, ttl = EXCLUDED.ttl;
72
+ `;
73
+ await this.#expire();
74
+ }
75
+ async delete(key) {
76
+ await this.initialize();
77
+ await this.#sql`
78
+ DELETE FROM ${this.#sql(this.#tableName)}
79
+ WHERE key = ${key};
80
+ `;
81
+ await this.#expire();
82
+ }
83
+ /**
84
+ * Creates the table used by the key–value store if it does not already exist.
85
+ * Does nothing if the table already exists.
86
+ */
87
+ async initialize() {
88
+ if (this.#initialized) return;
89
+ logger.debug("Initializing the key–value store table {tableName}...", { tableName: this.#tableName });
90
+ await this.#sql`
91
+ CREATE UNLOGGED TABLE IF NOT EXISTS ${this.#sql(this.#tableName)} (
92
+ key text[] PRIMARY KEY,
93
+ value jsonb NOT NULL,
94
+ created timestamp with time zone DEFAULT CURRENT_TIMESTAMP,
95
+ ttl interval
96
+ );
97
+ `;
98
+ this.#driverSerializesJson = await require_utils.driverSerializesJson(this.#sql);
99
+ this.#initialized = true;
100
+ logger.debug("Initialized the key–value store table {tableName}.", { tableName: this.#tableName });
101
+ }
102
+ /**
103
+ * Drops the table used by the key–value store. Does nothing if the table
104
+ * does not exist.
105
+ */
106
+ async drop() {
107
+ await this.#sql`DROP TABLE IF EXISTS ${this.#sql(this.#tableName)};`;
108
+ }
109
+ #json(value) {
110
+ if (this.#driverSerializesJson) return this.#sql.json(value);
111
+ return this.#sql.json(JSON.stringify(value));
112
+ }
113
+ };
114
+
115
+ //#endregion
116
+ exports.PostgresKvStore = PostgresKvStore;
package/dist/kv.d.cts ADDED
@@ -0,0 +1,59 @@
1
+ import { KvKey, KvStore, KvStoreSetOptions } from "@fedify/fedify";
2
+ import { Sql } from "postgres";
3
+
4
+ //#region src/kv.d.ts
5
+ /**
6
+ * Options for the PostgreSQL key–value store.
7
+ */
8
+ interface PostgresKvStoreOptions {
9
+ /**
10
+ * The table name to use for the key–value store.
11
+ * `"fedify_kv_v2"` by default.
12
+ * @default `"fedify_kv_v2"`
13
+ */
14
+ tableName?: string;
15
+ /**
16
+ * Whether the table has been initialized. `false` by default.
17
+ * @default `false`
18
+ */
19
+ initialized?: boolean;
20
+ }
21
+ /**
22
+ * A key–value store that uses PostgreSQL as the underlying storage.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { createFederation } from "@fedify/fedify";
27
+ * import { PostgresKvStore } from "@fedify/postgres";
28
+ * import postgres from "postgres";
29
+ *
30
+ * const federation = createFederation({
31
+ * // ...
32
+ * kv: new PostgresKvStore(postgres("postgres://user:pass@localhost/db")),
33
+ * });
34
+ * ```
35
+ */
36
+ declare class PostgresKvStore implements KvStore {
37
+ #private;
38
+ /**
39
+ * Creates a new PostgreSQL key–value store.
40
+ * @param sql The PostgreSQL client to use.
41
+ * @param options The options for the key–value store.
42
+ */
43
+ constructor(sql: Sql<{}>, options?: PostgresKvStoreOptions);
44
+ get<T = unknown>(key: KvKey): Promise<T | undefined>;
45
+ set(key: KvKey, value: unknown, options?: KvStoreSetOptions | undefined): Promise<void>;
46
+ delete(key: KvKey): Promise<void>;
47
+ /**
48
+ * Creates the table used by the key–value store if it does not already exist.
49
+ * Does nothing if the table already exists.
50
+ */
51
+ initialize(): Promise<void>;
52
+ /**
53
+ * Drops the table used by the key–value store. Does nothing if the table
54
+ * does not exist.
55
+ */
56
+ drop(): Promise<void>;
57
+ }
58
+ //#endregion
59
+ export { PostgresKvStore, PostgresKvStoreOptions };
package/dist/kv.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  import { driverSerializesJson } from "./utils.js";
5
5
  import { getLogger } from "@logtape/logtape";
6
6
 
package/dist/mod.cjs ADDED
@@ -0,0 +1,8 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ const require_kv = require('./kv.cjs');
5
+ const require_mq = require('./mq.cjs');
6
+
7
+ exports.PostgresKvStore = require_kv.PostgresKvStore;
8
+ exports.PostgresMessageQueue = require_mq.PostgresMessageQueue;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,3 @@
1
+ import { PostgresKvStore, PostgresKvStoreOptions } from "./kv.cjs";
2
+ import { PostgresMessageQueue, PostgresMessageQueueOptions } from "./mq.cjs";
3
+ export { PostgresKvStore, PostgresKvStoreOptions, PostgresMessageQueue, PostgresMessageQueueOptions };
package/dist/mod.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  import { PostgresKvStore } from "./kv.js";
5
5
  import { PostgresMessageQueue } from "./mq.js";
6
6
 
package/dist/mq.cjs ADDED
@@ -0,0 +1,186 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
5
+ const require_utils = require('./utils.cjs');
6
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
7
+ const postgres = require_rolldown_runtime.__toESM(require("postgres"));
8
+
9
+ //#region src/mq.ts
10
+ const logger = (0, __logtape_logtape.getLogger)([
11
+ "fedify",
12
+ "postgres",
13
+ "mq"
14
+ ]);
15
+ /**
16
+ * A message queue that uses PostgreSQL as the underlying storage.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { createFederation } from "@fedify/fedify";
21
+ * import { PostgresKvStore, PostgresMessageQueue } from "@fedify/postgres";
22
+ * import postgres from "postgres";
23
+ *
24
+ * const sql = postgres("postgres://user:pass@localhost/db");
25
+ *
26
+ * const federation = createFederation({
27
+ * kv: new PostgresKvStore(sql),
28
+ * queue: new PostgresMessageQueue(sql),
29
+ * });
30
+ * ```
31
+ */
32
+ var PostgresMessageQueue = class {
33
+ #sql;
34
+ #tableName;
35
+ #channelName;
36
+ #pollIntervalMs;
37
+ #initialized;
38
+ #driverSerializesJson = false;
39
+ constructor(sql, options = {}) {
40
+ this.#sql = sql;
41
+ this.#tableName = options?.tableName ?? "fedify_message_v2";
42
+ this.#channelName = options?.channelName ?? "fedify_channel";
43
+ this.#pollIntervalMs = Temporal.Duration.from(options?.pollInterval ?? { seconds: 5 }).total("millisecond");
44
+ this.#initialized = options?.initialized ?? false;
45
+ }
46
+ async enqueue(message, options) {
47
+ await this.initialize();
48
+ const delay = options?.delay ?? Temporal.Duration.from({ seconds: 0 });
49
+ if (options?.delay) logger.debug("Enqueuing a message with a delay of {delay}...", {
50
+ delay,
51
+ message
52
+ });
53
+ else logger.debug("Enqueuing a message...", { message });
54
+ await this.#sql`
55
+ INSERT INTO ${this.#sql(this.#tableName)} (message, delay)
56
+ VALUES (
57
+ ${this.#json(message)},
58
+ ${delay.toString()}
59
+ );
60
+ `;
61
+ logger.debug("Enqueued a message.", { message });
62
+ await this.#sql.notify(this.#channelName, delay.toString());
63
+ logger.debug("Notified the message queue channel {channelName}.", {
64
+ channelName: this.#channelName,
65
+ message
66
+ });
67
+ }
68
+ async enqueueMany(messages, options) {
69
+ if (messages.length === 0) return;
70
+ await this.initialize();
71
+ const delay = options?.delay ?? Temporal.Duration.from({ seconds: 0 });
72
+ if (options?.delay) logger.debug("Enqueuing messages with a delay of {delay}...", {
73
+ delay,
74
+ messages
75
+ });
76
+ else logger.debug("Enqueuing messages...", { messages });
77
+ for (const message of messages) await this.#sql`
78
+ INSERT INTO ${this.#sql(this.#tableName)} (message, delay)
79
+ VALUES (
80
+ ${this.#json(message)},
81
+ ${delay.toString()}
82
+ );
83
+ `;
84
+ logger.debug("Enqueued messages.", { messages });
85
+ await this.#sql.notify(this.#channelName, delay.toString());
86
+ logger.debug("Notified the message queue channel {channelName}.", {
87
+ channelName: this.#channelName,
88
+ messages
89
+ });
90
+ }
91
+ async listen(handler, options = {}) {
92
+ await this.initialize();
93
+ const { signal } = options;
94
+ const poll = async () => {
95
+ while (!signal?.aborted) {
96
+ const query = this.#sql`
97
+ DELETE FROM ${this.#sql(this.#tableName)}
98
+ WHERE id = (
99
+ SELECT id
100
+ FROM ${this.#sql(this.#tableName)}
101
+ WHERE created + delay < CURRENT_TIMESTAMP
102
+ ORDER BY created
103
+ LIMIT 1
104
+ )
105
+ RETURNING message;
106
+ `.execute();
107
+ const cancel = query.cancel.bind(query);
108
+ signal?.addEventListener("abort", cancel);
109
+ let i = 0;
110
+ for (const message of await query) {
111
+ if (signal?.aborted) return;
112
+ await handler(message.message);
113
+ i++;
114
+ }
115
+ signal?.removeEventListener("abort", cancel);
116
+ if (i < 1) break;
117
+ }
118
+ };
119
+ const timeouts = /* @__PURE__ */ new Set();
120
+ const listen = await this.#sql.listen(this.#channelName, async (delay) => {
121
+ const duration = Temporal.Duration.from(delay);
122
+ const durationMs = duration.total("millisecond");
123
+ if (durationMs < 1) await poll();
124
+ else timeouts.add(setTimeout(poll, durationMs));
125
+ }, poll);
126
+ signal?.addEventListener("abort", () => {
127
+ listen.unlisten();
128
+ for (const timeout of timeouts) clearTimeout(timeout);
129
+ });
130
+ while (!signal?.aborted) {
131
+ let timeout;
132
+ await new Promise((resolve) => {
133
+ signal?.addEventListener("abort", resolve);
134
+ timeout = setTimeout(() => {
135
+ signal?.removeEventListener("abort", resolve);
136
+ resolve(0);
137
+ }, this.#pollIntervalMs);
138
+ timeouts.add(timeout);
139
+ });
140
+ if (timeout != null) timeouts.delete(timeout);
141
+ await poll();
142
+ }
143
+ await new Promise((resolve) => {
144
+ signal?.addEventListener("abort", () => resolve());
145
+ if (signal?.aborted) return resolve();
146
+ });
147
+ }
148
+ /**
149
+ * Initializes the message queue table if it does not already exist.
150
+ */
151
+ async initialize() {
152
+ if (this.#initialized) return;
153
+ logger.debug("Initializing the message queue table {tableName}...", { tableName: this.#tableName });
154
+ try {
155
+ await this.#sql`
156
+ CREATE TABLE IF NOT EXISTS ${this.#sql(this.#tableName)} (
157
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
158
+ message jsonb NOT NULL,
159
+ delay interval DEFAULT '0 seconds',
160
+ created timestamp with time zone DEFAULT CURRENT_TIMESTAMP
161
+ );
162
+ `;
163
+ } catch (error) {
164
+ if (!(error instanceof postgres.default.PostgresError && error.constraint_name === "pg_type_typname_nsp_index")) {
165
+ logger.error("Failed to initialize the message queue table: {error}", { error });
166
+ throw error;
167
+ }
168
+ }
169
+ this.#driverSerializesJson = await require_utils.driverSerializesJson(this.#sql);
170
+ this.#initialized = true;
171
+ logger.debug("Initialized the message queue table {tableName}.", { tableName: this.#tableName });
172
+ }
173
+ /**
174
+ * Drops the message queue table if it exists.
175
+ */
176
+ async drop() {
177
+ await this.#sql`DROP TABLE IF EXISTS ${this.#sql(this.#tableName)};`;
178
+ }
179
+ #json(value) {
180
+ if (this.#driverSerializesJson) return this.#sql.json(value);
181
+ return this.#sql.json(JSON.stringify(value));
182
+ }
183
+ };
184
+
185
+ //#endregion
186
+ exports.PostgresMessageQueue = PostgresMessageQueue;
package/dist/mq.d.cts ADDED
@@ -0,0 +1,65 @@
1
+ import { MessageQueue, MessageQueueEnqueueOptions, MessageQueueListenOptions } from "@fedify/fedify";
2
+ import { Sql } from "postgres";
3
+
4
+ //#region src/mq.d.ts
5
+ /**
6
+ * Options for the PostgreSQL message queue.
7
+ */
8
+ interface PostgresMessageQueueOptions {
9
+ /**
10
+ * The table name to use for the message queue.
11
+ * `"fedify_message_v2"` by default.
12
+ * @default `"fedify_message_v2"`
13
+ */
14
+ tableName?: string;
15
+ /**
16
+ * The channel name to use for the message queue.
17
+ * `"fedify_channel"` by default.
18
+ * @default `"fedify_channel"`
19
+ */
20
+ channelName?: string;
21
+ /**
22
+ * Whether the table has been initialized. `false` by default.
23
+ * @default `false`
24
+ */
25
+ initialized?: boolean;
26
+ /**
27
+ * The poll interval for the message queue. 5 seconds by default.
28
+ * @default `{ seconds: 5 }`
29
+ */
30
+ pollInterval?: Temporal.Duration | Temporal.DurationLike;
31
+ }
32
+ /**
33
+ * A message queue that uses PostgreSQL as the underlying storage.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * import { createFederation } from "@fedify/fedify";
38
+ * import { PostgresKvStore, PostgresMessageQueue } from "@fedify/postgres";
39
+ * import postgres from "postgres";
40
+ *
41
+ * const sql = postgres("postgres://user:pass@localhost/db");
42
+ *
43
+ * const federation = createFederation({
44
+ * kv: new PostgresKvStore(sql),
45
+ * queue: new PostgresMessageQueue(sql),
46
+ * });
47
+ * ```
48
+ */
49
+ declare class PostgresMessageQueue implements MessageQueue {
50
+ #private;
51
+ constructor(sql: Sql<{}>, options?: PostgresMessageQueueOptions);
52
+ enqueue(message: any, options?: MessageQueueEnqueueOptions): Promise<void>;
53
+ enqueueMany(messages: any[], options?: MessageQueueEnqueueOptions): Promise<void>;
54
+ listen(handler: (message: any) => void | Promise<void>, options?: MessageQueueListenOptions): Promise<void>;
55
+ /**
56
+ * Initializes the message queue table if it does not already exist.
57
+ */
58
+ initialize(): Promise<void>;
59
+ /**
60
+ * Drops the message queue table if it exists.
61
+ */
62
+ drop(): Promise<void>;
63
+ }
64
+ //#endregion
65
+ export { PostgresMessageQueue, PostgresMessageQueueOptions };
package/dist/mq.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  import { driverSerializesJson } from "./utils.js";
5
5
  import { getLogger } from "@logtape/logtape";
6
6
  import postgres from "postgres";
package/dist/utils.cjs ADDED
@@ -0,0 +1,12 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+
5
+ //#region src/utils.ts
6
+ async function driverSerializesJson(sql) {
7
+ const result = await sql`SELECT ${sql.json("{\"foo\":1}")}::jsonb AS test;`;
8
+ return result[0].test === "{\"foo\":1}";
9
+ }
10
+
11
+ //#endregion
12
+ exports.driverSerializesJson = driverSerializesJson;
package/dist/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  //#region src/utils.ts
5
5
  async function driverSerializesJson(sql) {
6
6
  const result = await sql`SELECT ${sql.json("{\"foo\":1}")}::jsonb AS test;`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/postgres",
3
- "version": "2.0.0-pr.433.1601+360b8a26",
3
+ "version": "2.0.0-pr.434.1659+7c115883",
4
4
  "description": "PostgreSQL drivers for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -27,23 +27,38 @@
27
27
  "https://github.com/sponsors/dahlia"
28
28
  ],
29
29
  "type": "module",
30
- "main": "./dist/mod.js",
30
+ "main": "./dist/mod.cjs",
31
31
  "module": "./dist/mod.js",
32
32
  "types": "./dist/mod.d.ts",
33
33
  "exports": {
34
34
  ".": {
35
- "types": "./dist/mod.d.ts",
35
+ "types": {
36
+ "import": "./dist/mod.d.ts",
37
+ "require": "./dist/mod.d.cts",
38
+ "default": "./dist/mod.d.ts"
39
+ },
36
40
  "import": "./dist/mod.js",
41
+ "require": "./dist/mod.cjs",
37
42
  "default": "./dist/mod.js"
38
43
  },
39
44
  "./kv": {
40
- "types": "./dist/kv.d.ts",
45
+ "types": {
46
+ "import": "./dist/kv.d.ts",
47
+ "require": "./dist/kv.d.cts",
48
+ "default": "./dist/kv.d.ts"
49
+ },
41
50
  "import": "./dist/kv.js",
51
+ "require": "./dist/kv.cjs",
42
52
  "default": "./dist/kv.js"
43
53
  },
44
54
  "./mq": {
45
- "types": "./dist/mq.d.ts",
55
+ "types": {
56
+ "import": "./dist/mq.d.ts",
57
+ "require": "./dist/mq.d.cts",
58
+ "default": "./dist/mq.d.ts"
59
+ },
46
60
  "import": "./dist/mq.js",
61
+ "require": "./dist/mq.cjs",
47
62
  "default": "./dist/mq.js"
48
63
  },
49
64
  "./package.json": "./package.json"
@@ -59,7 +74,7 @@
59
74
  },
60
75
  "peerDependencies": {
61
76
  "postgres": "^3.4.7",
62
- "@fedify/fedify": "^2.0.0-pr.433.1601+360b8a26"
77
+ "@fedify/fedify": "^2.0.0-pr.434.1659+7c115883"
63
78
  },
64
79
  "devDependencies": {
65
80
  "@std/async": "npm:@jsr/std__async@^1.0.13",