@nagi-js/pgmq 0.1.1-rc.22 → 0.1.1-rc.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +10 -4
- package/dist/index.js.map +1 -1
- package/package.json +7 -2
package/dist/index.js
CHANGED
|
@@ -3,9 +3,15 @@ import { sql } from 'kysely';
|
|
|
3
3
|
// src/pgmq-queue.ts
|
|
4
4
|
var DEFAULT_QUEUE_NAME = "nagi";
|
|
5
5
|
var DEFAULT_VISIBILITY_TIMEOUT_MS = 12e4;
|
|
6
|
+
var QUEUE_NAME_RE = /^[A-Za-z0-9_]{1,47}$/;
|
|
6
7
|
function pgmqQueue(opts) {
|
|
7
|
-
const db = stripPlugins(opts.db);
|
|
8
8
|
const queueName = opts.queueName ?? DEFAULT_QUEUE_NAME;
|
|
9
|
+
if (!QUEUE_NAME_RE.test(queueName)) {
|
|
10
|
+
throw new Error(
|
|
11
|
+
`@nagi-js/pgmq: invalid queue name "${queueName}". Must match ${QUEUE_NAME_RE}.`
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
const db = stripPlugins(opts.db);
|
|
9
15
|
const vtSeconds = Math.max(
|
|
10
16
|
1,
|
|
11
17
|
Math.ceil(
|
|
@@ -55,7 +61,7 @@ function buildQueue(executor, config) {
|
|
|
55
61
|
async dequeue({
|
|
56
62
|
count
|
|
57
63
|
}) {
|
|
58
|
-
const { rows } = await sql`SELECT msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(
|
|
64
|
+
const { rows } = await sql`SELECT msg_id::text AS msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(
|
|
59
65
|
executor
|
|
60
66
|
);
|
|
61
67
|
return rows.map(
|
|
@@ -106,7 +112,7 @@ function buildQueue(executor, config) {
|
|
|
106
112
|
}
|
|
107
113
|
};
|
|
108
114
|
}
|
|
109
|
-
function projectMessage(
|
|
115
|
+
function projectMessage(msgId, raw, readCount) {
|
|
110
116
|
if (raw === null || typeof raw !== "object" || typeof raw.runId !== "string" || typeof raw.stepId !== "string" || typeof raw.attempt !== "number") {
|
|
111
117
|
throw new Error(
|
|
112
118
|
`pgmq: malformed message envelope ${JSON.stringify(raw)} \u2014 expected { runId, stepId, attempt }`
|
|
@@ -114,7 +120,7 @@ function projectMessage(rawMsgId, raw, readCount) {
|
|
|
114
120
|
}
|
|
115
121
|
const envelope = raw;
|
|
116
122
|
return {
|
|
117
|
-
receipt:
|
|
123
|
+
receipt: msgId,
|
|
118
124
|
runId: envelope.runId,
|
|
119
125
|
stepId: envelope.stepId,
|
|
120
126
|
attempt: envelope.attempt,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgmq-queue.ts"],"names":[],"mappings":";;;AAcA,IAAM,kBAAA,GAAqB,MAAA;AAK3B,IAAM,6BAAA,GAAwC,IAAA;AA8BvC,SAAS,UAAwB,IAAA,EAAoC;AAK1E,EAAA,MAAM,EAAA,GAAK,YAAA,CAAa,IAAA,CAAK,EAAgC,CAAA;AAC7D,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,kBAAA;AACpC,EAAA,MAAM,YAAY,IAAA,CAAK,GAAA;AAAA,IACrB,CAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MAAA,CACF,IAAA,CAAK,uBAAuB,6BAAA,IAAiC;AAAA;AAChE,GACF;AACA,EAAA,MAAM,WAAA,GAAc,KAAK,WAAA,IAAe,KAAA;AACxC,EAAA,MAAM,YAAA,GAAe,KAAK,YAAA,IAAgB,KAAA;AAC1C,EAAA,MAAM,MAAA,GAAsB,EAAE,SAAA,EAAW,SAAA,EAAW,YAAA,EAAa;AAEjE,EAAA,OAAO;AAAA,IACL,GAAG,UAAA,CAAW,EAAA,EAAI,MAAM,CAAA;AAAA,IAExB,MAAM,YAAA,GAA8B;AAClC,MAAA,MAAM,GA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,GAAA,EACA,SAAA,EACc;AACd,EAAA,IACE,QAAQ,IAAA,IACR,OAAO,GAAA,KAAQ,QAAA,IACf,OAAQ,GAAA,CAA4B,KAAA,KAAU,QAAA,IAC9C,OAAQ,IAA6B,MAAA,KAAW,QAAA,IAChD,OAAQ,GAAA,CAA8B,YAAY,QAAA,EAClD;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,iCAAA,EAAoC,IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA,2CAAA;AAAA,KACzD;AAAA,EACF;AACA,EAAA,MAAM,QAAA,GAAW,GAAA;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,OAAO,QAAQ,CAAA;AAAA,IACxB,OAAO,QAAA,CAAS,KAAA;AAAA,IAChB,QAAQ,QAAA,CAAS,MAAA;AAAA,IACjB,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,SAAA;AAAA,IACA,OAAA,EAAS,IAAA;AAAA,IACT,GAAI,SAAS,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAO,GAAI;AAAC,GACrE;AACF;AAEA,SAAS,aAAa,OAAA,EAAyB;AAC7C,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,OAAO,CAAA;AAAA,EAChB,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAA,GACJ,OAAA,KAAY,WAAA,GACR,wIAAA,GACA,EAAA;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,2BAA2B,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,6CAAwC,IAAI,CAAA;AAAA,KAChG;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"index.js","sourcesContent":["import type {\n AttemptNumber,\n Millis,\n Queue,\n QueueDequeueOpts,\n QueueEnqueueOpts,\n QueueInspectEntry,\n QueueMessage,\n RunId,\n StepId,\n Tx,\n} from \"@nagi-js/core\";\nimport { type Kysely, sql } from \"kysely\";\n\nconst DEFAULT_QUEUE_NAME = \"nagi\";\n// Must exceed core's DEFAULT_HEARTBEAT_INTERVAL_MS (40s), or a slow step is\n// redelivered before its first lease extension. Matches core's\n// DEFAULT_HEARTBEAT_LEASE_MS so a crashed worker's message and its store\n// lease become reclaimable at the same time.\nconst DEFAULT_VISIBILITY_TIMEOUT_MS: Millis = 120_000;\n\nexport interface PgmqQueueOpts<DB = unknown> {\n readonly db: Kysely<DB>;\n readonly queueName?: string;\n readonly visibilityTimeoutMs?: Millis;\n readonly partitioned?: boolean;\n readonly archiveOnAck?: boolean;\n}\n\n// Narrows the optional core capabilities to required: pgmq always provides both.\nexport interface PgmqQueue extends Queue {\n ensureSchema(): Promise<void>;\n withTx(tx: Tx): Queue;\n}\n\ninterface MessageEnvelope {\n readonly runId: string;\n readonly stepId: string;\n readonly attempt: number;\n // Absent on messages enqueued before the field existed; see QueueMessage.\n readonly flowId?: string;\n}\n\ninterface QueueConfig {\n readonly queueName: string;\n readonly vtSeconds: number;\n readonly archiveOnAck: boolean;\n}\n\nexport function pgmqQueue<DB = unknown>(opts: PgmqQueueOpts<DB>): PgmqQueue {\n // Caller-installed Kysely plugins (notably CamelCasePlugin) rewrite the result\n // transformer, turning our internal `msg_id` reads into `msgId` and breaking\n // parseReceipt. Strip plugins from the executor used for our own SQL only —\n // the caller's `db` is untouched so their CamelCase reads still work.\n const db = stripPlugins(opts.db as unknown as Kysely<unknown>);\n const queueName = opts.queueName ?? DEFAULT_QUEUE_NAME;\n const vtSeconds = Math.max(\n 1,\n Math.ceil(\n (opts.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS) / 1000,\n ),\n );\n const partitioned = opts.partitioned ?? false;\n const archiveOnAck = opts.archiveOnAck ?? false;\n const config: QueueConfig = { queueName, vtSeconds, archiveOnAck };\n\n return {\n ...buildQueue(db, config),\n\n async ensureSchema(): Promise<void> {\n await sql`CREATE EXTENSION IF NOT EXISTS pgmq`.execute(db);\n if (partitioned) {\n await sql`SELECT pgmq.create_partitioned(${queueName})`.execute(db);\n } else {\n await sql`SELECT pgmq.create(${queueName})`.execute(db);\n }\n },\n\n withTx(tx: Tx): Queue {\n return buildQueue(stripPlugins(tx as unknown as Kysely<unknown>), config);\n },\n };\n}\n\ninterface PluginStrippable {\n withoutPlugins?: () => Kysely<unknown>;\n}\n\nfunction stripPlugins(executor: Kysely<unknown>): Kysely<unknown> {\n const candidate = executor as Kysely<unknown> & PluginStrippable;\n return typeof candidate.withoutPlugins === \"function\"\n ? candidate.withoutPlugins()\n : executor;\n}\n\nfunction buildQueue(executor: Kysely<unknown>, config: QueueConfig): Queue {\n const { queueName, vtSeconds, archiveOnAck } = config;\n\n return {\n async enqueue(\n runId: RunId,\n stepId: StepId,\n options?: QueueEnqueueOpts,\n ): Promise<void> {\n const envelope: MessageEnvelope = {\n runId,\n stepId,\n attempt: options?.attempt ?? 1,\n ...(options?.flowId !== undefined ? { flowId: options.flowId } : {}),\n };\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.send(${queueName}, ${JSON.stringify(envelope)}::jsonb, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async dequeue({\n count,\n }: QueueDequeueOpts): Promise<readonly QueueMessage[]> {\n const { rows } = await sql<{\n msg_id: string | number | bigint;\n read_ct: number;\n message: unknown;\n }>`SELECT msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(\n executor,\n );\n return rows.map((row) =>\n projectMessage(row.msg_id, row.message, row.read_ct),\n );\n },\n\n async ack(receipt: string): Promise<void> {\n const msgId = parseReceipt(receipt);\n if (archiveOnAck) {\n await sql`SELECT pgmq.archive(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n } else {\n await sql`SELECT pgmq.delete(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n }\n },\n\n async nack(\n receipt: string,\n options?: { readonly delayMs?: Millis },\n ): Promise<void> {\n const msgId = parseReceipt(receipt);\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async extend(receipt: string, leaseMs: Millis): Promise<void> {\n const msgId = parseReceipt(receipt);\n const vt = Math.max(1, Math.ceil(leaseMs / 1000));\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${vt}::int)`.execute(\n executor,\n );\n },\n\n async inspect(runId: RunId): Promise<readonly QueueInspectEntry[]> {\n // Direct table read (pgmq stores queue \"x\" as pgmq.q_x) — pgmq has no\n // query-by-payload API. Read-only; safe alongside consuming workers.\n const { rows } = await sql<{\n read_ct: number;\n vt: Date | string;\n message: unknown;\n }>`SELECT read_ct, vt, message FROM ${sql.raw(`pgmq.q_${queueName}`)}\n WHERE message->>'runId' = ${runId}`.execute(executor);\n return rows.map((row) => {\n const m = projectMessage(\"0\", row.message, row.read_ct);\n return {\n stepId: m.stepId,\n attempt: m.attempt,\n readCount: row.read_ct,\n visibleAt: row.vt instanceof Date ? row.vt : new Date(row.vt),\n };\n });\n },\n };\n}\n\nfunction projectMessage(\n rawMsgId: string | number | bigint,\n raw: unknown,\n readCount: number,\n): QueueMessage {\n if (\n raw === null ||\n typeof raw !== \"object\" ||\n typeof (raw as { runId?: unknown }).runId !== \"string\" ||\n typeof (raw as { stepId?: unknown }).stepId !== \"string\" ||\n typeof (raw as { attempt?: unknown }).attempt !== \"number\"\n ) {\n throw new Error(\n `pgmq: malformed message envelope ${JSON.stringify(raw)} — expected { runId, stepId, attempt }`,\n );\n }\n const envelope = raw as MessageEnvelope;\n return {\n receipt: String(rawMsgId),\n runId: envelope.runId as RunId,\n stepId: envelope.stepId as StepId,\n attempt: envelope.attempt as AttemptNumber,\n readCount,\n payload: null,\n ...(envelope.flowId !== undefined ? { flowId: envelope.flowId } : {}),\n };\n}\n\nfunction parseReceipt(receipt: string): string {\n try {\n BigInt(receipt);\n } catch {\n const hint =\n receipt === \"undefined\"\n ? \" (likely caller installed a Kysely CamelCasePlugin that rewrote msg_id → msgId; nagi internal executor should be plugin-stripped)\"\n : \"\";\n throw new Error(\n `pgmq: malformed receipt ${JSON.stringify(receipt)} — expected stringified bigint msg_id${hint}`,\n );\n }\n return receipt;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/pgmq-queue.ts"],"names":[],"mappings":";;;AAcA,IAAM,kBAAA,GAAqB,MAAA;AAK3B,IAAM,6BAAA,GAAwC,IAAA;AAG9C,IAAM,aAAA,GAAgB,sBAAA;AA8Bf,SAAS,UAAwB,IAAA,EAAoC;AAC1E,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,kBAAA;AACpC,EAAA,IAAI,CAAC,aAAA,CAAc,IAAA,CAAK,SAAS,CAAA,EAAG;AAClC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,mCAAA,EAAsC,SAAS,CAAA,cAAA,EAAiB,aAAa,CAAA,CAAA;AAAA,KAC/E;AAAA,EACF;AAKA,EAAA,MAAM,EAAA,GAAK,YAAA,CAAa,IAAA,CAAK,EAAgC,CAAA;AAC7D,EAAA,MAAM,YAAY,IAAA,CAAK,GAAA;AAAA,IACrB,CAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MAAA,CACF,IAAA,CAAK,uBAAuB,6BAAA,IAAiC;AAAA;AAChE,GACF;AACA,EAAA,MAAM,WAAA,GAAc,KAAK,WAAA,IAAe,KAAA;AACxC,EAAA,MAAM,YAAA,GAAe,KAAK,YAAA,IAAgB,KAAA;AAC1C,EAAA,MAAM,MAAA,GAAsB,EAAE,SAAA,EAAW,SAAA,EAAW,YAAA,EAAa;AAEjE,EAAA,OAAO;AAAA,IACL,GAAG,UAAA,CAAW,EAAA,EAAI,MAAM,CAAA;AAAA,IAExB,MAAM,YAAA,GAA8B;AAClC,MAAA,MAAM,GAAA,CAAA,mCAAA,CAAA,CAAyC,QAAQ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ACE,QAAQ,IAAA,IACR,OAAO,GAAA,KAAQ,QAAA,IACf,OAAQ,GAAA,CAA4B,KAAA,KAAU,QAAA,IAC9C,OAAQ,IAA6B,MAAA,KAAW,QAAA,IAChD,OAAQ,GAAA,CAA8B,YAAY,QAAA,EAClD;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,iCAAA,EAAoC,IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA,2CAAA;AAAA,KACzD;AAAA,EACF;AACA,EAAA,MAAM,QAAA,GAAW,GAAA;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,OAAO,QAAA,CAAS,KAAA;AAAA,IAChB,QAAQ,QAAA,CAAS,MAAA;AAAA,IACjB,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,SAAA;AAAA,IACA,OAAA,EAAS,IAAA;AAAA,IACT,GAAI,SAAS,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAO,GAAI;AAAC,GACrE;AACF;AAEA,SAAS,aAAa,OAAA,EAAyB;AAC7C,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,OAAO,CAAA;AAAA,EAChB,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAA,GACJ,OAAA,KAAY,WAAA,GACR,wIAAA,GACA,EAAA;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,2BAA2B,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,6CAAwC,IAAI,CAAA;AAAA,KAChG;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"index.js","sourcesContent":["import type {\n AttemptNumber,\n Millis,\n Queue,\n QueueDequeueOpts,\n QueueEnqueueOpts,\n QueueInspectEntry,\n QueueMessage,\n RunId,\n StepId,\n Tx,\n} from \"@nagi-js/core\";\nimport { type Kysely, sql } from \"kysely\";\n\nconst DEFAULT_QUEUE_NAME = \"nagi\";\n// Must exceed core's DEFAULT_HEARTBEAT_INTERVAL_MS (40s), or a slow step is\n// redelivered before its first lease extension. Matches core's\n// DEFAULT_HEARTBEAT_LEASE_MS so a crashed worker's message and its store\n// lease become reclaimable at the same time.\nconst DEFAULT_VISIBILITY_TIMEOUT_MS: Millis = 120_000;\n// pgmq's client rule (max 47 keeps archived_at_idx_<name> within 63 bytes);\n// stricter than the extension because inspect() splices it unquoted.\nconst QUEUE_NAME_RE = /^[A-Za-z0-9_]{1,47}$/;\n\nexport interface PgmqQueueOpts<DB = unknown> {\n readonly db: Kysely<DB>;\n readonly queueName?: string;\n readonly visibilityTimeoutMs?: Millis;\n readonly partitioned?: boolean;\n readonly archiveOnAck?: boolean;\n}\n\n// Narrows the optional core capabilities to required: pgmq always provides both.\nexport interface PgmqQueue extends Queue {\n ensureSchema(): Promise<void>;\n withTx(tx: Tx): Queue;\n}\n\ninterface MessageEnvelope {\n readonly runId: string;\n readonly stepId: string;\n readonly attempt: number;\n // Absent on messages enqueued before the field existed; see QueueMessage.\n readonly flowId?: string;\n}\n\ninterface QueueConfig {\n readonly queueName: string;\n readonly vtSeconds: number;\n readonly archiveOnAck: boolean;\n}\n\nexport function pgmqQueue<DB = unknown>(opts: PgmqQueueOpts<DB>): PgmqQueue {\n const queueName = opts.queueName ?? DEFAULT_QUEUE_NAME;\n if (!QUEUE_NAME_RE.test(queueName)) {\n throw new Error(\n `@nagi-js/pgmq: invalid queue name \"${queueName}\". Must match ${QUEUE_NAME_RE}.`,\n );\n }\n // Caller-installed Kysely plugins (notably CamelCasePlugin) rewrite the result\n // transformer, turning our internal `msg_id` reads into `msgId` and breaking\n // parseReceipt. Strip plugins from the executor used for our own SQL only —\n // the caller's `db` is untouched so their CamelCase reads still work.\n const db = stripPlugins(opts.db as unknown as Kysely<unknown>);\n const vtSeconds = Math.max(\n 1,\n Math.ceil(\n (opts.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS) / 1000,\n ),\n );\n const partitioned = opts.partitioned ?? false;\n const archiveOnAck = opts.archiveOnAck ?? false;\n const config: QueueConfig = { queueName, vtSeconds, archiveOnAck };\n\n return {\n ...buildQueue(db, config),\n\n async ensureSchema(): Promise<void> {\n await sql`CREATE EXTENSION IF NOT EXISTS pgmq`.execute(db);\n if (partitioned) {\n await sql`SELECT pgmq.create_partitioned(${queueName})`.execute(db);\n } else {\n await sql`SELECT pgmq.create(${queueName})`.execute(db);\n }\n },\n\n withTx(tx: Tx): Queue {\n return buildQueue(stripPlugins(tx as unknown as Kysely<unknown>), config);\n },\n };\n}\n\ninterface PluginStrippable {\n withoutPlugins?: () => Kysely<unknown>;\n}\n\nfunction stripPlugins(executor: Kysely<unknown>): Kysely<unknown> {\n const candidate = executor as Kysely<unknown> & PluginStrippable;\n return typeof candidate.withoutPlugins === \"function\"\n ? candidate.withoutPlugins()\n : executor;\n}\n\nfunction buildQueue(executor: Kysely<unknown>, config: QueueConfig): Queue {\n const { queueName, vtSeconds, archiveOnAck } = config;\n\n return {\n async enqueue(\n runId: RunId,\n stepId: StepId,\n options?: QueueEnqueueOpts,\n ): Promise<void> {\n const envelope: MessageEnvelope = {\n runId,\n stepId,\n attempt: options?.attempt ?? 1,\n ...(options?.flowId !== undefined ? { flowId: options.flowId } : {}),\n };\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.send(${queueName}, ${JSON.stringify(envelope)}::jsonb, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async dequeue({\n count,\n }: QueueDequeueOpts): Promise<readonly QueueMessage[]> {\n // ::text: a consumer int8 parser would round msg_id past 2^53.\n const { rows } = await sql<{\n msg_id: string;\n read_ct: number;\n message: unknown;\n }>`SELECT msg_id::text AS msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(\n executor,\n );\n return rows.map((row) =>\n projectMessage(row.msg_id, row.message, row.read_ct),\n );\n },\n\n async ack(receipt: string): Promise<void> {\n const msgId = parseReceipt(receipt);\n if (archiveOnAck) {\n await sql`SELECT pgmq.archive(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n } else {\n await sql`SELECT pgmq.delete(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n }\n },\n\n async nack(\n receipt: string,\n options?: { readonly delayMs?: Millis },\n ): Promise<void> {\n const msgId = parseReceipt(receipt);\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async extend(receipt: string, leaseMs: Millis): Promise<void> {\n const msgId = parseReceipt(receipt);\n const vt = Math.max(1, Math.ceil(leaseMs / 1000));\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${vt}::int)`.execute(\n executor,\n );\n },\n\n async inspect(runId: RunId): Promise<readonly QueueInspectEntry[]> {\n // Direct table read (pgmq stores queue \"x\" as pgmq.q_x) — pgmq has no\n // query-by-payload API. Read-only; safe alongside consuming workers.\n const { rows } = await sql<{\n read_ct: number;\n vt: Date | string;\n message: unknown;\n }>`SELECT read_ct, vt, message FROM ${sql.raw(`pgmq.q_${queueName}`)}\n WHERE message->>'runId' = ${runId}`.execute(executor);\n return rows.map((row) => {\n const m = projectMessage(\"0\", row.message, row.read_ct);\n return {\n stepId: m.stepId,\n attempt: m.attempt,\n readCount: row.read_ct,\n visibleAt: row.vt instanceof Date ? row.vt : new Date(row.vt),\n };\n });\n },\n };\n}\n\nfunction projectMessage(\n msgId: string,\n raw: unknown,\n readCount: number,\n): QueueMessage {\n if (\n raw === null ||\n typeof raw !== \"object\" ||\n typeof (raw as { runId?: unknown }).runId !== \"string\" ||\n typeof (raw as { stepId?: unknown }).stepId !== \"string\" ||\n typeof (raw as { attempt?: unknown }).attempt !== \"number\"\n ) {\n throw new Error(\n `pgmq: malformed message envelope ${JSON.stringify(raw)} — expected { runId, stepId, attempt }`,\n );\n }\n const envelope = raw as MessageEnvelope;\n return {\n receipt: msgId,\n runId: envelope.runId as RunId,\n stepId: envelope.stepId as StepId,\n attempt: envelope.attempt as AttemptNumber,\n readCount,\n payload: null,\n ...(envelope.flowId !== undefined ? { flowId: envelope.flowId } : {}),\n };\n}\n\nfunction parseReceipt(receipt: string): string {\n try {\n BigInt(receipt);\n } catch {\n const hint =\n receipt === \"undefined\"\n ? \" (likely caller installed a Kysely CamelCasePlugin that rewrote msg_id → msgId; nagi internal executor should be plugin-stripped)\"\n : \"\";\n throw new Error(\n `pgmq: malformed receipt ${JSON.stringify(receipt)} — expected stringified bigint msg_id${hint}`,\n );\n }\n return receipt;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nagi-js/pgmq",
|
|
3
|
-
"version": "0.1.1-rc.
|
|
3
|
+
"version": "0.1.1-rc.23",
|
|
4
4
|
"description": "PGMQ Queue adapter for nagi.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -35,11 +35,16 @@
|
|
|
35
35
|
"LICENSE"
|
|
36
36
|
],
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@nagi-js/core": "0.1.1-rc.
|
|
38
|
+
"@nagi-js/core": "0.1.1-rc.22"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"kysely": "^0.29.0"
|
|
42
42
|
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/pg": "^8.23.1",
|
|
45
|
+
"kysely": "^0.29.0",
|
|
46
|
+
"pg": "^8.23.0"
|
|
47
|
+
},
|
|
43
48
|
"repository": {
|
|
44
49
|
"type": "git",
|
|
45
50
|
"url": "git+https://github.com/lymo-inc/nagi.git",
|