@hotmeshio/hotmesh 0.31.3 → 0.33.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/build/package.json +1 -1
- package/build/services/dba/index.d.ts +86 -0
- package/build/services/dba/index.js +119 -0
- package/build/services/dba/retention/batch.d.ts +7 -0
- package/build/services/dba/retention/batch.js +170 -0
- package/build/services/dba/retention/index.d.ts +4 -0
- package/build/services/dba/retention/index.js +12 -0
- package/build/services/dba/retention/overview.d.ts +6 -0
- package/build/services/dba/retention/overview.js +52 -0
- package/build/services/dba/retention/pressure.d.ts +9 -0
- package/build/services/dba/retention/pressure.js +58 -0
- package/build/services/dba/retention/session.d.ts +25 -0
- package/build/services/dba/retention/session.js +87 -0
- package/build/services/dba/retention/sql.d.ts +55 -0
- package/build/services/dba/retention/sql.js +188 -0
- package/build/services/dba/retention/survey.d.ts +6 -0
- package/build/services/dba/retention/survey.js +289 -0
- package/build/services/durable/workflow/condition.d.ts +20 -0
- package/build/services/durable/workflow/condition.js +20 -0
- package/build/services/escalations/batch.d.ts +4 -2
- package/build/services/escalations/batch.js +32 -2
- package/build/services/escalations/client.d.ts +11 -2
- package/build/services/escalations/client.js +12 -3
- package/build/services/escalations/fold.d.ts +2 -1
- package/build/services/escalations/fold.js +8 -1
- package/build/services/escalations/index.d.ts +1 -1
- package/build/services/escalations/index.js +5 -1
- package/build/services/store/providers/postgres/postgres.js +37 -7
- package/build/types/dba.d.ts +3 -0
- package/build/types/hmsh_escalations.d.ts +42 -6
- package/build/types/hmsh_escalations.js +19 -2
- package/build/types/index.d.ts +2 -1
- package/build/types/index.js +5 -1
- package/build/types/retention.d.ts +282 -0
- package/build/types/retention.js +2 -0
- package/package.json +1 -1
package/build/package.json
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PruneOptions, PruneResult } from '../../types/dba';
|
|
2
|
+
import { DeleteRetentionBatchOptions, ReadRetentionOverviewOptions, ReadRetentionPressureOptions, RetentionApp, RetentionBatchResult, RetentionOverview, RetentionPressure, RetentionSurvey, SurveyRetentionOptions } from '../../types/retention';
|
|
2
3
|
import { PostgresClientType } from '../../types/postgres';
|
|
3
4
|
/**
|
|
4
5
|
* Database maintenance operations for HotMesh's Postgres backend.
|
|
@@ -24,6 +25,31 @@ import { PostgresClientType } from '../../types/postgres';
|
|
|
24
25
|
* - {@link DBA.deploy | deploy()} — Pre-deploys the Postgres function
|
|
25
26
|
* (e.g., during CI/CD migrations) without running a prune.
|
|
26
27
|
*
|
|
28
|
+
* ## Guided retention
|
|
29
|
+
*
|
|
30
|
+
* For large tables, four methods let a caller survey first and then
|
|
31
|
+
* delete in small, paced batches it controls. They run plain
|
|
32
|
+
* parameterized SQL on a client the caller owns: no DDL, no deployed
|
|
33
|
+
* functions, no schema changes.
|
|
34
|
+
*
|
|
35
|
+
* - {@link DBA.discoverRetentionApps | discoverRetentionApps()} — app
|
|
36
|
+
* schemas that hold jobs and stream tables
|
|
37
|
+
* - {@link DBA.surveyRetention | surveyRetention()} — what a walk would
|
|
38
|
+
* delete and keep, with storage and health, in one snapshot
|
|
39
|
+
* - {@link DBA.deleteRetentionBatch | deleteRetentionBatch()} — one
|
|
40
|
+
* bounded, oldest-first batch; `rehearse` rolls it back
|
|
41
|
+
* - {@link DBA.readRetentionPressure | readRetentionPressure()} —
|
|
42
|
+
* backlog, replication lag, blocked sessions and dead rows
|
|
43
|
+
* - {@link DBA.readRetentionOverview | readRetentionOverview()} — sizes
|
|
44
|
+
* and the oldest settled row per target, from indexes and statistics
|
|
45
|
+
*
|
|
46
|
+
* A job is eligible only when it finished, its engine retention
|
|
47
|
+
* (`expired_at`) ended before the frozen `asOf`, it completed
|
|
48
|
+
* (`updated_at`) before `before`, no pending escalation names its
|
|
49
|
+
* workflow, and its root or parent workflow is not running. A stream
|
|
50
|
+
* message is eligible when it was processed before `before` and is not
|
|
51
|
+
* dead-lettered unless asked.
|
|
52
|
+
*
|
|
27
53
|
* ## Attribute stripping preserves export history
|
|
28
54
|
*
|
|
29
55
|
* Stripping removes `adata`, `hmark`, `status`, and `other` attributes
|
|
@@ -178,6 +204,10 @@ declare class DBA {
|
|
|
178
204
|
* 'myapp',
|
|
179
205
|
* );
|
|
180
206
|
* ```
|
|
207
|
+
*
|
|
208
|
+
* @deprecated Use the guided retention methods: {@link DBA.surveyRetention}
|
|
209
|
+
* to plan and {@link DBA.deleteRetentionBatch} to delete in bounded,
|
|
210
|
+
* oldest-first batches. They run plain SQL with no deployed function or DDL.
|
|
181
211
|
*/
|
|
182
212
|
static deploy(connection: PruneOptions['connection'], appId: string): Promise<void>;
|
|
183
213
|
/**
|
|
@@ -218,7 +248,63 @@ declare class DBA {
|
|
|
218
248
|
* entities: ['book'],
|
|
219
249
|
* });
|
|
220
250
|
* ```
|
|
251
|
+
*
|
|
252
|
+
* @deprecated Use the guided retention methods: {@link DBA.surveyRetention}
|
|
253
|
+
* to plan and {@link DBA.deleteRetentionBatch} to delete in bounded,
|
|
254
|
+
* oldest-first batches. They run plain SQL with no deployed function or DDL.
|
|
221
255
|
*/
|
|
222
256
|
static prune(options: PruneOptions): Promise<PruneResult>;
|
|
257
|
+
/**
|
|
258
|
+
* Lists app schemas that hold retention tables (`jobs`,
|
|
259
|
+
* `engine_streams`, `worker_streams`).
|
|
260
|
+
*/
|
|
261
|
+
static discoverRetentionApps(client: PostgresClientType): Promise<RetentionApp[]>;
|
|
262
|
+
/**
|
|
263
|
+
* Counts what a batch walk over each criteria would delete and keep,
|
|
264
|
+
* by reason, in one read-only snapshot, with storage statistics and
|
|
265
|
+
* database health. Deletes nothing.
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* ```typescript
|
|
269
|
+
* const survey = await DBA.surveyRetention({
|
|
270
|
+
* appId: 'durable',
|
|
271
|
+
* client,
|
|
272
|
+
* criteria: [{ target: 'jobs', before: '2026-06-01T00:00:00Z' }],
|
|
273
|
+
* });
|
|
274
|
+
* ```
|
|
275
|
+
*/
|
|
276
|
+
static surveyRetention(options: SurveyRetentionOptions): Promise<RetentionSurvey>;
|
|
277
|
+
/**
|
|
278
|
+
* Deletes one bounded batch of eligible rows, oldest first, in one
|
|
279
|
+
* transaction with its own lock and statement timeouts. Pass the
|
|
280
|
+
* returned `watermark` as `after` to continue. With `rehearse: true`
|
|
281
|
+
* the transaction rolls back, which measures cost without deleting.
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```typescript
|
|
285
|
+
* let after = null;
|
|
286
|
+
* do {
|
|
287
|
+
* const batch = await DBA.deleteRetentionBatch({
|
|
288
|
+
* appId: 'durable', client, limit: 200, after,
|
|
289
|
+
* criteria: { target: 'jobs', before, asOf },
|
|
290
|
+
* });
|
|
291
|
+
* after = batch.watermark;
|
|
292
|
+
* if (batch.done) break;
|
|
293
|
+
* } while (true);
|
|
294
|
+
* ```
|
|
295
|
+
*/
|
|
296
|
+
static deleteRetentionBatch(options: DeleteRetentionBatchOptions): Promise<RetentionBatchResult>;
|
|
297
|
+
/**
|
|
298
|
+
* Reads table sizes, dead rows and the oldest settled row for every
|
|
299
|
+
* target using index probes and statistics only. Cheap enough for a
|
|
300
|
+
* dashboard to call on every visit.
|
|
301
|
+
*/
|
|
302
|
+
static readRetentionOverview(options: ReadRetentionOverviewOptions): Promise<RetentionOverview>;
|
|
303
|
+
/**
|
|
304
|
+
* Reads the signals a caller checks between batches: engine backlog,
|
|
305
|
+
* replication slot lag, sessions waiting on `blockerPid`, and dead
|
|
306
|
+
* rows per target.
|
|
307
|
+
*/
|
|
308
|
+
static readRetentionPressure(options: ReadRetentionPressureOptions): Promise<RetentionPressure>;
|
|
223
309
|
}
|
|
224
310
|
export { DBA };
|
|
@@ -1,8 +1,32 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
2
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
26
|
exports.DBA = void 0;
|
|
4
27
|
const utils_1 = require("../../modules/utils");
|
|
5
28
|
const postgres_1 = require("../connector/providers/postgres");
|
|
29
|
+
const retention = __importStar(require("./retention"));
|
|
6
30
|
/**
|
|
7
31
|
* Database maintenance operations for HotMesh's Postgres backend.
|
|
8
32
|
*
|
|
@@ -27,6 +51,31 @@ const postgres_1 = require("../connector/providers/postgres");
|
|
|
27
51
|
* - {@link DBA.deploy | deploy()} — Pre-deploys the Postgres function
|
|
28
52
|
* (e.g., during CI/CD migrations) without running a prune.
|
|
29
53
|
*
|
|
54
|
+
* ## Guided retention
|
|
55
|
+
*
|
|
56
|
+
* For large tables, four methods let a caller survey first and then
|
|
57
|
+
* delete in small, paced batches it controls. They run plain
|
|
58
|
+
* parameterized SQL on a client the caller owns: no DDL, no deployed
|
|
59
|
+
* functions, no schema changes.
|
|
60
|
+
*
|
|
61
|
+
* - {@link DBA.discoverRetentionApps | discoverRetentionApps()} — app
|
|
62
|
+
* schemas that hold jobs and stream tables
|
|
63
|
+
* - {@link DBA.surveyRetention | surveyRetention()} — what a walk would
|
|
64
|
+
* delete and keep, with storage and health, in one snapshot
|
|
65
|
+
* - {@link DBA.deleteRetentionBatch | deleteRetentionBatch()} — one
|
|
66
|
+
* bounded, oldest-first batch; `rehearse` rolls it back
|
|
67
|
+
* - {@link DBA.readRetentionPressure | readRetentionPressure()} —
|
|
68
|
+
* backlog, replication lag, blocked sessions and dead rows
|
|
69
|
+
* - {@link DBA.readRetentionOverview | readRetentionOverview()} — sizes
|
|
70
|
+
* and the oldest settled row per target, from indexes and statistics
|
|
71
|
+
*
|
|
72
|
+
* A job is eligible only when it finished, its engine retention
|
|
73
|
+
* (`expired_at`) ended before the frozen `asOf`, it completed
|
|
74
|
+
* (`updated_at`) before `before`, no pending escalation names its
|
|
75
|
+
* workflow, and its root or parent workflow is not running. A stream
|
|
76
|
+
* message is eligible when it was processed before `before` and is not
|
|
77
|
+
* dead-lettered unless asked.
|
|
78
|
+
*
|
|
30
79
|
* ## Attribute stripping preserves export history
|
|
31
80
|
*
|
|
32
81
|
* Stripping removes `adata`, `hmark`, `status`, and `other` attributes
|
|
@@ -354,6 +403,10 @@ class DBA {
|
|
|
354
403
|
* 'myapp',
|
|
355
404
|
* );
|
|
356
405
|
* ```
|
|
406
|
+
*
|
|
407
|
+
* @deprecated Use the guided retention methods: {@link DBA.surveyRetention}
|
|
408
|
+
* to plan and {@link DBA.deleteRetentionBatch} to delete in bounded,
|
|
409
|
+
* oldest-first batches. They run plain SQL with no deployed function or DDL.
|
|
357
410
|
*/
|
|
358
411
|
static async deploy(connection, appId) {
|
|
359
412
|
const schema = DBA.safeName(appId);
|
|
@@ -419,6 +472,10 @@ class DBA {
|
|
|
419
472
|
* entities: ['book'],
|
|
420
473
|
* });
|
|
421
474
|
* ```
|
|
475
|
+
*
|
|
476
|
+
* @deprecated Use the guided retention methods: {@link DBA.surveyRetention}
|
|
477
|
+
* to plan and {@link DBA.deleteRetentionBatch} to delete in bounded,
|
|
478
|
+
* oldest-first batches. They run plain SQL with no deployed function or DDL.
|
|
422
479
|
*/
|
|
423
480
|
static async prune(options) {
|
|
424
481
|
const schema = DBA.safeName(options.appId);
|
|
@@ -459,5 +516,67 @@ class DBA {
|
|
|
459
516
|
await release();
|
|
460
517
|
}
|
|
461
518
|
}
|
|
519
|
+
/**
|
|
520
|
+
* Lists app schemas that hold retention tables (`jobs`,
|
|
521
|
+
* `engine_streams`, `worker_streams`).
|
|
522
|
+
*/
|
|
523
|
+
static async discoverRetentionApps(client) {
|
|
524
|
+
return retention.discoverRetentionApps(client);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Counts what a batch walk over each criteria would delete and keep,
|
|
528
|
+
* by reason, in one read-only snapshot, with storage statistics and
|
|
529
|
+
* database health. Deletes nothing.
|
|
530
|
+
*
|
|
531
|
+
* @example
|
|
532
|
+
* ```typescript
|
|
533
|
+
* const survey = await DBA.surveyRetention({
|
|
534
|
+
* appId: 'durable',
|
|
535
|
+
* client,
|
|
536
|
+
* criteria: [{ target: 'jobs', before: '2026-06-01T00:00:00Z' }],
|
|
537
|
+
* });
|
|
538
|
+
* ```
|
|
539
|
+
*/
|
|
540
|
+
static async surveyRetention(options) {
|
|
541
|
+
return retention.surveyRetention(DBA.safeName(options.appId), options);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Deletes one bounded batch of eligible rows, oldest first, in one
|
|
545
|
+
* transaction with its own lock and statement timeouts. Pass the
|
|
546
|
+
* returned `watermark` as `after` to continue. With `rehearse: true`
|
|
547
|
+
* the transaction rolls back, which measures cost without deleting.
|
|
548
|
+
*
|
|
549
|
+
* @example
|
|
550
|
+
* ```typescript
|
|
551
|
+
* let after = null;
|
|
552
|
+
* do {
|
|
553
|
+
* const batch = await DBA.deleteRetentionBatch({
|
|
554
|
+
* appId: 'durable', client, limit: 200, after,
|
|
555
|
+
* criteria: { target: 'jobs', before, asOf },
|
|
556
|
+
* });
|
|
557
|
+
* after = batch.watermark;
|
|
558
|
+
* if (batch.done) break;
|
|
559
|
+
* } while (true);
|
|
560
|
+
* ```
|
|
561
|
+
*/
|
|
562
|
+
static async deleteRetentionBatch(options) {
|
|
563
|
+
return retention.deleteRetentionBatch(DBA.safeName(options.appId), options);
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Reads table sizes, dead rows and the oldest settled row for every
|
|
567
|
+
* target using index probes and statistics only. Cheap enough for a
|
|
568
|
+
* dashboard to call on every visit.
|
|
569
|
+
*/
|
|
570
|
+
static async readRetentionOverview(options) {
|
|
571
|
+
return retention.readRetentionOverview(DBA.safeName(options.appId), options);
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Reads the signals a caller checks between batches: engine backlog,
|
|
575
|
+
* replication slot lag, sessions waiting on `blockerPid`, and dead
|
|
576
|
+
* rows per target.
|
|
577
|
+
*/
|
|
578
|
+
static async readRetentionPressure(options) {
|
|
579
|
+
return retention.readRetentionPressure(DBA.safeName(options.appId), options);
|
|
580
|
+
}
|
|
462
581
|
}
|
|
463
582
|
exports.DBA = DBA;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { DeleteRetentionBatchOptions, RetentionBatchResult } from '../../../types/retention';
|
|
2
|
+
/**
|
|
3
|
+
* Deletes one bounded batch, oldest first, in a single transaction.
|
|
4
|
+
* Jobs are locked, their attributes deleted in one statement, then the
|
|
5
|
+
* jobs themselves. With `rehearse` the transaction rolls back.
|
|
6
|
+
*/
|
|
7
|
+
export declare function deleteRetentionBatch(schema: string, options: DeleteRetentionBatchOptions): Promise<RetentionBatchResult>;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.deleteRetentionBatch = void 0;
|
|
4
|
+
const sql_1 = require("./sql");
|
|
5
|
+
const session_1 = require("./session");
|
|
6
|
+
const MAX_BATCH = 100000;
|
|
7
|
+
/**
|
|
8
|
+
* Deletes one bounded batch, oldest first, in a single transaction.
|
|
9
|
+
* Jobs are locked, their attributes deleted in one statement, then the
|
|
10
|
+
* jobs themselves. With `rehearse` the transaction rolls back.
|
|
11
|
+
*/
|
|
12
|
+
async function deleteRetentionBatch(schema, options) {
|
|
13
|
+
const { client, criteria, limit } = options;
|
|
14
|
+
(0, session_1.assertTarget)(criteria.target);
|
|
15
|
+
(0, session_1.assertPositiveInt)('limit', limit, MAX_BATCH);
|
|
16
|
+
const minimumAgeDays = options.minimumAgeDays ?? 0;
|
|
17
|
+
if (!Number.isInteger(minimumAgeDays) || minimumAgeDays < 0) {
|
|
18
|
+
throw new Error(`minimumAgeDays must be a whole number of days, 0 or more; received ${minimumAgeDays}`);
|
|
19
|
+
}
|
|
20
|
+
if (!criteria.asOf) {
|
|
21
|
+
throw new Error('criteria.asOf is required so every batch shares one frozen scope');
|
|
22
|
+
}
|
|
23
|
+
const rehearse = options.rehearse === true;
|
|
24
|
+
const hasEscalations = criteria.target === 'jobs' || criteria.target === 'escalations'
|
|
25
|
+
? await (0, session_1.hasEscalationsTable)(client)
|
|
26
|
+
: false;
|
|
27
|
+
if (criteria.target === 'escalations' && !hasEscalations) {
|
|
28
|
+
throw new Error(`${sql_1.ESCALATIONS_TABLE} is missing; escalations cannot be deleted`);
|
|
29
|
+
}
|
|
30
|
+
const started = performance.now();
|
|
31
|
+
const outcome = await (0, session_1.withTransaction)(client, {
|
|
32
|
+
lockTimeoutMs: options.lockTimeoutMs ?? 2000,
|
|
33
|
+
statementTimeoutMs: options.statementTimeoutMs ?? 30000,
|
|
34
|
+
rollback: rehearse,
|
|
35
|
+
}, () => criteria.target === 'jobs'
|
|
36
|
+
? deleteJobs(client, schema, options, hasEscalations)
|
|
37
|
+
: criteria.target === 'escalations'
|
|
38
|
+
? deleteEscalations(client, options)
|
|
39
|
+
: deleteStreamMessages(client, schema, options));
|
|
40
|
+
return {
|
|
41
|
+
target: criteria.target,
|
|
42
|
+
deleted: outcome.deleted,
|
|
43
|
+
attributesDeleted: outcome.attributesDeleted,
|
|
44
|
+
watermark: outcome.watermark ?? options.after ?? null,
|
|
45
|
+
done: outcome.visited < limit,
|
|
46
|
+
rehearsed: rehearse,
|
|
47
|
+
ms: Math.round(performance.now() - started),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
exports.deleteRetentionBatch = deleteRetentionBatch;
|
|
51
|
+
async function deleteJobs(client, schema, options, hasEscalations) {
|
|
52
|
+
const { criteria, after, limit } = options;
|
|
53
|
+
const params = [
|
|
54
|
+
criteria.before,
|
|
55
|
+
criteria.asOf,
|
|
56
|
+
limit,
|
|
57
|
+
options.minimumAgeDays ?? 0,
|
|
58
|
+
];
|
|
59
|
+
const keyset = after ? (0, sql_1.jobsAfter)('$5', '$6') : '';
|
|
60
|
+
if (after)
|
|
61
|
+
params.push(after.at, after.id);
|
|
62
|
+
// 1. Lock the oldest eligible jobs; rows another session holds are skipped
|
|
63
|
+
const { rows } = await client.query(`SELECT j.id::text AS id, ${(0, sql_1.iso)('j.expired_at')} AS at
|
|
64
|
+
FROM ${schema}.jobs j
|
|
65
|
+
WHERE ${(0, sql_1.jobsEligible)(schema, '$1', '$2', hasEscalations)}
|
|
66
|
+
AND j.updated_at < now() - ($4::int * interval '1 day')
|
|
67
|
+
${keyset}
|
|
68
|
+
ORDER BY j.expired_at, j.id
|
|
69
|
+
LIMIT $3
|
|
70
|
+
FOR UPDATE OF j SKIP LOCKED`, params);
|
|
71
|
+
if (rows.length === 0) {
|
|
72
|
+
return { deleted: 0, attributesDeleted: 0, watermark: null, visited: 0 };
|
|
73
|
+
}
|
|
74
|
+
const ids = rows.map((row) => row.id);
|
|
75
|
+
// 2. Attributes in one statement, then the jobs
|
|
76
|
+
const attributes = await client.query(`DELETE FROM ${schema}.jobs_attributes WHERE job_id = ANY ($1::uuid[])`, [ids]);
|
|
77
|
+
const jobs = await client.query(`DELETE FROM ${schema}.jobs WHERE id = ANY ($1::uuid[])`, [ids]);
|
|
78
|
+
const last = rows[rows.length - 1];
|
|
79
|
+
return {
|
|
80
|
+
deleted: (0, session_1.toNumber)(jobs.rowCount),
|
|
81
|
+
attributesDeleted: (0, session_1.toNumber)(attributes.rowCount),
|
|
82
|
+
watermark: { at: last.at, id: last.id },
|
|
83
|
+
visited: rows.length,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function deleteEscalations(client, options) {
|
|
87
|
+
const { criteria, after, limit } = options;
|
|
88
|
+
const params = [
|
|
89
|
+
options.appId,
|
|
90
|
+
criteria.before,
|
|
91
|
+
criteria.asOf,
|
|
92
|
+
limit,
|
|
93
|
+
options.minimumAgeDays ?? 0,
|
|
94
|
+
];
|
|
95
|
+
const keyset = after ? (0, sql_1.escalationsAfter)('$6', '$7') : '';
|
|
96
|
+
if (after)
|
|
97
|
+
params.push(after.at, after.id);
|
|
98
|
+
// 1. Lock the oldest ended escalations; rows another session holds are skipped
|
|
99
|
+
const { rows } = await client.query(`SELECT e.id::text AS id, ${(0, sql_1.iso)(sql_1.ENDED_AT)} AS at
|
|
100
|
+
FROM ${sql_1.ESCALATIONS_TABLE} e
|
|
101
|
+
WHERE ${(0, sql_1.escalationsEligible)('$1', '$2', '$3', criteria.references ?? [])}
|
|
102
|
+
AND ${sql_1.ENDED_AT} < now() - ($5::int * interval '1 day')
|
|
103
|
+
${keyset}
|
|
104
|
+
ORDER BY ${sql_1.ENDED_AT}, e.id
|
|
105
|
+
LIMIT $4
|
|
106
|
+
FOR UPDATE OF e SKIP LOCKED`, params);
|
|
107
|
+
if (rows.length === 0) {
|
|
108
|
+
return { deleted: 0, attributesDeleted: 0, watermark: null, visited: 0 };
|
|
109
|
+
}
|
|
110
|
+
// 2. Delete the locked rows, still ended
|
|
111
|
+
const deleted = await client.query(`DELETE FROM ${sql_1.ESCALATIONS_TABLE}
|
|
112
|
+
WHERE id = ANY ($1::uuid[]) AND status <> 'pending'`, [rows.map((row) => row.id)]);
|
|
113
|
+
const last = rows[rows.length - 1];
|
|
114
|
+
return {
|
|
115
|
+
deleted: (0, session_1.toNumber)(deleted.rowCount),
|
|
116
|
+
attributesDeleted: 0,
|
|
117
|
+
watermark: { at: last.at, id: last.id },
|
|
118
|
+
visited: rows.length,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
async function deleteStreamMessages(client, schema, options) {
|
|
122
|
+
const { criteria, after, limit } = options;
|
|
123
|
+
const table = `${schema}.${criteria.target}`;
|
|
124
|
+
const params = [
|
|
125
|
+
criteria.before,
|
|
126
|
+
criteria.asOf,
|
|
127
|
+
criteria.includeDeadLettered === true,
|
|
128
|
+
limit,
|
|
129
|
+
options.minimumAgeDays ?? 0,
|
|
130
|
+
];
|
|
131
|
+
const keyset = after ? (0, sql_1.streamsAfter)('$6', '$7', '$8') : '';
|
|
132
|
+
if (after)
|
|
133
|
+
params.push(after.at, after.stream ?? '', after.id);
|
|
134
|
+
const { rows } = await client.query(`WITH visited AS (
|
|
135
|
+
SELECT s.stream_name, s.id, s.expired_at
|
|
136
|
+
FROM ${table} s
|
|
137
|
+
WHERE ${(0, sql_1.streamsEligible)('$1', '$2', '$3')}
|
|
138
|
+
AND s.expired_at < now() - ($5::int * interval '1 day')
|
|
139
|
+
${keyset}
|
|
140
|
+
ORDER BY s.expired_at, s.stream_name, s.id
|
|
141
|
+
LIMIT $4
|
|
142
|
+
),
|
|
143
|
+
removed AS (
|
|
144
|
+
DELETE FROM ${table} t
|
|
145
|
+
USING visited v
|
|
146
|
+
WHERE t.stream_name = v.stream_name AND t.id = v.id
|
|
147
|
+
RETURNING 1
|
|
148
|
+
),
|
|
149
|
+
last AS (
|
|
150
|
+
SELECT ${(0, sql_1.iso)('expired_at')} AS at, stream_name, id::text AS id
|
|
151
|
+
FROM visited
|
|
152
|
+
ORDER BY expired_at DESC, stream_name DESC, id DESC
|
|
153
|
+
LIMIT 1
|
|
154
|
+
)
|
|
155
|
+
SELECT
|
|
156
|
+
(SELECT count(*) FROM removed)::bigint AS deleted,
|
|
157
|
+
(SELECT count(*) FROM visited)::bigint AS visited,
|
|
158
|
+
last.at, last.stream_name, last.id
|
|
159
|
+
FROM (SELECT 1) one
|
|
160
|
+
LEFT JOIN last ON true`, params);
|
|
161
|
+
const row = rows[0];
|
|
162
|
+
return {
|
|
163
|
+
deleted: (0, session_1.toNumber)(row.deleted),
|
|
164
|
+
attributesDeleted: 0,
|
|
165
|
+
watermark: row.at
|
|
166
|
+
? { at: row.at, id: row.id, stream: row.stream_name }
|
|
167
|
+
: null,
|
|
168
|
+
visited: (0, session_1.toNumber)(row.visited),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readRetentionOverview = exports.discoverRetentionApps = exports.readRetentionPressure = exports.deleteRetentionBatch = exports.surveyRetention = void 0;
|
|
4
|
+
var survey_1 = require("./survey");
|
|
5
|
+
Object.defineProperty(exports, "surveyRetention", { enumerable: true, get: function () { return survey_1.surveyRetention; } });
|
|
6
|
+
var batch_1 = require("./batch");
|
|
7
|
+
Object.defineProperty(exports, "deleteRetentionBatch", { enumerable: true, get: function () { return batch_1.deleteRetentionBatch; } });
|
|
8
|
+
var pressure_1 = require("./pressure");
|
|
9
|
+
Object.defineProperty(exports, "readRetentionPressure", { enumerable: true, get: function () { return pressure_1.readRetentionPressure; } });
|
|
10
|
+
Object.defineProperty(exports, "discoverRetentionApps", { enumerable: true, get: function () { return pressure_1.discoverRetentionApps; } });
|
|
11
|
+
var overview_1 = require("./overview");
|
|
12
|
+
Object.defineProperty(exports, "readRetentionOverview", { enumerable: true, get: function () { return overview_1.readRetentionOverview; } });
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ReadRetentionOverviewOptions, RetentionOverview } from '../../../types/retention';
|
|
2
|
+
/**
|
|
3
|
+
* Sizes, dead rows and the oldest settled row per target. Every read is
|
|
4
|
+
* an index probe or a statistics lookup, so it is safe to call often.
|
|
5
|
+
*/
|
|
6
|
+
export declare function readRetentionOverview(schema: string, options: ReadRetentionOverviewOptions): Promise<RetentionOverview>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readRetentionOverview = void 0;
|
|
4
|
+
const sql_1 = require("./sql");
|
|
5
|
+
const session_1 = require("./session");
|
|
6
|
+
/** The oldest settled row of a target, read from the index that orders it. */
|
|
7
|
+
function oldestSQL(schema, target) {
|
|
8
|
+
if (target === 'jobs') {
|
|
9
|
+
return `SELECT ${(0, sql_1.iso)('updated_at')} AS oldest FROM ${schema}.jobs
|
|
10
|
+
WHERE expired_at IS NOT NULL ORDER BY expired_at LIMIT 1`;
|
|
11
|
+
}
|
|
12
|
+
if (target === 'escalations') {
|
|
13
|
+
return `SELECT ${(0, sql_1.iso)(sql_1.ENDED_AT)} AS oldest FROM ${sql_1.ESCALATIONS_TABLE} e
|
|
14
|
+
WHERE e.app_id = $1 AND e.status <> 'pending'
|
|
15
|
+
AND e.status IN ('resolved', 'cancelled', 'expired')
|
|
16
|
+
ORDER BY ${sql_1.ENDED_AT} LIMIT 1`;
|
|
17
|
+
}
|
|
18
|
+
return `SELECT ${(0, sql_1.iso)('expired_at')} AS oldest FROM ${schema}.${target}
|
|
19
|
+
WHERE expired_at IS NOT NULL ORDER BY expired_at LIMIT 1`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Sizes, dead rows and the oldest settled row per target. Every read is
|
|
23
|
+
* an index probe or a statistics lookup, so it is safe to call often.
|
|
24
|
+
*/
|
|
25
|
+
async function readRetentionOverview(schema, options) {
|
|
26
|
+
const { client } = options;
|
|
27
|
+
const clock = await client.query(`SELECT ${(0, sql_1.iso)('now()')} AS now`);
|
|
28
|
+
const hasEscalations = await (0, session_1.hasEscalationsTable)(client);
|
|
29
|
+
const targets = [];
|
|
30
|
+
for (const target of sql_1.RETENTION_TARGETS) {
|
|
31
|
+
if (target === 'escalations' && !hasEscalations)
|
|
32
|
+
continue;
|
|
33
|
+
const oldest = await client.query(oldestSQL(schema, target), target === 'escalations' ? [options.appId] : []);
|
|
34
|
+
targets.push({
|
|
35
|
+
target,
|
|
36
|
+
oldest: oldest.rows[0]?.oldest ?? null,
|
|
37
|
+
tables: await (0, session_1.readTablesStats)(client, (0, sql_1.tablesFor)(schema, target)),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const backlog = await client.query((0, sql_1.backlogSQL)(schema));
|
|
41
|
+
return {
|
|
42
|
+
appId: options.appId,
|
|
43
|
+
schema,
|
|
44
|
+
readAt: clock.rows[0].now,
|
|
45
|
+
targets,
|
|
46
|
+
backlog: {
|
|
47
|
+
engine: (0, session_1.toNumber)(backlog.rows[0].engine),
|
|
48
|
+
worker: (0, session_1.toNumber)(backlog.rows[0].worker),
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
exports.readRetentionOverview = readRetentionOverview;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ReadRetentionPressureOptions, RetentionApp, RetentionPressure } from '../../../types/retention';
|
|
2
|
+
import { PostgresClientType } from '../../../types/postgres';
|
|
3
|
+
/**
|
|
4
|
+
* Signals to check between batches: engine backlog, replication lag,
|
|
5
|
+
* sessions waiting on the deleting backend, and dead rows per target.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readRetentionPressure(schema: string, options: ReadRetentionPressureOptions): Promise<RetentionPressure>;
|
|
8
|
+
/** HotMesh app schemas that hold retention tables. */
|
|
9
|
+
export declare function discoverRetentionApps(client: PostgresClientType): Promise<RetentionApp[]>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.discoverRetentionApps = exports.readRetentionPressure = void 0;
|
|
4
|
+
const sql_1 = require("./sql");
|
|
5
|
+
const session_1 = require("./session");
|
|
6
|
+
/**
|
|
7
|
+
* Signals to check between batches: engine backlog, replication lag,
|
|
8
|
+
* sessions waiting on the deleting backend, and dead rows per target.
|
|
9
|
+
*/
|
|
10
|
+
async function readRetentionPressure(schema, options) {
|
|
11
|
+
const { client, blockerPid } = options;
|
|
12
|
+
const clock = await client.query(`SELECT ${(0, sql_1.iso)('now()')} AS now`);
|
|
13
|
+
const backlog = await client.query((0, sql_1.backlogSQL)(schema));
|
|
14
|
+
const slots = await (0, session_1.readReplicationSlots)(client);
|
|
15
|
+
const blocked = blockerPid
|
|
16
|
+
? await client.query(`SELECT count(*)::int AS waiting FROM pg_stat_activity
|
|
17
|
+
WHERE $1::int = ANY (pg_blocking_pids(pid))`, [blockerPid])
|
|
18
|
+
: { rows: [{ waiting: 0 }] };
|
|
19
|
+
const hasEscalations = await (0, session_1.hasEscalationsTable)(client);
|
|
20
|
+
const deadRows = {};
|
|
21
|
+
for (const target of sql_1.RETENTION_TARGETS) {
|
|
22
|
+
if (target === 'escalations' && !hasEscalations) {
|
|
23
|
+
deadRows[target] = 0;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const stats = await (0, session_1.readTablesStats)(client, (0, sql_1.tablesFor)(schema, target));
|
|
27
|
+
deadRows[target] = stats.reduce((sum, s) => sum + s.deadRows, 0);
|
|
28
|
+
}
|
|
29
|
+
const lags = (slots ?? [])
|
|
30
|
+
.map((slot) => slot.lagBytes)
|
|
31
|
+
.filter((lag) => lag != null);
|
|
32
|
+
return {
|
|
33
|
+
backlog: {
|
|
34
|
+
engine: (0, session_1.toNumber)(backlog.rows[0].engine),
|
|
35
|
+
worker: (0, session_1.toNumber)(backlog.rows[0].worker),
|
|
36
|
+
},
|
|
37
|
+
maxReplicationLagBytes: slots == null ? null : lags.length ? Math.max(...lags) : 0,
|
|
38
|
+
blockedSessions: (0, session_1.toNumber)(blocked.rows[0].waiting),
|
|
39
|
+
deadRows,
|
|
40
|
+
readAt: clock.rows[0].now,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
exports.readRetentionPressure = readRetentionPressure;
|
|
44
|
+
/** HotMesh app schemas that hold retention tables. */
|
|
45
|
+
async function discoverRetentionApps(client) {
|
|
46
|
+
const { rows } = await client.query(sql_1.discoverAppsSQL, [sql_1.SCHEMA_TARGETS]);
|
|
47
|
+
const escalations = await (0, session_1.hasEscalationsTable)(client);
|
|
48
|
+
return rows
|
|
49
|
+
.map((row) => {
|
|
50
|
+
const tables = row.tables.filter((t) => sql_1.SCHEMA_TARGETS.includes(t));
|
|
51
|
+
// The shared escalations table serves every app that has jobs.
|
|
52
|
+
if (escalations && tables.includes('jobs'))
|
|
53
|
+
tables.push('escalations');
|
|
54
|
+
return { schema: row.schema, tables };
|
|
55
|
+
})
|
|
56
|
+
.filter((app) => app.tables.length > 0);
|
|
57
|
+
}
|
|
58
|
+
exports.discoverRetentionApps = discoverRetentionApps;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { RetentionReplicationSlot, RetentionTableStats, RetentionTarget } from '../../../types/retention';
|
|
2
|
+
import { PostgresClientType } from '../../../types/postgres';
|
|
3
|
+
interface TransactionSettings {
|
|
4
|
+
readOnly?: boolean;
|
|
5
|
+
lockTimeoutMs?: number;
|
|
6
|
+
statementTimeoutMs?: number;
|
|
7
|
+
/** Roll back instead of committing (rehearsals). */
|
|
8
|
+
rollback?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function assertTarget(target: string): asserts target is RetentionTarget;
|
|
11
|
+
export declare function assertPositiveInt(name: string, value: number, max: number): void;
|
|
12
|
+
export declare const toNumber: (value: unknown) => number;
|
|
13
|
+
/**
|
|
14
|
+
* Runs `work` inside one transaction on the caller's client with
|
|
15
|
+
* transaction-scoped timeouts. Rolls back on error, or always when
|
|
16
|
+
* `rollback` is set.
|
|
17
|
+
*/
|
|
18
|
+
export declare function withTransaction<T>(client: PostgresClientType, settings: TransactionSettings, work: () => Promise<T>): Promise<T>;
|
|
19
|
+
export declare function hasEscalationsTable(client: PostgresClientType): Promise<boolean>;
|
|
20
|
+
export declare function readTableStats(client: PostgresClientType, table: string): Promise<RetentionTableStats>;
|
|
21
|
+
/** Statistics for several tables, read one after another on the client. */
|
|
22
|
+
export declare function readTablesStats(client: PostgresClientType, tables: string[]): Promise<RetentionTableStats[]>;
|
|
23
|
+
/** Slots and their WAL lag, or null when the role cannot read them. */
|
|
24
|
+
export declare function readReplicationSlots(client: PostgresClientType): Promise<RetentionReplicationSlot[] | null>;
|
|
25
|
+
export {};
|