@hotmeshio/hotmesh 0.29.1 → 0.31.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/README.md +43 -0
- package/build/index.d.ts +2 -1
- package/build/index.js +3 -1
- package/build/modules/enums.d.ts +35 -0
- package/build/modules/enums.js +41 -1
- package/build/modules/errors.d.ts +26 -2
- package/build/modules/errors.js +82 -1
- package/build/modules/utils.d.ts +8 -0
- package/build/modules/utils.js +19 -1
- package/build/package.json +1 -1
- package/build/services/activities/trigger.js +3 -1
- package/build/services/connector/health.d.ts +42 -0
- package/build/services/connector/health.js +100 -0
- package/build/services/connector/index.js +2 -1
- package/build/services/connector/providers/postgres-resilient-client.d.ts +95 -0
- package/build/services/connector/providers/postgres-resilient-client.js +446 -0
- package/build/services/connector/providers/postgres.d.ts +6 -0
- package/build/services/connector/providers/postgres.js +72 -14
- package/build/services/durable/client.js +11 -3
- package/build/services/durable/handle.js +101 -41
- package/build/services/durable/worker.js +12 -4
- package/build/services/durable/workflow/condition.d.ts +14 -0
- package/build/services/durable/workflow/condition.js +14 -0
- package/build/services/engine/completion.js +3 -3
- package/build/services/engine/signal.js +3 -3
- package/build/services/escalations/batch.d.ts +7 -3
- package/build/services/escalations/batch.js +64 -6
- package/build/services/escalations/client.d.ts +4 -2
- package/build/services/escalations/client.js +4 -2
- package/build/services/escalations/fold.d.ts +3 -2
- package/build/services/escalations/fold.js +13 -2
- package/build/services/escalations/index.d.ts +1 -1
- package/build/services/escalations/index.js +2 -1
- package/build/services/hotmesh/index.js +17 -4
- package/build/services/quorum/index.js +13 -13
- package/build/services/router/consumption/index.d.ts +20 -0
- package/build/services/router/consumption/index.js +177 -7
- package/build/services/store/providers/postgres/kvtransaction.js +8 -1
- package/build/services/store/providers/postgres/postgres.d.ts +2 -1
- package/build/services/store/providers/postgres/postgres.js +18 -9
- package/build/services/stream/index.d.ts +16 -0
- package/build/services/stream/index.js +23 -0
- package/build/services/stream/providers/postgres/messages.d.ts +7 -0
- package/build/services/stream/providers/postgres/messages.js +27 -1
- package/build/services/stream/providers/postgres/notifications.d.ts +13 -0
- package/build/services/stream/providers/postgres/notifications.js +89 -2
- package/build/services/stream/providers/postgres/postgres.d.ts +7 -0
- package/build/services/stream/providers/postgres/postgres.js +24 -3
- package/build/services/stream/providers/postgres/scout.d.ts +10 -0
- package/build/services/stream/providers/postgres/scout.js +38 -4
- package/build/services/stream/registry.d.ts +6 -0
- package/build/services/stream/registry.js +11 -2
- package/build/services/sub/providers/postgres/postgres.d.ts +6 -0
- package/build/services/sub/providers/postgres/postgres.js +62 -2
- package/build/services/task/index.js +1 -1
- package/build/services/worker/credentials.js +5 -0
- package/build/services/worker/index.js +5 -5
- package/build/types/hmsh_escalations.d.ts +32 -0
- package/build/types/hmsh_escalations.js +5 -1
- package/build/types/index.d.ts +3 -3
- package/build/types/index.js +2 -1
- package/build/types/postgres.d.ts +20 -0
- package/build/types/provider.d.ts +28 -0
- package/index.ts +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { EventEmitter } from 'events';
|
|
3
|
+
import { ILogger } from '../../logger';
|
|
4
|
+
import { PostgresClassType, PostgresClientOptions, PostgresClientType } from '../../../types/postgres';
|
|
5
|
+
/** Timing policy of a resilient client; defaults come from the `HMSH_PG_*` settings. */
|
|
6
|
+
export interface ResilientPostgresPolicy {
|
|
7
|
+
reconnectBaseMs: number;
|
|
8
|
+
reconnectMaxMs: number;
|
|
9
|
+
heartbeatMs: number;
|
|
10
|
+
heartbeatTimeoutMs: number;
|
|
11
|
+
txLostWindowMs: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A PostgreSQL client that survives server restarts, failovers and
|
|
15
|
+
* dropped sockets.
|
|
16
|
+
*
|
|
17
|
+
* It is a stable object that owns exactly one native `pg.Client` at a
|
|
18
|
+
* time. Store, stream and sub services hold a reference to this object
|
|
19
|
+
* for their lifetime, so the native socket underneath can be replaced
|
|
20
|
+
* without any of them noticing.
|
|
21
|
+
*
|
|
22
|
+
* Contract:
|
|
23
|
+
* - A lost socket never emits an unhandled `'error'`. The wrapper
|
|
24
|
+
* re-emits `'error'` only when the caller registered a listener.
|
|
25
|
+
* - While reconnecting, `query()` rejects at once with a
|
|
26
|
+
* `HotMeshConnectionError`; callers already retry on query failure.
|
|
27
|
+
* - A failure caused by the connection (not by the statement) is
|
|
28
|
+
* always surfaced as a `HotMeshConnectionError`.
|
|
29
|
+
* - Reconnect uses full-jitter exponential backoff and never gives up
|
|
30
|
+
* until `end()`.
|
|
31
|
+
* - `'reconnected'` fires after every successful reconnect so LISTEN
|
|
32
|
+
* owners can re-arm their channels on the new session.
|
|
33
|
+
* - A transaction opened on one session never continues on the next:
|
|
34
|
+
* statements after a reconnect reject until the owner closes it.
|
|
35
|
+
* - An idle session is probed on a heartbeat; a probe that times out
|
|
36
|
+
* destroys the socket, so a blackholed host is detected.
|
|
37
|
+
*
|
|
38
|
+
* Unknown properties (`processID`, `escapeIdentifier`, ...) resolve
|
|
39
|
+
* against the current native client, and `instanceof` checks against
|
|
40
|
+
* the native class hold, so existing callers keep working.
|
|
41
|
+
*/
|
|
42
|
+
declare class ResilientPostgresClient extends EventEmitter {
|
|
43
|
+
readonly id: string;
|
|
44
|
+
private readonly ClientClass;
|
|
45
|
+
private readonly options;
|
|
46
|
+
private readonly logger;
|
|
47
|
+
private readonly policy;
|
|
48
|
+
private current;
|
|
49
|
+
private lastNative;
|
|
50
|
+
private state;
|
|
51
|
+
private generation;
|
|
52
|
+
private attempts;
|
|
53
|
+
private lostAt;
|
|
54
|
+
private inflight;
|
|
55
|
+
private beating;
|
|
56
|
+
private txGeneration;
|
|
57
|
+
private txLostUntil;
|
|
58
|
+
private reconnectTimer;
|
|
59
|
+
private heartbeatTimer;
|
|
60
|
+
constructor(ClientClass: PostgresClassType, options: PostgresClientOptions, id: string, logger: ILogger, policy?: Partial<ResilientPostgresPolicy>);
|
|
61
|
+
/** Session generation; increments on every successful reconnect. */
|
|
62
|
+
get connectionGeneration(): number;
|
|
63
|
+
/** True while a live session is attached. */
|
|
64
|
+
get isConnected(): boolean;
|
|
65
|
+
/** pg compatibility: callers test these before issuing best-effort queries. */
|
|
66
|
+
get _ending(): boolean;
|
|
67
|
+
get _ended(): boolean;
|
|
68
|
+
/** The native client of the current session (undefined while reconnecting). */
|
|
69
|
+
getNativeClient(): PostgresClientType | undefined;
|
|
70
|
+
connect(): Promise<void>;
|
|
71
|
+
query(...args: any[]): any;
|
|
72
|
+
end(): Promise<void>;
|
|
73
|
+
/**
|
|
74
|
+
* The error for a statement issued without a live session. An ended
|
|
75
|
+
* client keeps pg's own message, which shutdown paths recognize; a
|
|
76
|
+
* reconnecting client raises a connection error whose message never
|
|
77
|
+
* matches those shutdown checks, so no caller mistakes an outage for
|
|
78
|
+
* a closed client and returns an empty result.
|
|
79
|
+
*/
|
|
80
|
+
private unavailableError;
|
|
81
|
+
/** Listener faults are logged; they never reach the socket or the reconnect loop. */
|
|
82
|
+
private safeEmit;
|
|
83
|
+
private execute;
|
|
84
|
+
private open;
|
|
85
|
+
private onLost;
|
|
86
|
+
private scheduleReconnect;
|
|
87
|
+
private reconnect;
|
|
88
|
+
private startHeartbeat;
|
|
89
|
+
private stopHeartbeat;
|
|
90
|
+
/** Probe an idle session; a busy session is proving itself already. */
|
|
91
|
+
private beat;
|
|
92
|
+
/** End a native client without ever waiting on a dead socket. */
|
|
93
|
+
private endNative;
|
|
94
|
+
}
|
|
95
|
+
export { ResilientPostgresClient };
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ResilientPostgresClient = void 0;
|
|
4
|
+
const events_1 = require("events");
|
|
5
|
+
const enums_1 = require("../../../modules/enums");
|
|
6
|
+
const errors_1 = require("../../../modules/errors");
|
|
7
|
+
const health_1 = require("../health");
|
|
8
|
+
/** A statement that opens a multi-statement transaction on the session. */
|
|
9
|
+
const TX_OPEN = /^\s*(BEGIN|START\s+TRANSACTION)\b[^;]*;?\s*$/i;
|
|
10
|
+
/** A statement that closes the session's open transaction. */
|
|
11
|
+
const TX_CLOSE = /^\s*(COMMIT|END|ROLLBACK|ABORT)\b/i;
|
|
12
|
+
const TX_ROLLBACK = /^\s*(ROLLBACK|ABORT)\b/i;
|
|
13
|
+
/** Bound on awaiting a native client's `end()`; a dead socket never blocks shutdown. */
|
|
14
|
+
const END_TIMEOUT_MS = 5000;
|
|
15
|
+
const noop = () => undefined;
|
|
16
|
+
function resolvePolicy(policy = {}) {
|
|
17
|
+
return {
|
|
18
|
+
reconnectBaseMs: policy.reconnectBaseMs ?? enums_1.HMSH_PG_RECONNECT_BASE_MS,
|
|
19
|
+
reconnectMaxMs: policy.reconnectMaxMs ?? enums_1.HMSH_PG_RECONNECT_MAX_MS,
|
|
20
|
+
heartbeatMs: policy.heartbeatMs ?? enums_1.HMSH_PG_HEARTBEAT_MS,
|
|
21
|
+
heartbeatTimeoutMs: policy.heartbeatTimeoutMs ?? enums_1.HMSH_PG_HEARTBEAT_TIMEOUT_MS,
|
|
22
|
+
txLostWindowMs: policy.txLostWindowMs ?? enums_1.HMSH_PG_TX_LOST_WINDOW_MS,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A PostgreSQL client that survives server restarts, failovers and
|
|
27
|
+
* dropped sockets.
|
|
28
|
+
*
|
|
29
|
+
* It is a stable object that owns exactly one native `pg.Client` at a
|
|
30
|
+
* time. Store, stream and sub services hold a reference to this object
|
|
31
|
+
* for their lifetime, so the native socket underneath can be replaced
|
|
32
|
+
* without any of them noticing.
|
|
33
|
+
*
|
|
34
|
+
* Contract:
|
|
35
|
+
* - A lost socket never emits an unhandled `'error'`. The wrapper
|
|
36
|
+
* re-emits `'error'` only when the caller registered a listener.
|
|
37
|
+
* - While reconnecting, `query()` rejects at once with a
|
|
38
|
+
* `HotMeshConnectionError`; callers already retry on query failure.
|
|
39
|
+
* - A failure caused by the connection (not by the statement) is
|
|
40
|
+
* always surfaced as a `HotMeshConnectionError`.
|
|
41
|
+
* - Reconnect uses full-jitter exponential backoff and never gives up
|
|
42
|
+
* until `end()`.
|
|
43
|
+
* - `'reconnected'` fires after every successful reconnect so LISTEN
|
|
44
|
+
* owners can re-arm their channels on the new session.
|
|
45
|
+
* - A transaction opened on one session never continues on the next:
|
|
46
|
+
* statements after a reconnect reject until the owner closes it.
|
|
47
|
+
* - An idle session is probed on a heartbeat; a probe that times out
|
|
48
|
+
* destroys the socket, so a blackholed host is detected.
|
|
49
|
+
*
|
|
50
|
+
* Unknown properties (`processID`, `escapeIdentifier`, ...) resolve
|
|
51
|
+
* against the current native client, and `instanceof` checks against
|
|
52
|
+
* the native class hold, so existing callers keep working.
|
|
53
|
+
*/
|
|
54
|
+
class ResilientPostgresClient extends events_1.EventEmitter {
|
|
55
|
+
constructor(ClientClass, options, id, logger, policy) {
|
|
56
|
+
super();
|
|
57
|
+
this.current = null;
|
|
58
|
+
//the most recent native session; answers property introspection while
|
|
59
|
+
//reconnecting (queries never use it)
|
|
60
|
+
this.lastNative = null;
|
|
61
|
+
this.state = 'idle';
|
|
62
|
+
this.generation = 0;
|
|
63
|
+
this.attempts = 0;
|
|
64
|
+
this.lostAt = 0;
|
|
65
|
+
this.inflight = 0;
|
|
66
|
+
this.beating = false;
|
|
67
|
+
this.txGeneration = null;
|
|
68
|
+
this.txLostUntil = 0;
|
|
69
|
+
this.ClientClass = ClientClass;
|
|
70
|
+
this.options = options;
|
|
71
|
+
this.id = id;
|
|
72
|
+
this.logger = logger;
|
|
73
|
+
this.policy = resolvePolicy(policy);
|
|
74
|
+
const nativePrototype = ClientClass?.prototype;
|
|
75
|
+
const nativeOf = (target) => target.current ?? target.lastNative;
|
|
76
|
+
return new Proxy(this, {
|
|
77
|
+
get(target, prop, receiver) {
|
|
78
|
+
if (prop in target) {
|
|
79
|
+
return Reflect.get(target, prop, receiver);
|
|
80
|
+
}
|
|
81
|
+
const native = nativeOf(target);
|
|
82
|
+
const value = native?.[prop];
|
|
83
|
+
return typeof value === 'function' ? value.bind(native) : value;
|
|
84
|
+
},
|
|
85
|
+
has(target, prop) {
|
|
86
|
+
const native = nativeOf(target);
|
|
87
|
+
return prop in target || (native ? prop in native : false);
|
|
88
|
+
},
|
|
89
|
+
//provider detection and serializers read own keys (`database`,
|
|
90
|
+
//`connection`); expose the native client's alongside the wrapper's
|
|
91
|
+
ownKeys(target) {
|
|
92
|
+
const keys = new Set(Reflect.ownKeys(target));
|
|
93
|
+
const native = nativeOf(target);
|
|
94
|
+
if (native) {
|
|
95
|
+
for (const key of Reflect.ownKeys(native))
|
|
96
|
+
keys.add(key);
|
|
97
|
+
}
|
|
98
|
+
return Array.from(keys);
|
|
99
|
+
},
|
|
100
|
+
getOwnPropertyDescriptor(target, prop) {
|
|
101
|
+
const own = Reflect.getOwnPropertyDescriptor(target, prop);
|
|
102
|
+
if (own) {
|
|
103
|
+
return own;
|
|
104
|
+
}
|
|
105
|
+
const native = nativeOf(target);
|
|
106
|
+
const descriptor = native
|
|
107
|
+
? Reflect.getOwnPropertyDescriptor(native, prop)
|
|
108
|
+
: undefined;
|
|
109
|
+
//a key the target does not own must be reported configurable
|
|
110
|
+
return descriptor ? { ...descriptor, configurable: true } : undefined;
|
|
111
|
+
},
|
|
112
|
+
getPrototypeOf(target) {
|
|
113
|
+
return nativePrototype ?? Reflect.getPrototypeOf(target);
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** Session generation; increments on every successful reconnect. */
|
|
118
|
+
get connectionGeneration() {
|
|
119
|
+
return this.generation;
|
|
120
|
+
}
|
|
121
|
+
/** True while a live session is attached. */
|
|
122
|
+
get isConnected() {
|
|
123
|
+
return this.state === 'connected';
|
|
124
|
+
}
|
|
125
|
+
/** pg compatibility: callers test these before issuing best-effort queries. */
|
|
126
|
+
get _ending() {
|
|
127
|
+
return this.state === 'ended';
|
|
128
|
+
}
|
|
129
|
+
get _ended() {
|
|
130
|
+
return this.state === 'ended';
|
|
131
|
+
}
|
|
132
|
+
/** The native client of the current session (undefined while reconnecting). */
|
|
133
|
+
getNativeClient() {
|
|
134
|
+
return this.current ?? undefined;
|
|
135
|
+
}
|
|
136
|
+
async connect() {
|
|
137
|
+
if (this.state !== 'idle') {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
this.state = 'connecting';
|
|
141
|
+
try {
|
|
142
|
+
this.current = await this.open();
|
|
143
|
+
this.lastNative = this.current;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
this.state = 'idle';
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
this.state = 'connected';
|
|
150
|
+
health_1.ConnectionHealth.register(this.id);
|
|
151
|
+
this.startHeartbeat();
|
|
152
|
+
}
|
|
153
|
+
query(...args) {
|
|
154
|
+
const callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
|
155
|
+
// submittables (cursors, streams) are driven by the native client
|
|
156
|
+
if (args[0] && typeof args[0].submit === 'function') {
|
|
157
|
+
if (!this.current) {
|
|
158
|
+
throw this.unavailableError();
|
|
159
|
+
}
|
|
160
|
+
const passthrough = callback ? [...args, callback] : args;
|
|
161
|
+
return this.current.query(...passthrough);
|
|
162
|
+
}
|
|
163
|
+
const result = this.execute(args);
|
|
164
|
+
if (callback) {
|
|
165
|
+
result.then((value) => callback(null, value), (error) => callback(error));
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
async end() {
|
|
171
|
+
if (this.state === 'ended') {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
this.state = 'ended';
|
|
175
|
+
if (this.reconnectTimer) {
|
|
176
|
+
clearTimeout(this.reconnectTimer);
|
|
177
|
+
this.reconnectTimer = undefined;
|
|
178
|
+
}
|
|
179
|
+
this.stopHeartbeat();
|
|
180
|
+
health_1.ConnectionHealth.unregister(this.id);
|
|
181
|
+
const client = this.current;
|
|
182
|
+
this.current = null;
|
|
183
|
+
if (client) {
|
|
184
|
+
await this.endNative(client);
|
|
185
|
+
}
|
|
186
|
+
this.safeEmit('end');
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The error for a statement issued without a live session. An ended
|
|
190
|
+
* client keeps pg's own message, which shutdown paths recognize; a
|
|
191
|
+
* reconnecting client raises a connection error whose message never
|
|
192
|
+
* matches those shutdown checks, so no caller mistakes an outage for
|
|
193
|
+
* a closed client and returns an empty result.
|
|
194
|
+
*/
|
|
195
|
+
unavailableError() {
|
|
196
|
+
if (this.state === 'ended') {
|
|
197
|
+
return new Error('Client was closed and is not queryable');
|
|
198
|
+
}
|
|
199
|
+
return new errors_1.HotMeshConnectionError(`postgres-client-${this.state}`, this.id);
|
|
200
|
+
}
|
|
201
|
+
/** Listener faults are logged; they never reach the socket or the reconnect loop. */
|
|
202
|
+
safeEmit(event, payload) {
|
|
203
|
+
try {
|
|
204
|
+
this.emit(event, payload);
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
this.logger.error('postgres-client-listener-error', {
|
|
208
|
+
connectionId: this.id,
|
|
209
|
+
event,
|
|
210
|
+
error,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
async execute(args) {
|
|
215
|
+
const text = typeof args[0] === 'string' ? args[0] : args[0]?.text;
|
|
216
|
+
const statement = typeof text === 'string' ? text : '';
|
|
217
|
+
if (this.txGeneration !== null && this.txGeneration !== this.generation) {
|
|
218
|
+
if (Date.now() > this.txLostUntil) {
|
|
219
|
+
this.txGeneration = null;
|
|
220
|
+
}
|
|
221
|
+
else if (TX_CLOSE.test(statement)) {
|
|
222
|
+
this.txGeneration = null;
|
|
223
|
+
if (TX_ROLLBACK.test(statement)) {
|
|
224
|
+
//the server already rolled the lost session back
|
|
225
|
+
return { rows: [], rowCount: 0, command: 'ROLLBACK' };
|
|
226
|
+
}
|
|
227
|
+
throw new errors_1.HotMeshConnectionError('postgres-transaction-lost', this.id);
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
throw new errors_1.HotMeshConnectionError('postgres-transaction-lost', this.id);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const client = this.current;
|
|
234
|
+
if (this.state !== 'connected' || !client) {
|
|
235
|
+
throw this.unavailableError();
|
|
236
|
+
}
|
|
237
|
+
const generation = this.generation;
|
|
238
|
+
if (TX_OPEN.test(statement)) {
|
|
239
|
+
this.txGeneration = generation;
|
|
240
|
+
}
|
|
241
|
+
else if (TX_CLOSE.test(statement)) {
|
|
242
|
+
this.txGeneration = null;
|
|
243
|
+
}
|
|
244
|
+
this.inflight++;
|
|
245
|
+
try {
|
|
246
|
+
return await client.query(...args);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
if (error instanceof errors_1.HotMeshConnectionError ||
|
|
250
|
+
client !== this.current ||
|
|
251
|
+
this.state !== 'connected' ||
|
|
252
|
+
(0, errors_1.isConnectionError)(error)) {
|
|
253
|
+
//state changes across the await; an ended client keeps pg's error
|
|
254
|
+
if (this._ended) {
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
throw new errors_1.HotMeshConnectionError('postgres-session-lost', this.id, error);
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
this.inflight--;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async open() {
|
|
266
|
+
const client = new this.ClientClass(this.options);
|
|
267
|
+
client.on('error', (error) => this.onLost(client, error));
|
|
268
|
+
client.on('end', () => this.onLost(client, new Error('Connection terminated unexpectedly')));
|
|
269
|
+
client.on('notification', (message) => this.safeEmit('notification', message));
|
|
270
|
+
client.on('notice', (message) => this.safeEmit('notice', message));
|
|
271
|
+
try {
|
|
272
|
+
await client.connect();
|
|
273
|
+
await client.query('SELECT 1');
|
|
274
|
+
return client;
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
void this.endNative(client);
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
onLost(client, error) {
|
|
282
|
+
if (client !== this.current || this.state !== 'connected') {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
this.state = 'reconnecting';
|
|
286
|
+
this.current = null;
|
|
287
|
+
this.lostAt = Date.now();
|
|
288
|
+
this.attempts = 0;
|
|
289
|
+
this.stopHeartbeat();
|
|
290
|
+
const code = error?.code;
|
|
291
|
+
this.logger.warn('postgres-connection-lost', {
|
|
292
|
+
connectionId: this.id,
|
|
293
|
+
generation: this.generation,
|
|
294
|
+
error: error?.message,
|
|
295
|
+
code,
|
|
296
|
+
});
|
|
297
|
+
health_1.ConnectionHealth.markLost({
|
|
298
|
+
connectionId: this.id,
|
|
299
|
+
at: this.lostAt,
|
|
300
|
+
error: { message: error?.message, code },
|
|
301
|
+
});
|
|
302
|
+
if (this.listenerCount('error') > 0) {
|
|
303
|
+
this.safeEmit('error', error);
|
|
304
|
+
}
|
|
305
|
+
void this.endNative(client);
|
|
306
|
+
this.scheduleReconnect();
|
|
307
|
+
}
|
|
308
|
+
scheduleReconnect() {
|
|
309
|
+
if (this.state !== 'reconnecting') {
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
const ceiling = Math.min(this.policy.reconnectMaxMs, this.policy.reconnectBaseMs * 2 ** Math.min(this.attempts, 30));
|
|
313
|
+
const delay = Math.round(Math.random() * ceiling);
|
|
314
|
+
this.reconnectTimer = setTimeout(() => {
|
|
315
|
+
this.reconnectTimer = undefined;
|
|
316
|
+
void this.reconnect();
|
|
317
|
+
}, delay);
|
|
318
|
+
//a pending reconnect never holds a finished process open
|
|
319
|
+
this.reconnectTimer.unref?.();
|
|
320
|
+
}
|
|
321
|
+
async reconnect() {
|
|
322
|
+
if (this.state !== 'reconnecting') {
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
this.attempts++;
|
|
326
|
+
let client;
|
|
327
|
+
try {
|
|
328
|
+
client = await this.open();
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (this.state === 'reconnecting') {
|
|
332
|
+
this.logger.debug('postgres-reconnect-failed', {
|
|
333
|
+
connectionId: this.id,
|
|
334
|
+
attempts: this.attempts,
|
|
335
|
+
error: error?.message,
|
|
336
|
+
});
|
|
337
|
+
this.scheduleReconnect();
|
|
338
|
+
}
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (this.state !== 'reconnecting') {
|
|
342
|
+
//ended while the session was opening
|
|
343
|
+
void this.endNative(client);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
this.current = client;
|
|
347
|
+
this.lastNative = client;
|
|
348
|
+
this.generation++;
|
|
349
|
+
this.state = 'connected';
|
|
350
|
+
if (this.txGeneration !== null) {
|
|
351
|
+
this.txLostUntil = Date.now() + this.policy.txLostWindowMs;
|
|
352
|
+
}
|
|
353
|
+
const now = Date.now();
|
|
354
|
+
const restored = {
|
|
355
|
+
connectionId: this.id,
|
|
356
|
+
at: now,
|
|
357
|
+
downtimeMs: now - this.lostAt,
|
|
358
|
+
attempts: this.attempts,
|
|
359
|
+
};
|
|
360
|
+
this.logger.info('postgres-connection-restored', {
|
|
361
|
+
...restored,
|
|
362
|
+
generation: this.generation,
|
|
363
|
+
});
|
|
364
|
+
health_1.ConnectionHealth.markRestored(restored);
|
|
365
|
+
this.startHeartbeat();
|
|
366
|
+
this.safeEmit('reconnected', { ...restored, generation: this.generation });
|
|
367
|
+
}
|
|
368
|
+
startHeartbeat() {
|
|
369
|
+
this.stopHeartbeat();
|
|
370
|
+
if (this.policy.heartbeatMs <= 0) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
this.heartbeatTimer = setInterval(() => {
|
|
374
|
+
void this.beat();
|
|
375
|
+
}, this.policy.heartbeatMs);
|
|
376
|
+
this.heartbeatTimer.unref?.();
|
|
377
|
+
}
|
|
378
|
+
stopHeartbeat() {
|
|
379
|
+
if (this.heartbeatTimer) {
|
|
380
|
+
clearInterval(this.heartbeatTimer);
|
|
381
|
+
this.heartbeatTimer = undefined;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/** Probe an idle session; a busy session is proving itself already. */
|
|
385
|
+
async beat() {
|
|
386
|
+
const client = this.current;
|
|
387
|
+
if (this.state !== 'connected' ||
|
|
388
|
+
!client ||
|
|
389
|
+
this.inflight > 0 ||
|
|
390
|
+
this.beating) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
this.beating = true;
|
|
394
|
+
let timer;
|
|
395
|
+
try {
|
|
396
|
+
await Promise.race([
|
|
397
|
+
client.query('SELECT 1'),
|
|
398
|
+
new Promise((_, reject) => {
|
|
399
|
+
timer = setTimeout(() => reject(new Error('postgres-heartbeat-timeout')), this.policy.heartbeatTimeoutMs);
|
|
400
|
+
}),
|
|
401
|
+
]);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
if (client === this.current && this.state === 'connected') {
|
|
405
|
+
this.logger.warn('postgres-heartbeat-failed', {
|
|
406
|
+
connectionId: this.id,
|
|
407
|
+
error: error?.message,
|
|
408
|
+
});
|
|
409
|
+
this.onLost(client, error);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
finally {
|
|
413
|
+
if (timer) {
|
|
414
|
+
clearTimeout(timer);
|
|
415
|
+
}
|
|
416
|
+
this.beating = false;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/** End a native client without ever waiting on a dead socket. */
|
|
420
|
+
async endNative(client) {
|
|
421
|
+
let timer;
|
|
422
|
+
try {
|
|
423
|
+
await Promise.race([
|
|
424
|
+
Promise.resolve(client.end()).catch(noop),
|
|
425
|
+
new Promise((resolve) => {
|
|
426
|
+
timer = setTimeout(() => {
|
|
427
|
+
try {
|
|
428
|
+
client.connection?.stream?.destroy?.();
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
//already destroyed
|
|
432
|
+
}
|
|
433
|
+
resolve();
|
|
434
|
+
}, END_TIMEOUT_MS);
|
|
435
|
+
timer.unref?.();
|
|
436
|
+
}),
|
|
437
|
+
]);
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
if (timer) {
|
|
441
|
+
clearTimeout(timer);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
exports.ResilientPostgresClient = ResilientPostgresClient;
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { AbstractConnection } from '..';
|
|
2
2
|
import { PostgresClientOptions, PostgresClientType, PostgresClassType, PostgresPoolClientType } from '../../../types/postgres';
|
|
3
|
+
/**
|
|
4
|
+
* Connection defaults HotMesh applies to the clients it creates. Only
|
|
5
|
+
* keys the caller left unset are filled; an explicit caller value
|
|
6
|
+
* (including `connectionString` parameters) always wins.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withConnectionDefaults(options: PostgresClientOptions): PostgresClientOptions;
|
|
3
9
|
declare class PostgresConnection extends AbstractConnection<PostgresClassType, PostgresClientOptions> {
|
|
4
10
|
defaultOptions: PostgresClientOptions;
|
|
5
11
|
protected static poolClientInstances: Set<PostgresPoolClientType>;
|
|
@@ -1,8 +1,47 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.PostgresConnection = void 0;
|
|
3
|
+
exports.PostgresConnection = exports.withConnectionDefaults = void 0;
|
|
4
4
|
const __1 = require("..");
|
|
5
5
|
const utils_1 = require("../../../modules/utils");
|
|
6
|
+
const enums_1 = require("../../../modules/enums");
|
|
7
|
+
const postgres_resilient_client_1 = require("./postgres-resilient-client");
|
|
8
|
+
/**
|
|
9
|
+
* Connection defaults HotMesh applies to the clients it creates. Only
|
|
10
|
+
* keys the caller left unset are filled; an explicit caller value
|
|
11
|
+
* (including `connectionString` parameters) always wins.
|
|
12
|
+
*/
|
|
13
|
+
function withConnectionDefaults(options) {
|
|
14
|
+
const resolved = { ...options };
|
|
15
|
+
if (resolved.connectionTimeoutMillis === undefined &&
|
|
16
|
+
enums_1.HMSH_PG_CONNECT_TIMEOUT_MS > 0) {
|
|
17
|
+
resolved.connectionTimeoutMillis = enums_1.HMSH_PG_CONNECT_TIMEOUT_MS;
|
|
18
|
+
}
|
|
19
|
+
if (resolved.keepAlive === undefined) {
|
|
20
|
+
resolved.keepAlive = true;
|
|
21
|
+
}
|
|
22
|
+
if (resolved.keepAliveInitialDelayMillis === undefined) {
|
|
23
|
+
resolved.keepAliveInitialDelayMillis = enums_1.HMSH_PG_KEEPALIVE_DELAY_MS;
|
|
24
|
+
}
|
|
25
|
+
if (resolved.application_name === undefined) {
|
|
26
|
+
resolved.application_name = 'hotmesh';
|
|
27
|
+
}
|
|
28
|
+
return resolved;
|
|
29
|
+
}
|
|
30
|
+
exports.withConnectionDefaults = withConnectionDefaults;
|
|
31
|
+
/** Attach a logging `'error'` listener to an emitter that has none. */
|
|
32
|
+
function guardErrors(target, label) {
|
|
33
|
+
if (target &&
|
|
34
|
+
typeof target.on === 'function' &&
|
|
35
|
+
typeof target.listenerCount === 'function' &&
|
|
36
|
+
target.listenerCount('error') === 0) {
|
|
37
|
+
target.on('error', (error) => {
|
|
38
|
+
__1.AbstractConnection.logger.warn(label, {
|
|
39
|
+
error: error?.message,
|
|
40
|
+
code: error?.code,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
6
45
|
class PostgresConnection extends __1.AbstractConnection {
|
|
7
46
|
constructor() {
|
|
8
47
|
super(...arguments);
|
|
@@ -75,13 +114,24 @@ class PostgresConnection extends __1.AbstractConnection {
|
|
|
75
114
|
PostgresConnection.isPoolClient(clientConstructor)) {
|
|
76
115
|
// It's a PoolClient
|
|
77
116
|
connection = clientConstructor;
|
|
117
|
+
//an idle pooled client that loses its socket is re-emitted on the
|
|
118
|
+
//pool; never let that reach an unhandled 'error' event
|
|
119
|
+
guardErrors(clientConstructor, 'postgres-pool-client-lost');
|
|
78
120
|
if (config.connect) {
|
|
79
121
|
const client = await clientConstructor.connect();
|
|
122
|
+
//a checked-out client has no pool listener while it is held
|
|
123
|
+
guardErrors(client, 'postgres-pool-held-client-lost');
|
|
80
124
|
//register the connection singularly to be 'released' later
|
|
81
125
|
PostgresConnection.poolClientInstances.add(client);
|
|
82
126
|
this.poolClientInstance = client;
|
|
83
127
|
}
|
|
84
128
|
}
|
|
129
|
+
else if (enums_1.HMSH_PG_RESILIENT) {
|
|
130
|
+
// It's a Client: wrap it so the session survives restarts
|
|
131
|
+
const resilient = new postgres_resilient_client_1.ResilientPostgresClient(clientConstructor, withConnectionDefaults(options), this.id ?? (0, utils_1.guid)(), PostgresConnection.logger);
|
|
132
|
+
await resilient.connect();
|
|
133
|
+
connection = resilient;
|
|
134
|
+
}
|
|
85
135
|
else {
|
|
86
136
|
// It's a Client
|
|
87
137
|
connection = new clientConstructor(options);
|
|
@@ -119,26 +169,34 @@ class PostgresConnection extends __1.AbstractConnection {
|
|
|
119
169
|
//this.logConnectionStats();
|
|
120
170
|
if (!this.disconnecting) {
|
|
121
171
|
this.disconnecting = true;
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
172
|
+
try {
|
|
173
|
+
// Clear the reuse caches first so no caller is handed a closing connection
|
|
174
|
+
this.taskQueueConnections.clear();
|
|
175
|
+
this.instances.clear();
|
|
176
|
+
await this.disconnectPoolClients();
|
|
177
|
+
await this.disconnectConnections();
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
this.disconnecting = false;
|
|
181
|
+
}
|
|
129
182
|
}
|
|
130
183
|
}
|
|
131
184
|
static async disconnectPoolClients() {
|
|
132
|
-
Array.from(this.poolClientInstances.values())
|
|
133
|
-
instance.release();
|
|
134
|
-
});
|
|
185
|
+
const clients = Array.from(this.poolClientInstances.values());
|
|
135
186
|
this.poolClientInstances.clear();
|
|
187
|
+
for (const instance of clients) {
|
|
188
|
+
try {
|
|
189
|
+
instance.release();
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
this.logger.debug('postgres-pool-client-release-error', { error });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
136
195
|
}
|
|
137
196
|
static async disconnectConnections() {
|
|
138
|
-
Array.from(this.connectionInstances.values())
|
|
139
|
-
instance.end();
|
|
140
|
-
});
|
|
197
|
+
const connections = Array.from(this.connectionInstances.values());
|
|
141
198
|
this.connectionInstances.clear();
|
|
199
|
+
await Promise.allSettled(connections.map((instance) => Promise.resolve().then(() => instance.end())));
|
|
142
200
|
}
|
|
143
201
|
async closeConnection(connection) {
|
|
144
202
|
//no-op (handled by disconnectAll)
|