@haathie/pgmb 0.2.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/LICENSE +21 -0
- package/lib/abortable-async-iterator.d.ts +14 -0
- package/lib/abortable-async-iterator.js +86 -0
- package/lib/batcher.d.ts +12 -0
- package/lib/batcher.js +71 -0
- package/lib/client.d.ts +73 -0
- package/lib/client.js +432 -0
- package/lib/consts.d.ts +1 -0
- package/lib/consts.js +4 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +19 -0
- package/lib/queries.d.ts +453 -0
- package/lib/queries.js +235 -0
- package/lib/query-types.d.ts +17 -0
- package/lib/query-types.js +2 -0
- package/lib/retry-handler.d.ts +11 -0
- package/lib/retry-handler.js +93 -0
- package/lib/sse.d.ts +4 -0
- package/lib/sse.js +137 -0
- package/lib/types.d.ts +202 -0
- package/lib/types.js +2 -0
- package/lib/utils.d.ts +15 -0
- package/lib/utils.js +52 -0
- package/lib/webhook-handler.d.ts +6 -0
- package/lib/webhook-handler.js +68 -0
- package/package.json +52 -0
- package/readme.md +493 -0
- package/sql/pgmb-0.1.12-0.2.0.sql +1018 -0
- package/sql/pgmb-0.1.12.sql +612 -0
- package/sql/pgmb-0.1.5-0.1.6.sql +256 -0
- package/sql/pgmb-0.1.6-0.1.12.sql +95 -0
- package/sql/pgmb.sql +1030 -0
- package/sql/queries.sql +154 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 haathie
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
type AAResult<T> = IteratorResult<T>;
|
|
2
|
+
export declare class AbortableAsyncIterator<T> implements AsyncIterableIterator<T> {
|
|
3
|
+
#private;
|
|
4
|
+
readonly signal: AbortSignal;
|
|
5
|
+
readonly onEnd: () => void;
|
|
6
|
+
ended: boolean;
|
|
7
|
+
constructor(signal: AbortSignal, onEnd?: () => void);
|
|
8
|
+
next(): Promise<AAResult<T>>;
|
|
9
|
+
enqueue(value: T): void;
|
|
10
|
+
throw(reason?: unknown): Promise<AAResult<T>>;
|
|
11
|
+
return(value?: any): Promise<AAResult<T>>;
|
|
12
|
+
[Symbol.asyncIterator](): this;
|
|
13
|
+
}
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.AbortableAsyncIterator = void 0;
|
|
7
|
+
const assert_1 = __importDefault(require("assert"));
|
|
8
|
+
class AbortableAsyncIterator {
|
|
9
|
+
signal;
|
|
10
|
+
onEnd;
|
|
11
|
+
ended = false;
|
|
12
|
+
#resolve;
|
|
13
|
+
#reject;
|
|
14
|
+
#queue = [];
|
|
15
|
+
#locked = false;
|
|
16
|
+
constructor(signal, onEnd = () => { }) {
|
|
17
|
+
this.signal = signal;
|
|
18
|
+
this.onEnd = onEnd;
|
|
19
|
+
signal.addEventListener('abort', this.#onAbort);
|
|
20
|
+
}
|
|
21
|
+
async next() {
|
|
22
|
+
(0, assert_1.default)(!this.ended, 'Iterator has already been completed');
|
|
23
|
+
(0, assert_1.default)(!this.#locked, 'Concurrent calls to next() are not allowed');
|
|
24
|
+
let nextItem = this.#queue.shift();
|
|
25
|
+
if (nextItem) {
|
|
26
|
+
return { value: nextItem, done: false };
|
|
27
|
+
}
|
|
28
|
+
this.#locked = true;
|
|
29
|
+
try {
|
|
30
|
+
await this.#setupNextPromise();
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
this.#locked = false;
|
|
34
|
+
}
|
|
35
|
+
nextItem = this.#queue.shift();
|
|
36
|
+
if (nextItem) {
|
|
37
|
+
return { value: nextItem, done: false };
|
|
38
|
+
}
|
|
39
|
+
return { value: undefined, done: true };
|
|
40
|
+
}
|
|
41
|
+
enqueue(value) {
|
|
42
|
+
(0, assert_1.default)(!this.ended, 'Iterator has already been completed');
|
|
43
|
+
this.#queue.push(value);
|
|
44
|
+
this.#resolve?.();
|
|
45
|
+
}
|
|
46
|
+
throw(reason) {
|
|
47
|
+
this.signal.throwIfAborted();
|
|
48
|
+
this.#reject?.(reason);
|
|
49
|
+
this.#end();
|
|
50
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
51
|
+
}
|
|
52
|
+
return(value) {
|
|
53
|
+
this.#resolve?.();
|
|
54
|
+
this.#end();
|
|
55
|
+
return Promise.resolve({ done: true, value });
|
|
56
|
+
}
|
|
57
|
+
#setupNextPromise() {
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
this.#resolve = () => {
|
|
60
|
+
resolve();
|
|
61
|
+
this.#cleanupTask();
|
|
62
|
+
};
|
|
63
|
+
this.#reject = err => {
|
|
64
|
+
reject(err);
|
|
65
|
+
this.#cleanupTask();
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
#cleanupTask() {
|
|
70
|
+
this.#resolve = undefined;
|
|
71
|
+
this.#reject = undefined;
|
|
72
|
+
}
|
|
73
|
+
#onAbort = (reason) => {
|
|
74
|
+
this.#reject?.(reason);
|
|
75
|
+
this.#end();
|
|
76
|
+
this.ended = true;
|
|
77
|
+
};
|
|
78
|
+
#end() {
|
|
79
|
+
this.signal.removeEventListener('abort', this.#onAbort);
|
|
80
|
+
this.onEnd();
|
|
81
|
+
}
|
|
82
|
+
[Symbol.asyncIterator]() {
|
|
83
|
+
return this;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
exports.AbortableAsyncIterator = AbortableAsyncIterator;
|
package/lib/batcher.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { IEventData, PGMBEventBatcherOpts } from './types.ts';
|
|
2
|
+
export declare class PGMBEventBatcher<T extends IEventData> {
|
|
3
|
+
#private;
|
|
4
|
+
constructor({ shouldLog, publish, flushIntervalMs, maxBatchSize, logger }: PGMBEventBatcherOpts<T>);
|
|
5
|
+
end(): Promise<void>;
|
|
6
|
+
/**
|
|
7
|
+
* Enqueue a message to be published, will be flushed to the database
|
|
8
|
+
* when flush() is called (either manually or via interval)
|
|
9
|
+
*/
|
|
10
|
+
enqueue(msg: T): void;
|
|
11
|
+
flush(): Promise<void>;
|
|
12
|
+
}
|
package/lib/batcher.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PGMBEventBatcher = void 0;
|
|
4
|
+
class PGMBEventBatcher {
|
|
5
|
+
#publish;
|
|
6
|
+
#flushIntervalMs;
|
|
7
|
+
#maxBatchSize;
|
|
8
|
+
#currentBatch = { messages: [] };
|
|
9
|
+
#flushTimeout;
|
|
10
|
+
#flushTask;
|
|
11
|
+
#logger;
|
|
12
|
+
#shouldLog;
|
|
13
|
+
#batch = 0;
|
|
14
|
+
constructor({ shouldLog, publish, flushIntervalMs, maxBatchSize = 2500, logger }) {
|
|
15
|
+
this.#publish = publish;
|
|
16
|
+
this.#flushIntervalMs = flushIntervalMs;
|
|
17
|
+
this.#maxBatchSize = maxBatchSize;
|
|
18
|
+
this.#logger = logger;
|
|
19
|
+
this.#shouldLog = shouldLog;
|
|
20
|
+
}
|
|
21
|
+
async end() {
|
|
22
|
+
clearTimeout(this.#flushTimeout);
|
|
23
|
+
await this.#flushTask;
|
|
24
|
+
await this.flush();
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Enqueue a message to be published, will be flushed to the database
|
|
28
|
+
* when flush() is called (either manually or via interval)
|
|
29
|
+
*/
|
|
30
|
+
enqueue(msg) {
|
|
31
|
+
this.#currentBatch.messages.push(msg);
|
|
32
|
+
if (this.#currentBatch.messages.length >= this.#maxBatchSize) {
|
|
33
|
+
this.flush();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (this.#flushTimeout || !this.#flushIntervalMs) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
this.#flushTimeout = setTimeout(() => this.flush(), this.#flushIntervalMs);
|
|
40
|
+
}
|
|
41
|
+
async flush() {
|
|
42
|
+
if (!this.#currentBatch.messages.length) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const batch = this.#currentBatch;
|
|
46
|
+
this.#currentBatch = { messages: [] };
|
|
47
|
+
clearTimeout(this.#flushTimeout);
|
|
48
|
+
this.#flushTimeout = undefined;
|
|
49
|
+
await this.#flushTask;
|
|
50
|
+
this.#flushTask = this.#publishBatch(batch);
|
|
51
|
+
return this.#flushTask;
|
|
52
|
+
}
|
|
53
|
+
async #publishBatch({ messages }) {
|
|
54
|
+
const batch = ++this.#batch;
|
|
55
|
+
try {
|
|
56
|
+
const ids = await this.#publish(...messages);
|
|
57
|
+
for (const [i, { id }] of ids.entries()) {
|
|
58
|
+
if (this.#shouldLog && !this.#shouldLog(messages[i])) {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
this.#logger
|
|
62
|
+
?.info({ batch, id, message: messages[i] }, 'published message');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
this.#logger
|
|
67
|
+
?.error({ batch, err, msgs: messages }, 'failed to publish messages');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
exports.PGMBEventBatcher = PGMBEventBatcher;
|
package/lib/client.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type Logger } from 'pino';
|
|
2
|
+
import { PGMBEventBatcher } from './batcher.ts';
|
|
3
|
+
import type { PgClientLike } from './query-types.ts';
|
|
4
|
+
import type { GetWebhookInfoFn, IEphemeralListener, IEventData, IEventHandler, IReadEvent, Pgmb2ClientOpts, registerReliableHandlerParams, RegisterSubscriptionParams } from './types.ts';
|
|
5
|
+
type IReliableListener<T extends IEventData> = {
|
|
6
|
+
type: 'reliable';
|
|
7
|
+
handler: IEventHandler<T>;
|
|
8
|
+
removeOnEmpty?: boolean;
|
|
9
|
+
extra?: unknown;
|
|
10
|
+
queue: {
|
|
11
|
+
item: IReadEvent<T>;
|
|
12
|
+
checkpoint: Checkpoint;
|
|
13
|
+
}[];
|
|
14
|
+
};
|
|
15
|
+
type IFireAndForgetListener<T extends IEventData> = {
|
|
16
|
+
type: 'fire-and-forget';
|
|
17
|
+
stream: IEphemeralListener<T>;
|
|
18
|
+
};
|
|
19
|
+
type IListener<T extends IEventData> = IFireAndForgetListener<T> | IReliableListener<T>;
|
|
20
|
+
type Checkpoint = {
|
|
21
|
+
activeTasks: number;
|
|
22
|
+
nextCursor: string;
|
|
23
|
+
cancelled?: boolean;
|
|
24
|
+
};
|
|
25
|
+
export type IListenerStore<T extends IEventData> = {
|
|
26
|
+
values: {
|
|
27
|
+
[id: string]: IListener<T>;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export declare class PgmbClient<T extends IEventData = IEventData> extends PGMBEventBatcher<T> {
|
|
31
|
+
#private;
|
|
32
|
+
readonly client: PgClientLike;
|
|
33
|
+
readonly logger: Logger;
|
|
34
|
+
readonly groupId: string;
|
|
35
|
+
readonly sleepDurationMs: number;
|
|
36
|
+
readonly readChunkSize: number;
|
|
37
|
+
readonly subscriptionMaintenanceMs: number;
|
|
38
|
+
readonly tableMaintenanceMs: number;
|
|
39
|
+
readonly maxActiveCheckpoints: number;
|
|
40
|
+
readonly getWebhookInfo: GetWebhookInfoFn;
|
|
41
|
+
readonly webhookHandler: IEventHandler;
|
|
42
|
+
readonly listeners: {
|
|
43
|
+
[subId: string]: IListenerStore<T>;
|
|
44
|
+
};
|
|
45
|
+
constructor({ client, groupId, logger, sleepDurationMs, readChunkSize, maxActiveCheckpoints, poll, subscriptionMaintenanceMs, webhookHandlerOpts, getWebhookInfo, tableMaintainanceMs, ...batcherOpts }: Pgmb2ClientOpts);
|
|
46
|
+
init(): Promise<void>;
|
|
47
|
+
end(): Promise<void>;
|
|
48
|
+
publish(events: T[], client?: PgClientLike): Promise<import("./queries.ts").IWriteEventsResult[]>;
|
|
49
|
+
assertSubscription(opts: RegisterSubscriptionParams, client?: PgClientLike): Promise<import("./queries.ts").IAssertSubscriptionResult>;
|
|
50
|
+
/**
|
|
51
|
+
* Registers a fire-and-forget handler, returning an async iterator
|
|
52
|
+
* that yields events as they arrive. The client does not wait for event
|
|
53
|
+
* processing acknowledgements. Useful for cases where data is eventually
|
|
54
|
+
* consistent, or when event delivery isn't critical
|
|
55
|
+
* (eg. http SSE, websockets).
|
|
56
|
+
*/
|
|
57
|
+
registerFireAndForgetHandler(opts: RegisterSubscriptionParams): Promise<IEphemeralListener<T>>;
|
|
58
|
+
/**
|
|
59
|
+
* Registers a reliable handler for the given subscription params.
|
|
60
|
+
* If the handler throws an error, client will rollback to the last known
|
|
61
|
+
* good cursor, and re-deliver events.
|
|
62
|
+
* To avoid a full redelivery of a batch, a retry strategy can be provided
|
|
63
|
+
* to retry failed events by the handler itself, allowing for delayed retries
|
|
64
|
+
* with backoff, and without disrupting the overall event flow.
|
|
65
|
+
*/
|
|
66
|
+
registerReliableHandler({ retryOpts, name, ...opts }: registerReliableHandlerParams, handler: IEventHandler<T>): Promise<{
|
|
67
|
+
subscriptionId: string;
|
|
68
|
+
cancel: () => void;
|
|
69
|
+
}>;
|
|
70
|
+
removeSubscription(subId: string): Promise<void>;
|
|
71
|
+
readChanges(): Promise<number>;
|
|
72
|
+
}
|
|
73
|
+
export {};
|