@itphx/synth-storage-postgres 0.0.0-stage → 0.11.3
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 +18 -0
- package/LICENSE.ru.md +31 -0
- package/dist/errors.d.ts +71 -0
- package/dist/errors.js +126 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +34 -0
- package/dist/json-param.d.ts +14 -0
- package/dist/json-param.js +22 -0
- package/dist/locks.d.ts +104 -0
- package/dist/locks.js +201 -0
- package/dist/migrate.d.ts +58 -0
- package/dist/migrate.js +125 -0
- package/dist/migrations/001-init.d.ts +15 -0
- package/dist/migrations/001-init.js +457 -0
- package/dist/migrations/002-egress-audit.d.ts +12 -0
- package/dist/migrations/002-egress-audit.js +52 -0
- package/dist/migrations/003-analytics-rollups.d.ts +12 -0
- package/dist/migrations/003-analytics-rollups.js +21 -0
- package/dist/migrations/index.d.ts +23 -0
- package/dist/migrations/index.js +23 -0
- package/dist/pool.d.ts +178 -0
- package/dist/pool.js +382 -0
- package/dist/ports/analytics.d.ts +26 -0
- package/dist/ports/analytics.js +243 -0
- package/dist/ports/audit.d.ts +15 -0
- package/dist/ports/audit.js +189 -0
- package/dist/ports/content.d.ts +41 -0
- package/dist/ports/content.js +1539 -0
- package/dist/ports/core-sync.d.ts +31 -0
- package/dist/ports/core-sync.js +34 -0
- package/dist/ports/deps.d.ts +63 -0
- package/dist/ports/deps.js +19 -0
- package/dist/ports/events-bindings.d.ts +77 -0
- package/dist/ports/events-bindings.js +356 -0
- package/dist/ports/events-core.d.ts +35 -0
- package/dist/ports/events-core.js +71 -0
- package/dist/ports/events-journal.d.ts +68 -0
- package/dist/ports/events-journal.js +211 -0
- package/dist/ports/events-scheduler.d.ts +49 -0
- package/dist/ports/events-scheduler.js +231 -0
- package/dist/ports/events-webhooks.d.ts +64 -0
- package/dist/ports/events-webhooks.js +268 -0
- package/dist/ports/events.d.ts +20 -0
- package/dist/ports/events.js +27 -0
- package/dist/ports/principals-defaults.d.ts +21 -0
- package/dist/ports/principals-defaults.js +68 -0
- package/dist/ports/principals-documents.d.ts +23 -0
- package/dist/ports/principals-documents.js +38 -0
- package/dist/ports/principals-profiles.d.ts +21 -0
- package/dist/ports/principals-profiles.js +263 -0
- package/dist/ports/principals-projects.d.ts +19 -0
- package/dist/ports/principals-projects.js +158 -0
- package/dist/ports/principals-settings.d.ts +25 -0
- package/dist/ports/principals-settings.js +275 -0
- package/dist/ports/principals-shared.d.ts +33 -0
- package/dist/ports/principals-shared.js +44 -0
- package/dist/ports/principals.d.ts +27 -0
- package/dist/ports/principals.js +39 -0
- package/dist/ports/sessions-mapping.d.ts +237 -0
- package/dist/ports/sessions-mapping.js +405 -0
- package/dist/ports/sessions.d.ts +133 -0
- package/dist/ports/sessions.js +502 -0
- package/dist/ports/stub.d.ts +14 -0
- package/dist/ports/stub.js +32 -0
- package/dist/postgres-storage.d.ts +59 -0
- package/dist/postgres-storage.js +111 -0
- package/dist/schema.d.ts +13 -0
- package/dist/schema.js +22 -0
- package/dist/storage-context.d.ts +51 -0
- package/dist/storage-context.js +130 -0
- package/package.json +40 -3
- package/README.md +0 -3
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Общие примитивы PostgreSQL-реализации портов группы `events` (PROP-032, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Здесь только то, что переиспользуют файлы `events-*.ts`: ленивая загрузка core
|
|
5
|
+
* (доменные ошибки, крипто-хелперы), хелперы дат/чисел и деталь отображения
|
|
6
|
+
* секрета. Доменные типы берутся напрямую из `@itphx/synth-shared` (обычная
|
|
7
|
+
* зависимость драйвера, ADR-097), типы портов core — `import type` в файлах-группах.
|
|
8
|
+
*/
|
|
9
|
+
import { PostgresUniqueViolationError } from '../errors.js';
|
|
10
|
+
/** Длина видимой части секрета в `prefix` (`synth_evt_abcd…`/`whsec_abcd…`) — деталь отображения. */
|
|
11
|
+
export const SECRET_PREFIX_VISIBLE = 12;
|
|
12
|
+
let corePromise = null;
|
|
13
|
+
/**
|
|
14
|
+
* Ленивая загрузка `@itphx/synth-core`.
|
|
15
|
+
*
|
|
16
|
+
* Верхнеуровневый runtime-импорт core драйверу запрещён (ADR-097): core —
|
|
17
|
+
* `peerDependency`, а статический импорт не должен тянуть ядро при загрузке
|
|
18
|
+
* модуля драйвера (цикл core ↔ драйвер). Используется только внутри
|
|
19
|
+
* async-методов — для доменных классов ошибок (`EventApiKeyConflictError`,
|
|
20
|
+
* `WebhookConflictError`) и крипто-хелперов webhooks. Промис кэшируется; при
|
|
21
|
+
* ошибке кэш сбрасывается, чтобы следующий вызов повторил попытку.
|
|
22
|
+
*/
|
|
23
|
+
export function loadCore() {
|
|
24
|
+
if (!corePromise) {
|
|
25
|
+
corePromise = import('@itphx/synth-core').catch((err) => {
|
|
26
|
+
corePromise = null;
|
|
27
|
+
throw err;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
return corePromise;
|
|
31
|
+
}
|
|
32
|
+
// ── Хелперы ──────────────────────────────────────────────────────────────────
|
|
33
|
+
/** `timestamptz`/ISO → ISO-8601; `null`/`undefined` → `undefined`. */
|
|
34
|
+
export function toIso(value) {
|
|
35
|
+
if (value == null)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (value instanceof Date)
|
|
38
|
+
return value.toISOString();
|
|
39
|
+
return typeof value === 'string' ? value : String(value);
|
|
40
|
+
}
|
|
41
|
+
/** Обязательная дата: `null` недопустим (для `NOT NULL timestamptz`). */
|
|
42
|
+
export function toIsoRequired(value) {
|
|
43
|
+
return toIso(value) ?? new Date().toISOString();
|
|
44
|
+
}
|
|
45
|
+
/** `int8`/`int4`/numeric → число; `null` → `undefined`. */
|
|
46
|
+
export function toInt(value) {
|
|
47
|
+
if (value == null)
|
|
48
|
+
return undefined;
|
|
49
|
+
const n = typeof value === 'number' ? value : Number(value);
|
|
50
|
+
return Number.isFinite(n) ? n : undefined;
|
|
51
|
+
}
|
|
52
|
+
/** Убирает ключи со значением `undefined` — чистое доменное представление. */
|
|
53
|
+
export function compact(value) {
|
|
54
|
+
for (const key of Object.keys(value)) {
|
|
55
|
+
if (value[key] === undefined)
|
|
56
|
+
delete value[key];
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
/** Нарушение уникальности PG (в т.ч. `lower(label)`-индекс) → доменный конфликт. */
|
|
61
|
+
export function isUniqueViolation(err) {
|
|
62
|
+
if (err instanceof PostgresUniqueViolationError)
|
|
63
|
+
return true;
|
|
64
|
+
return (typeof err === 'object'
|
|
65
|
+
&& err !== null
|
|
66
|
+
&& err.code === 'STORAGE_POSTGRES_UNIQUE_VIOLATION');
|
|
67
|
+
}
|
|
68
|
+
/** Дни retention → SQL-выражение `now() - interval` (общий для журналов). */
|
|
69
|
+
export function retentionCutoffExpr(param = '$1') {
|
|
70
|
+
return `now() - interval '1 day' * ${param}::double precision`;
|
|
71
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PG-реализация append-журнала событий, одноразовых claim-кодов и дедупа
|
|
3
|
+
* (PROP-032, волна 3b): `eventJournal`/`identityClaims`/`dedup`.
|
|
4
|
+
*
|
|
5
|
+
* Семантика повторяет файловые реализации core (`EventJournalStore`,
|
|
6
|
+
* `IdentityClaimStore`, `FileDedupStore`): журнал — append-only (`seq bigserial`),
|
|
7
|
+
* `list(limit)` → последние N в порядке добавления; claim-код одноразовый
|
|
8
|
+
* (атомарный `UPDATE … WHERE consumed_at IS NULL`); дедуп — атомарный claim
|
|
9
|
+
* (`INSERT … ON CONFLICT DO NOTHING RETURNING`).
|
|
10
|
+
*/
|
|
11
|
+
import type { EventJournalEntry, IdentityClaimRecord, StorageContext } from '@itphx/synth-core';
|
|
12
|
+
import type { PortDeps } from './deps.js';
|
|
13
|
+
/** Часть `StorageContext`, которой владеет под-группа журнала/claim/дедупа. */
|
|
14
|
+
export type EventJournalPorts = Pick<StorageContext, 'eventJournal' | 'identityClaims' | 'dedup'>;
|
|
15
|
+
/**
|
|
16
|
+
* ADR-089: журнал обработанных внешних событий и решений Router. Append-only
|
|
17
|
+
* (`event_journal.seq`), `list(limit)` — последние N в порядке добавления.
|
|
18
|
+
*/
|
|
19
|
+
export declare class PgEventJournalRepository {
|
|
20
|
+
private readonly _deps;
|
|
21
|
+
constructor(_deps: PortDeps);
|
|
22
|
+
record(entry: EventJournalEntry): Promise<void>;
|
|
23
|
+
/** Записи в порядке добавления (старые → новые); `limit` — последние N. */
|
|
24
|
+
list(limit?: number): Promise<EventJournalEntry[]>;
|
|
25
|
+
/** Retention: удаляет записи старше `retentionDays` (по `ts`); число удалённых. */
|
|
26
|
+
prune(retentionDays: number): Promise<number>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* ADR-089 (claim-flow): хранилище одноразовых claim-кодов поверх
|
|
30
|
+
* `identity_claims`. `consume` — атомарный `UPDATE … WHERE consumed_at IS NULL
|
|
31
|
+
* AND expires_at > now()` (гонка не «съест» код дважды).
|
|
32
|
+
*/
|
|
33
|
+
export declare class PgIdentityClaimRepository {
|
|
34
|
+
private readonly _deps;
|
|
35
|
+
constructor(_deps: PortDeps);
|
|
36
|
+
create(input: {
|
|
37
|
+
provider: string;
|
|
38
|
+
externalId: string;
|
|
39
|
+
chatKey?: string;
|
|
40
|
+
principalId: string;
|
|
41
|
+
ttlSec?: number;
|
|
42
|
+
}): Promise<IdentityClaimRecord>;
|
|
43
|
+
consume(code: string, opts: {
|
|
44
|
+
userId: string;
|
|
45
|
+
provider?: string;
|
|
46
|
+
externalId?: string;
|
|
47
|
+
}): Promise<IdentityClaimRecord | null>;
|
|
48
|
+
/** Удаление мёртвых записей (истёкшие/потреблённые); число удалённых. */
|
|
49
|
+
cleanup(now?: number): Promise<number>;
|
|
50
|
+
/** Все записи; `activeOnly` — только живые (не потреблённые и не истёкшие). */
|
|
51
|
+
list(activeOnly?: boolean): Promise<IdentityClaimRecord[]>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* ADR-051/ADR-089: дедуп поверх `dedup(key text primary key)`.
|
|
55
|
+
*
|
|
56
|
+
* `tryClaim` — атомарный `INSERT … ON CONFLICT (key) DO NOTHING RETURNING key`:
|
|
57
|
+
* строка вернулась → ключ наш (`true`), иначе он уже занят (`false`). `seed` —
|
|
58
|
+
* no-op: durable-бэкенд хранит ключи сам (сигнатура порта синхронная, менять
|
|
59
|
+
* нельзя). Retention-очистку см. в отчёте (остаток).
|
|
60
|
+
*/
|
|
61
|
+
export declare class PgDedupRepository {
|
|
62
|
+
private readonly _deps;
|
|
63
|
+
constructor(_deps: PortDeps);
|
|
64
|
+
seed(_keys: Iterable<string>): void;
|
|
65
|
+
tryClaim(key: string): Promise<boolean>;
|
|
66
|
+
}
|
|
67
|
+
/** Собрать под-группу портов журнала/claim/дедупа. */
|
|
68
|
+
export declare function buildEventJournalPorts(deps: PortDeps): EventJournalPorts;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PG-реализация append-журнала событий, одноразовых claim-кодов и дедупа
|
|
3
|
+
* (PROP-032, волна 3b): `eventJournal`/`identityClaims`/`dedup`.
|
|
4
|
+
*
|
|
5
|
+
* Семантика повторяет файловые реализации core (`EventJournalStore`,
|
|
6
|
+
* `IdentityClaimStore`, `FileDedupStore`): журнал — append-only (`seq bigserial`),
|
|
7
|
+
* `list(limit)` → последние N в порядке добавления; claim-код одноразовый
|
|
8
|
+
* (атомарный `UPDATE … WHERE consumed_at IS NULL`); дедуп — атомарный claim
|
|
9
|
+
* (`INSERT … ON CONFLICT DO NOTHING RETURNING`).
|
|
10
|
+
*/
|
|
11
|
+
import { randomInt } from 'node:crypto';
|
|
12
|
+
import { jsonbParam } from '../json-param.js';
|
|
13
|
+
import { compact, loadCore, toIso, toIsoRequired } from './events-core.js';
|
|
14
|
+
/** Нормализация вводимого кода: верхний регистр, удаление дефисов/пробелов. */
|
|
15
|
+
function normalizeClaimCode(code) {
|
|
16
|
+
return code.toUpperCase().replace(/[^0-9A-Z]/g, '');
|
|
17
|
+
}
|
|
18
|
+
/** Канонический вид кода с дефисом: `ABCDEF` → `ABC-DEF`. */
|
|
19
|
+
function formatClaimCode(raw) {
|
|
20
|
+
const mid = Math.floor(raw.length / 2);
|
|
21
|
+
return `${raw.slice(0, mid)}-${raw.slice(mid)}`;
|
|
22
|
+
}
|
|
23
|
+
/** Генерация одного «сырого» кода (без дефиса) из алфавита/длины core. */
|
|
24
|
+
function generateClaimRaw(alphabet, length) {
|
|
25
|
+
let out = '';
|
|
26
|
+
for (let i = 0; i < length; i += 1) {
|
|
27
|
+
out += alphabet[randomInt(alphabet.length)];
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Восстановление записи журнала из колонок (полная запись больше не хранится
|
|
33
|
+
* внутри `payload`): `event` собирается из `id/ts/source/type/payload/identity/
|
|
34
|
+
* dedup_key`, остальные поля — из одноимённых колонок.
|
|
35
|
+
*/
|
|
36
|
+
function toJournalEntry(row) {
|
|
37
|
+
const ts = toIsoRequired(row.ts);
|
|
38
|
+
const event = {
|
|
39
|
+
id: row.id,
|
|
40
|
+
source: row.source ?? '',
|
|
41
|
+
type: row.type ?? 'message',
|
|
42
|
+
payload: row.payload ?? null,
|
|
43
|
+
identity: (row.identity ?? {}),
|
|
44
|
+
dedupKey: row.dedup_key ?? row.id,
|
|
45
|
+
ts,
|
|
46
|
+
};
|
|
47
|
+
return compact({
|
|
48
|
+
ts,
|
|
49
|
+
event,
|
|
50
|
+
decision: row.decision ?? undefined,
|
|
51
|
+
error: row.error ?? undefined,
|
|
52
|
+
keyId: row.key_id ?? undefined,
|
|
53
|
+
principalId: row.principal_id ?? undefined,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* ADR-089: журнал обработанных внешних событий и решений Router. Append-only
|
|
58
|
+
* (`event_journal.seq`), `list(limit)` — последние N в порядке добавления.
|
|
59
|
+
*/
|
|
60
|
+
export class PgEventJournalRepository {
|
|
61
|
+
_deps;
|
|
62
|
+
constructor(_deps) {
|
|
63
|
+
this._deps = _deps;
|
|
64
|
+
}
|
|
65
|
+
async record(entry) {
|
|
66
|
+
await this._deps.connection.query(`INSERT INTO event_journal
|
|
67
|
+
(id, ts, source, type, decision, key_id, identity, dedup_key, error, principal_id, payload)
|
|
68
|
+
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7::jsonb, $8, $9, $10, $11::jsonb)`, [
|
|
69
|
+
entry.event.id,
|
|
70
|
+
entry.ts,
|
|
71
|
+
entry.event.source,
|
|
72
|
+
entry.event.type,
|
|
73
|
+
entry.decision !== undefined ? jsonbParam(entry.decision) : null,
|
|
74
|
+
entry.keyId ?? null,
|
|
75
|
+
jsonbParam(entry.event.identity ?? {}),
|
|
76
|
+
entry.event.dedupKey ?? null,
|
|
77
|
+
entry.error ?? null,
|
|
78
|
+
entry.principalId ?? null,
|
|
79
|
+
entry.event.payload === undefined ? null : jsonbParam(entry.event.payload),
|
|
80
|
+
]);
|
|
81
|
+
}
|
|
82
|
+
/** Записи в порядке добавления (старые → новые); `limit` — последние N. */
|
|
83
|
+
async list(limit) {
|
|
84
|
+
const rows = limit !== undefined && Number.isFinite(limit) && limit > 0
|
|
85
|
+
? await this._deps.connection.query(`SELECT * FROM (
|
|
86
|
+
SELECT * FROM event_journal ORDER BY seq DESC LIMIT $1
|
|
87
|
+
) t ORDER BY seq ASC`, [Math.floor(limit)])
|
|
88
|
+
: await this._deps.connection.query('SELECT * FROM event_journal ORDER BY seq ASC');
|
|
89
|
+
return rows.map(toJournalEntry);
|
|
90
|
+
}
|
|
91
|
+
/** Retention: удаляет записи старше `retentionDays` (по `ts`); число удалённых. */
|
|
92
|
+
async prune(retentionDays) {
|
|
93
|
+
const days = Number.isFinite(retentionDays) ? retentionDays : 0;
|
|
94
|
+
const rows = await this._deps.connection.query(`DELETE FROM event_journal WHERE ts < now() - interval '1 day' * $1::double precision RETURNING seq`, [days]);
|
|
95
|
+
return rows.length;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Запись claim-кода из колонок (`principalId`/`chatKey` персистятся напрямую). */
|
|
99
|
+
function toClaim(row) {
|
|
100
|
+
return compact({
|
|
101
|
+
code: row.code,
|
|
102
|
+
provider: row.provider,
|
|
103
|
+
externalId: row.external_id,
|
|
104
|
+
chatKey: row.chat_key ?? undefined,
|
|
105
|
+
principalId: row.principal_id,
|
|
106
|
+
createdAt: toIsoRequired(row.created_at),
|
|
107
|
+
expiresAt: toIsoRequired(row.expires_at),
|
|
108
|
+
consumedAt: toIso(row.consumed_at),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* ADR-089 (claim-flow): хранилище одноразовых claim-кодов поверх
|
|
113
|
+
* `identity_claims`. `consume` — атомарный `UPDATE … WHERE consumed_at IS NULL
|
|
114
|
+
* AND expires_at > now()` (гонка не «съест» код дважды).
|
|
115
|
+
*/
|
|
116
|
+
export class PgIdentityClaimRepository {
|
|
117
|
+
_deps;
|
|
118
|
+
constructor(_deps) {
|
|
119
|
+
this._deps = _deps;
|
|
120
|
+
}
|
|
121
|
+
async create(input) {
|
|
122
|
+
const { IDENTITY_CLAIM_ALPHABET, IDENTITY_CLAIM_LENGTH, IDENTITY_CLAIM_TTL_SEC } = await loadCore();
|
|
123
|
+
const ttlSec = input.ttlSec ?? IDENTITY_CLAIM_TTL_SEC;
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
const createdAt = new Date(now).toISOString();
|
|
126
|
+
const expiresAt = new Date(now + ttlSec * 1000).toISOString();
|
|
127
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
128
|
+
const code = formatClaimCode(generateClaimRaw(IDENTITY_CLAIM_ALPHABET, IDENTITY_CLAIM_LENGTH));
|
|
129
|
+
const rows = await this._deps.connection.query(`INSERT INTO identity_claims
|
|
130
|
+
(code, provider, external_id, chat_key, principal_id, created_at, expires_at, consumed_at)
|
|
131
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, NULL)
|
|
132
|
+
ON CONFLICT (code) DO NOTHING
|
|
133
|
+
RETURNING *`, [code, input.provider, input.externalId, input.chatKey ?? null, input.principalId, createdAt, expiresAt]);
|
|
134
|
+
if (rows[0])
|
|
135
|
+
return toClaim(rows[0]);
|
|
136
|
+
}
|
|
137
|
+
throw new Error('не удалось сгенерировать уникальный claim-код');
|
|
138
|
+
}
|
|
139
|
+
async consume(code, opts) {
|
|
140
|
+
void opts.userId; // аудит подтвердившего — по `linkedBy` при linkIdentity
|
|
141
|
+
const normalized = normalizeClaimCode(code);
|
|
142
|
+
if (!normalized)
|
|
143
|
+
return null;
|
|
144
|
+
const params = [normalized];
|
|
145
|
+
let sql = `UPDATE identity_claims SET consumed_at = now()
|
|
146
|
+
WHERE regexp_replace(upper(code), '[^0-9A-Z]', '', 'g') = $1
|
|
147
|
+
AND consumed_at IS NULL
|
|
148
|
+
AND expires_at > now()`;
|
|
149
|
+
if (opts.provider) {
|
|
150
|
+
params.push(opts.provider);
|
|
151
|
+
sql += ` AND provider = $${params.length}`;
|
|
152
|
+
}
|
|
153
|
+
if (opts.externalId) {
|
|
154
|
+
params.push(opts.externalId);
|
|
155
|
+
sql += ` AND external_id = $${params.length}`;
|
|
156
|
+
}
|
|
157
|
+
sql += ' RETURNING *';
|
|
158
|
+
const rows = await this._deps.connection.query(sql, params);
|
|
159
|
+
return rows[0] ? toClaim(rows[0]) : null;
|
|
160
|
+
}
|
|
161
|
+
/** Удаление мёртвых записей (истёкшие/потреблённые); число удалённых. */
|
|
162
|
+
async cleanup(now = Date.now()) {
|
|
163
|
+
const { IDENTITY_CLAIM_TTL_SEC } = await loadCore();
|
|
164
|
+
const expiredBefore = new Date(now).toISOString();
|
|
165
|
+
const consumedBefore = new Date(now - IDENTITY_CLAIM_TTL_SEC * 1000).toISOString();
|
|
166
|
+
const rows = await this._deps.connection.query(`DELETE FROM identity_claims
|
|
167
|
+
WHERE expires_at <= $1
|
|
168
|
+
OR (consumed_at IS NOT NULL AND consumed_at < $2)
|
|
169
|
+
RETURNING code`, [expiredBefore, consumedBefore]);
|
|
170
|
+
return rows.length;
|
|
171
|
+
}
|
|
172
|
+
/** Все записи; `activeOnly` — только живые (не потреблённые и не истёкшие). */
|
|
173
|
+
async list(activeOnly = false) {
|
|
174
|
+
const rows = activeOnly
|
|
175
|
+
? await this._deps.connection.query(`SELECT * FROM identity_claims
|
|
176
|
+
WHERE consumed_at IS NULL AND expires_at > now()
|
|
177
|
+
ORDER BY created_at, code`)
|
|
178
|
+
: await this._deps.connection.query('SELECT * FROM identity_claims ORDER BY created_at, code');
|
|
179
|
+
return rows.map(toClaim);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// ── dedup ────────────────────────────────────────────────────────────────────
|
|
183
|
+
/**
|
|
184
|
+
* ADR-051/ADR-089: дедуп поверх `dedup(key text primary key)`.
|
|
185
|
+
*
|
|
186
|
+
* `tryClaim` — атомарный `INSERT … ON CONFLICT (key) DO NOTHING RETURNING key`:
|
|
187
|
+
* строка вернулась → ключ наш (`true`), иначе он уже занят (`false`). `seed` —
|
|
188
|
+
* no-op: durable-бэкенд хранит ключи сам (сигнатура порта синхронная, менять
|
|
189
|
+
* нельзя). Retention-очистку см. в отчёте (остаток).
|
|
190
|
+
*/
|
|
191
|
+
export class PgDedupRepository {
|
|
192
|
+
_deps;
|
|
193
|
+
constructor(_deps) {
|
|
194
|
+
this._deps = _deps;
|
|
195
|
+
}
|
|
196
|
+
seed(_keys) {
|
|
197
|
+
// durable-бэкенд: предзаполнение кэша не требуется
|
|
198
|
+
}
|
|
199
|
+
async tryClaim(key) {
|
|
200
|
+
const rows = await this._deps.connection.query('INSERT INTO dedup (key) VALUES ($1) ON CONFLICT (key) DO NOTHING RETURNING key', [key]);
|
|
201
|
+
return rows.length > 0;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/** Собрать под-группу портов журнала/claim/дедупа. */
|
|
205
|
+
export function buildEventJournalPorts(deps) {
|
|
206
|
+
return {
|
|
207
|
+
eventJournal: new PgEventJournalRepository(deps),
|
|
208
|
+
identityClaims: new PgIdentityClaimRepository(deps),
|
|
209
|
+
dedup: new PgDedupRepository(deps),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PG-реализация портов планировщика (PROP-032, волна 3b): `schedules`/`jobs`.
|
|
3
|
+
*
|
|
4
|
+
* Семантика повторяет файловые реализации core (`ScheduleStore`, `JobStore`):
|
|
5
|
+
* id `sch_<uuid>`, `updatedAt` при правке; `hasEnabledTargetFor` учитывает
|
|
6
|
+
* `enabled` и `target.mode !== 'ephemeral'` (SQL `EXISTS` по `target->>'sessionId'`);
|
|
7
|
+
* Job-история — append-only (`jobs.seq`), `list` — последние N в порядке добавления.
|
|
8
|
+
*/
|
|
9
|
+
import type { ScheduleRunUpdate, JobListOptions, StorageContext } from '@itphx/synth-core';
|
|
10
|
+
import { type Schedule, type ScheduleInput, type ScheduleJob } from '@itphx/synth-shared';
|
|
11
|
+
import type { PortDeps } from './deps.js';
|
|
12
|
+
/** Часть `StorageContext`, которой владеет под-группа планировщика. */
|
|
13
|
+
export type EventSchedulerPorts = Pick<StorageContext, 'schedules' | 'jobs'>;
|
|
14
|
+
/** ADR-051/ADR-089: реестр расписаний поверх `schedules`. */
|
|
15
|
+
export declare class PgScheduleRepository {
|
|
16
|
+
private readonly _deps;
|
|
17
|
+
constructor(_deps: PortDeps);
|
|
18
|
+
list(): Promise<Schedule[]>;
|
|
19
|
+
/**
|
|
20
|
+
* Есть ли включённое расписание, нацеленное на сессию (не `ephemeral`).
|
|
21
|
+
* `EXISTS` по `target->>'sessionId'` (индекс `schedules_enabled_idx`).
|
|
22
|
+
*/
|
|
23
|
+
hasEnabledTargetFor(sessionId: string): Promise<boolean>;
|
|
24
|
+
get(id: string): Promise<Schedule | null>;
|
|
25
|
+
/** Создаёт расписание: id `sch_<uuid>`, `createdAt`/`updatedAt` = now. */
|
|
26
|
+
create(input: ScheduleInput): Promise<Schedule>;
|
|
27
|
+
/** Обновляет расписание (partial-патч); `updatedAt` выставляется в now. */
|
|
28
|
+
update(id: string, patch: Partial<ScheduleInput>): Promise<Schedule | null>;
|
|
29
|
+
remove(id: string): Promise<boolean>;
|
|
30
|
+
/** Фиксация результата запуска (`updatedAt` не трогается). */
|
|
31
|
+
markRun(id: string, run: ScheduleRunUpdate): Promise<Schedule | null>;
|
|
32
|
+
/** Обновление только `nextRunAt` (служебное поле сервиса). */
|
|
33
|
+
setNextRun(id: string, nextRunAt: string | undefined): Promise<Schedule | null>;
|
|
34
|
+
}
|
|
35
|
+
/** ADR-051: append-only история срабатываний поверх `jobs`. */
|
|
36
|
+
export declare class PgJobRepository {
|
|
37
|
+
private readonly _deps;
|
|
38
|
+
constructor(_deps: PortDeps);
|
|
39
|
+
append(job: ScheduleJob): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* История в порядке добавления (старые → новые); фильтр `scheduleId`,
|
|
42
|
+
* `limit` — последние N.
|
|
43
|
+
*/
|
|
44
|
+
list(opts?: JobListOptions): Promise<ScheduleJob[]>;
|
|
45
|
+
/** Retention: удаляет записи старше `retentionDays` (по `startedAt`). */
|
|
46
|
+
prune(retentionDays: number): Promise<number>;
|
|
47
|
+
}
|
|
48
|
+
/** Собрать под-группу портов планировщика. */
|
|
49
|
+
export declare function buildEventSchedulerPorts(deps: PortDeps): EventSchedulerPorts;
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PG-реализация портов планировщика (PROP-032, волна 3b): `schedules`/`jobs`.
|
|
3
|
+
*
|
|
4
|
+
* Семантика повторяет файловые реализации core (`ScheduleStore`, `JobStore`):
|
|
5
|
+
* id `sch_<uuid>`, `updatedAt` при правке; `hasEnabledTargetFor` учитывает
|
|
6
|
+
* `enabled` и `target.mode !== 'ephemeral'` (SQL `EXISTS` по `target->>'sessionId'`);
|
|
7
|
+
* Job-история — append-only (`jobs.seq`), `list` — последние N в порядке добавления.
|
|
8
|
+
*/
|
|
9
|
+
import { generateId } from '@itphx/synth-shared';
|
|
10
|
+
import { jsonbParam } from '../json-param.js';
|
|
11
|
+
import { compact, toInt, toIso, toIsoRequired } from './events-core.js';
|
|
12
|
+
function toSchedule(row) {
|
|
13
|
+
return compact({
|
|
14
|
+
id: row.id,
|
|
15
|
+
name: row.name,
|
|
16
|
+
enabled: row.enabled,
|
|
17
|
+
cron: row.cron ?? undefined,
|
|
18
|
+
every: row.every ?? undefined,
|
|
19
|
+
target: (row.target ?? { mode: 'ephemeral' }),
|
|
20
|
+
prompt: row.prompt ?? undefined,
|
|
21
|
+
payload: (row.payload ?? undefined),
|
|
22
|
+
ownerId: row.owner_id ?? undefined,
|
|
23
|
+
catchUp: (row.catch_up ?? undefined),
|
|
24
|
+
createdAt: toIsoRequired(row.created_at),
|
|
25
|
+
updatedAt: toIsoRequired(row.updated_at),
|
|
26
|
+
lastRunAt: toIso(row.last_run_at),
|
|
27
|
+
nextRunAt: toIso(row.next_run_at),
|
|
28
|
+
lastStatus: (row.last_status ?? undefined),
|
|
29
|
+
lastError: row.last_error ?? undefined,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** ADR-051/ADR-089: реестр расписаний поверх `schedules`. */
|
|
33
|
+
export class PgScheduleRepository {
|
|
34
|
+
_deps;
|
|
35
|
+
constructor(_deps) {
|
|
36
|
+
this._deps = _deps;
|
|
37
|
+
}
|
|
38
|
+
async list() {
|
|
39
|
+
const rows = await this._deps.connection.query('SELECT * FROM schedules ORDER BY created_at, id');
|
|
40
|
+
return rows.map(toSchedule);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Есть ли включённое расписание, нацеленное на сессию (не `ephemeral`).
|
|
44
|
+
* `EXISTS` по `target->>'sessionId'` (индекс `schedules_enabled_idx`).
|
|
45
|
+
*/
|
|
46
|
+
async hasEnabledTargetFor(sessionId) {
|
|
47
|
+
const rows = await this._deps.connection.query(`SELECT EXISTS (
|
|
48
|
+
SELECT 1 FROM schedules
|
|
49
|
+
WHERE enabled = true
|
|
50
|
+
AND target->>'mode' <> 'ephemeral'
|
|
51
|
+
AND target->>'sessionId' = $1
|
|
52
|
+
) AS present`, [sessionId]);
|
|
53
|
+
return rows[0]?.present === true;
|
|
54
|
+
}
|
|
55
|
+
async get(id) {
|
|
56
|
+
const rows = await this._deps.connection.query('SELECT * FROM schedules WHERE id = $1 LIMIT 1', [id]);
|
|
57
|
+
return rows[0] ? toSchedule(rows[0]) : null;
|
|
58
|
+
}
|
|
59
|
+
/** Создаёт расписание: id `sch_<uuid>`, `createdAt`/`updatedAt` = now. */
|
|
60
|
+
async create(input) {
|
|
61
|
+
const id = `sch_${generateId()}`;
|
|
62
|
+
const now = new Date().toISOString();
|
|
63
|
+
const rows = await this._deps.connection.query(`INSERT INTO schedules
|
|
64
|
+
(id, name, enabled, cron, every, target, prompt, payload, owner_id, catch_up,
|
|
65
|
+
created_at, updated_at)
|
|
66
|
+
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8::jsonb, $9, $10, $11, $11)
|
|
67
|
+
RETURNING *`, [
|
|
68
|
+
id,
|
|
69
|
+
input.name,
|
|
70
|
+
input.enabled,
|
|
71
|
+
input.cron ?? null,
|
|
72
|
+
input.every ?? null,
|
|
73
|
+
jsonbParam(input.target ?? {}),
|
|
74
|
+
input.prompt ?? null,
|
|
75
|
+
input.payload !== undefined ? jsonbParam(input.payload) : null,
|
|
76
|
+
input.ownerId ?? null,
|
|
77
|
+
input.catchUp ?? null,
|
|
78
|
+
now,
|
|
79
|
+
]);
|
|
80
|
+
return toSchedule(rows[0]);
|
|
81
|
+
}
|
|
82
|
+
/** Обновляет расписание (partial-патч); `updatedAt` выставляется в now. */
|
|
83
|
+
async update(id, patch) {
|
|
84
|
+
const sets = ['updated_at = $1'];
|
|
85
|
+
const params = [new Date().toISOString()];
|
|
86
|
+
if (patch.name !== undefined) {
|
|
87
|
+
params.push(patch.name);
|
|
88
|
+
sets.push(`name = $${params.length}`);
|
|
89
|
+
}
|
|
90
|
+
if (patch.enabled !== undefined) {
|
|
91
|
+
params.push(patch.enabled);
|
|
92
|
+
sets.push(`enabled = $${params.length}`);
|
|
93
|
+
}
|
|
94
|
+
if (patch.cron !== undefined) {
|
|
95
|
+
params.push(patch.cron);
|
|
96
|
+
sets.push(`cron = $${params.length}`);
|
|
97
|
+
}
|
|
98
|
+
if (patch.every !== undefined) {
|
|
99
|
+
params.push(patch.every);
|
|
100
|
+
sets.push(`every = $${params.length}`);
|
|
101
|
+
}
|
|
102
|
+
if (patch.target !== undefined) {
|
|
103
|
+
params.push(jsonbParam(patch.target));
|
|
104
|
+
sets.push(`target = $${params.length}::jsonb`);
|
|
105
|
+
}
|
|
106
|
+
if (patch.prompt !== undefined) {
|
|
107
|
+
params.push(patch.prompt);
|
|
108
|
+
sets.push(`prompt = $${params.length}`);
|
|
109
|
+
}
|
|
110
|
+
if (patch.payload !== undefined) {
|
|
111
|
+
params.push(jsonbParam(patch.payload));
|
|
112
|
+
sets.push(`payload = $${params.length}::jsonb`);
|
|
113
|
+
}
|
|
114
|
+
if (patch.ownerId !== undefined) {
|
|
115
|
+
params.push(patch.ownerId);
|
|
116
|
+
sets.push(`owner_id = $${params.length}`);
|
|
117
|
+
}
|
|
118
|
+
if (patch.catchUp !== undefined) {
|
|
119
|
+
params.push(patch.catchUp);
|
|
120
|
+
sets.push(`catch_up = $${params.length}`);
|
|
121
|
+
}
|
|
122
|
+
params.push(id);
|
|
123
|
+
const rows = await this._deps.connection.query(`UPDATE schedules SET ${sets.join(', ')} WHERE id = $${params.length} RETURNING *`, params);
|
|
124
|
+
return rows[0] ? toSchedule(rows[0]) : null;
|
|
125
|
+
}
|
|
126
|
+
async remove(id) {
|
|
127
|
+
const rows = await this._deps.connection.query('DELETE FROM schedules WHERE id = $1 RETURNING id', [id]);
|
|
128
|
+
return rows.length > 0;
|
|
129
|
+
}
|
|
130
|
+
/** Фиксация результата запуска (`updatedAt` не трогается). */
|
|
131
|
+
async markRun(id, run) {
|
|
132
|
+
const sets = ['last_run_at = $2', 'last_status = $3', 'last_error = $4'];
|
|
133
|
+
const params = [id, run.at, run.status, run.error ?? null];
|
|
134
|
+
if (run.nextRunAt !== undefined) {
|
|
135
|
+
params.push(run.nextRunAt);
|
|
136
|
+
sets.push(`next_run_at = $${params.length}`);
|
|
137
|
+
}
|
|
138
|
+
const rows = await this._deps.connection.query(`UPDATE schedules SET ${sets.join(', ')} WHERE id = $1 RETURNING *`, params);
|
|
139
|
+
return rows[0] ? toSchedule(rows[0]) : null;
|
|
140
|
+
}
|
|
141
|
+
/** Обновление только `nextRunAt` (служебное поле сервиса). */
|
|
142
|
+
async setNextRun(id, nextRunAt) {
|
|
143
|
+
const rows = await this._deps.connection.query('UPDATE schedules SET next_run_at = $2 WHERE id = $1 RETURNING *', [id, nextRunAt ?? null]);
|
|
144
|
+
return rows[0] ? toSchedule(rows[0]) : null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function toJob(row) {
|
|
148
|
+
return compact({
|
|
149
|
+
id: row.id,
|
|
150
|
+
scheduleId: row.schedule_id,
|
|
151
|
+
scheduleName: row.schedule_name,
|
|
152
|
+
trigger: row.trigger,
|
|
153
|
+
status: row.status,
|
|
154
|
+
startedAt: toIsoRequired(row.started_at),
|
|
155
|
+
finishedAt: toIsoRequired(row.finished_at),
|
|
156
|
+
durationMs: toInt(row.duration_ms) ?? 0,
|
|
157
|
+
target: (row.target ?? { mode: 'ephemeral' }),
|
|
158
|
+
dedupKey: row.dedup_key ?? undefined,
|
|
159
|
+
decision: (row.decision ?? undefined),
|
|
160
|
+
reason: row.reason ?? undefined,
|
|
161
|
+
sessionId: row.session_id ?? undefined,
|
|
162
|
+
error: row.error ?? undefined,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** ADR-051: append-only история срабатываний поверх `jobs`. */
|
|
166
|
+
export class PgJobRepository {
|
|
167
|
+
_deps;
|
|
168
|
+
constructor(_deps) {
|
|
169
|
+
this._deps = _deps;
|
|
170
|
+
}
|
|
171
|
+
async append(job) {
|
|
172
|
+
await this._deps.connection.query(`INSERT INTO jobs
|
|
173
|
+
(id, schedule_id, schedule_name, trigger, status, started_at, finished_at,
|
|
174
|
+
duration_ms, target, dedup_key, decision, reason, session_id, error)
|
|
175
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, $13, $14)`, [
|
|
176
|
+
job.id,
|
|
177
|
+
job.scheduleId,
|
|
178
|
+
job.scheduleName,
|
|
179
|
+
job.trigger,
|
|
180
|
+
job.status,
|
|
181
|
+
job.startedAt,
|
|
182
|
+
job.finishedAt,
|
|
183
|
+
job.durationMs,
|
|
184
|
+
jsonbParam(job.target ?? {}),
|
|
185
|
+
job.dedupKey ?? null,
|
|
186
|
+
job.decision ?? null,
|
|
187
|
+
job.reason ?? null,
|
|
188
|
+
job.sessionId ?? null,
|
|
189
|
+
job.error ?? null,
|
|
190
|
+
]);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* История в порядке добавления (старые → новые); фильтр `scheduleId`,
|
|
194
|
+
* `limit` — последние N.
|
|
195
|
+
*/
|
|
196
|
+
async list(opts = {}) {
|
|
197
|
+
const limited = opts.limit !== undefined && Number.isFinite(opts.limit) && opts.limit > 0;
|
|
198
|
+
const limit = limited ? Math.floor(opts.limit) : 0;
|
|
199
|
+
let rows;
|
|
200
|
+
if (opts.scheduleId !== undefined && limited) {
|
|
201
|
+
rows = await this._deps.connection.query(`SELECT * FROM (
|
|
202
|
+
SELECT * FROM jobs WHERE schedule_id = $1 ORDER BY seq DESC LIMIT $2
|
|
203
|
+
) t ORDER BY seq ASC`, [opts.scheduleId, limit]);
|
|
204
|
+
}
|
|
205
|
+
else if (opts.scheduleId !== undefined) {
|
|
206
|
+
rows = await this._deps.connection.query('SELECT * FROM jobs WHERE schedule_id = $1 ORDER BY seq ASC', [opts.scheduleId]);
|
|
207
|
+
}
|
|
208
|
+
else if (limited) {
|
|
209
|
+
rows = await this._deps.connection.query(`SELECT * FROM (
|
|
210
|
+
SELECT * FROM jobs ORDER BY seq DESC LIMIT $1
|
|
211
|
+
) t ORDER BY seq ASC`, [limit]);
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
rows = await this._deps.connection.query('SELECT * FROM jobs ORDER BY seq ASC');
|
|
215
|
+
}
|
|
216
|
+
return rows.map(toJob);
|
|
217
|
+
}
|
|
218
|
+
/** Retention: удаляет записи старше `retentionDays` (по `startedAt`). */
|
|
219
|
+
async prune(retentionDays) {
|
|
220
|
+
const days = Number.isFinite(retentionDays) ? retentionDays : 0;
|
|
221
|
+
const rows = await this._deps.connection.query(`DELETE FROM jobs WHERE started_at < now() - interval '1 day' * $1::double precision RETURNING seq`, [days]);
|
|
222
|
+
return rows.length;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** Собрать под-группу портов планировщика. */
|
|
226
|
+
export function buildEventSchedulerPorts(deps) {
|
|
227
|
+
return {
|
|
228
|
+
schedules: new PgScheduleRepository(deps),
|
|
229
|
+
jobs: new PgJobRepository(deps),
|
|
230
|
+
};
|
|
231
|
+
}
|