@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
package/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Дмитрий Рамазанов <ramazanov_dv@mail.ru>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
6
|
+
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
|
7
|
+
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
12
|
+
portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
15
|
+
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
16
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
18
|
+
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/LICENSE.ru.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Лицензия MIT (перевод)
|
|
2
|
+
|
|
3
|
+
> **Внимание.** Этот файл — неофициальный перевод лицензии MIT на русский язык,
|
|
4
|
+
> предоставленный исключительно в информационных целях. Юридическую силу имеет
|
|
5
|
+
> оригинальный текст на английском языке — файл [LICENSE](./LICENSE).
|
|
6
|
+
> При любых расхождениях приоритет имеет английская версия.
|
|
7
|
+
|
|
8
|
+
MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 Дмитрий Рамазанов <ramazanov_dv@mail.ru>
|
|
11
|
+
|
|
12
|
+
Настоящим предоставляется бесплатное разрешение любому лицу, получившему копию
|
|
13
|
+
данного программного обеспечения и сопутствующих файлов документации (далее —
|
|
14
|
+
«Программное обеспечение»), безвозмездно распоряжаться Программным обеспечением
|
|
15
|
+
без ограничений, включая, помимо прочего, права на использование, копирование,
|
|
16
|
+
изменение, объединение, публикацию, распространение, сублицензирование и/или
|
|
17
|
+
продажу копий Программного обеспечения, а также разрешать лицам, которым
|
|
18
|
+
предоставляется Программное обеспечение, делать то же самое при соблюдении
|
|
19
|
+
следующих условий:
|
|
20
|
+
|
|
21
|
+
Указанное выше уведомление об авторских правах и настоящее уведомление о
|
|
22
|
+
разрешении должны быть включены во все копии или существенные части
|
|
23
|
+
Программного обеспечения.
|
|
24
|
+
|
|
25
|
+
ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ,
|
|
26
|
+
ЯВНЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ГАРАНТИИ ТОВАРНОЙ
|
|
27
|
+
ПРИГОДНОСТИ, ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЁННОЙ ЦЕЛИ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ
|
|
28
|
+
СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО КАКИМ-ЛИБО
|
|
29
|
+
ИСКАМ, УБЫТКАМ ИЛИ ИНЫМ ОБЯЗАТЕЛЬСТВАМ, БУДЬ ТО ПО ДОГОВОРУ, ДЕЛИКТУ ИЛИ ИНЫМ
|
|
30
|
+
ОСНОВАНИЯМ, ВОЗНИКАЮЩИМ ИЗ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ, В СВЯЗИ С НИМ ИЛИ В
|
|
31
|
+
РЕЗУЛЬТАТЕ ЕГО ИСПОЛЬЗОВАНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ С НИМ.
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ошибки PostgreSQL-драйвера хранения (ADR-096/ADR-097, PROP-032).
|
|
3
|
+
*
|
|
4
|
+
* Здесь живут и «конфигурационные» ошибки драйвера, и маппинг сырых ошибок
|
|
5
|
+
* `pg`/PostgreSQL в доменные классы. Маппинг — интерфейс для следующих волн
|
|
6
|
+
* (порты): SQLSTATE 23505/42P01/55P03 и сетевые ошибки соединения получают
|
|
7
|
+
* собственные типы, прочее — общий `PostgresQueryError`.
|
|
8
|
+
*/
|
|
9
|
+
/** Базовая ошибка драйвера хранения PostgreSQL. */
|
|
10
|
+
export declare class PostgresStorageError extends Error {
|
|
11
|
+
readonly code: string;
|
|
12
|
+
constructor(message: string, code: string, options?: {
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/** Конфиг драйвера невалиден (не задан способ подключения, плохая схема и т.п.). */
|
|
17
|
+
export declare class PostgresStorageConfigError extends PostgresStorageError {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
/** Optional-зависимость `pg` недоступна (не установлена). */
|
|
21
|
+
export declare class PostgresStorageDependencyError extends PostgresStorageError {
|
|
22
|
+
constructor(message: string, options?: {
|
|
23
|
+
cause?: unknown;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** Реализация портов ещё не поставлена (инфраструктурная волна). */
|
|
27
|
+
export declare class PostgresStorageNotImplementedError extends PostgresStorageError {
|
|
28
|
+
constructor(message?: string);
|
|
29
|
+
}
|
|
30
|
+
/** Версия схемы БД несовместима с ожидаемой драйвером (fail-closed). */
|
|
31
|
+
export declare class PostgresStorageSchemaError extends PostgresStorageError {
|
|
32
|
+
constructor(message: string, code: 'STORAGE_POSTGRES_SCHEMA_TOO_NEW' | 'STORAGE_POSTGRES_SCHEMA_OUTDATED');
|
|
33
|
+
}
|
|
34
|
+
/** Нарушение уникальности (SQLSTATE 23505). */
|
|
35
|
+
export declare class PostgresUniqueViolationError extends PostgresStorageError {
|
|
36
|
+
constructor(message: string, options?: {
|
|
37
|
+
cause?: unknown;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Обращение к несуществующей таблице (SQLSTATE 42P01) — обычно рассинхрон схемы. */
|
|
41
|
+
export declare class PostgresUndefinedTableError extends PostgresStorageError {
|
|
42
|
+
constructor(message: string, options?: {
|
|
43
|
+
cause?: unknown;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** Не удалось взять блокировку/таймаут ожидания (SQLSTATE 55P03 и производные). */
|
|
47
|
+
export declare class PostgresLockTimeoutError extends PostgresStorageError {
|
|
48
|
+
constructor(message: string, options?: {
|
|
49
|
+
cause?: unknown;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/** Сбой соединения с БД (SQLSTATE класса 08, 57P0x либо сетевой код Node). */
|
|
53
|
+
export declare class PostgresConnectionError extends PostgresStorageError {
|
|
54
|
+
constructor(message: string, options?: {
|
|
55
|
+
cause?: unknown;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** Прочий сбой SQL-запроса (дефолт маппинга). */
|
|
59
|
+
export declare class PostgresQueryError extends PostgresStorageError {
|
|
60
|
+
constructor(message: string, options?: {
|
|
61
|
+
cause?: unknown;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Маппинг сырой ошибки `pg`/PostgreSQL в доменный класс драйвера.
|
|
66
|
+
*
|
|
67
|
+
* Идемпотентен: уже доменная `PostgresStorageError` возвращается как есть (важно
|
|
68
|
+
* для вложенных хелперов — `withTransaction`/`withAdvisoryLock` не оборачивают
|
|
69
|
+
* ошибки callback'а повторно).
|
|
70
|
+
*/
|
|
71
|
+
export declare function mapPgError(err: unknown): PostgresStorageError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ошибки PostgreSQL-драйвера хранения (ADR-096/ADR-097, PROP-032).
|
|
3
|
+
*
|
|
4
|
+
* Здесь живут и «конфигурационные» ошибки драйвера, и маппинг сырых ошибок
|
|
5
|
+
* `pg`/PostgreSQL в доменные классы. Маппинг — интерфейс для следующих волн
|
|
6
|
+
* (порты): SQLSTATE 23505/42P01/55P03 и сетевые ошибки соединения получают
|
|
7
|
+
* собственные типы, прочее — общий `PostgresQueryError`.
|
|
8
|
+
*/
|
|
9
|
+
/** Базовая ошибка драйвера хранения PostgreSQL. */
|
|
10
|
+
export class PostgresStorageError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(message, code, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.name = 'PostgresStorageError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** Конфиг драйвера невалиден (не задан способ подключения, плохая схема и т.п.). */
|
|
19
|
+
export class PostgresStorageConfigError extends PostgresStorageError {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(message, 'STORAGE_POSTGRES_CONFIG_INVALID');
|
|
22
|
+
this.name = 'PostgresStorageConfigError';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Optional-зависимость `pg` недоступна (не установлена). */
|
|
26
|
+
export class PostgresStorageDependencyError extends PostgresStorageError {
|
|
27
|
+
constructor(message, options) {
|
|
28
|
+
super(message, 'STORAGE_POSTGRES_DEPENDENCY_MISSING', options);
|
|
29
|
+
this.name = 'PostgresStorageDependencyError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Реализация портов ещё не поставлена (инфраструктурная волна). */
|
|
33
|
+
export class PostgresStorageNotImplementedError extends PostgresStorageError {
|
|
34
|
+
constructor(message = 'PostgreSQL-драйвер хранения: реализация портов ещё не поставлена (PROP-032).') {
|
|
35
|
+
super(message, 'STORAGE_POSTGRES_NOT_IMPLEMENTED');
|
|
36
|
+
this.name = 'PostgresStorageNotImplementedError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Версия схемы БД несовместима с ожидаемой драйвером (fail-closed). */
|
|
40
|
+
export class PostgresStorageSchemaError extends PostgresStorageError {
|
|
41
|
+
constructor(message, code) {
|
|
42
|
+
super(message, code);
|
|
43
|
+
this.name = 'PostgresStorageSchemaError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Нарушение уникальности (SQLSTATE 23505). */
|
|
47
|
+
export class PostgresUniqueViolationError extends PostgresStorageError {
|
|
48
|
+
constructor(message, options) {
|
|
49
|
+
super(message, 'STORAGE_POSTGRES_UNIQUE_VIOLATION', options);
|
|
50
|
+
this.name = 'PostgresUniqueViolationError';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Обращение к несуществующей таблице (SQLSTATE 42P01) — обычно рассинхрон схемы. */
|
|
54
|
+
export class PostgresUndefinedTableError extends PostgresStorageError {
|
|
55
|
+
constructor(message, options) {
|
|
56
|
+
super(message, 'STORAGE_POSTGRES_UNDEFINED_TABLE', options);
|
|
57
|
+
this.name = 'PostgresUndefinedTableError';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Не удалось взять блокировку/таймаут ожидания (SQLSTATE 55P03 и производные). */
|
|
61
|
+
export class PostgresLockTimeoutError extends PostgresStorageError {
|
|
62
|
+
constructor(message, options) {
|
|
63
|
+
super(message, 'STORAGE_POSTGRES_LOCK_TIMEOUT', options);
|
|
64
|
+
this.name = 'PostgresLockTimeoutError';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Сбой соединения с БД (SQLSTATE класса 08, 57P0x либо сетевой код Node). */
|
|
68
|
+
export class PostgresConnectionError extends PostgresStorageError {
|
|
69
|
+
constructor(message, options) {
|
|
70
|
+
super(message, 'STORAGE_POSTGRES_CONNECTION', options);
|
|
71
|
+
this.name = 'PostgresConnectionError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Прочий сбой SQL-запроса (дефолт маппинга). */
|
|
75
|
+
export class PostgresQueryError extends PostgresStorageError {
|
|
76
|
+
constructor(message, options) {
|
|
77
|
+
super(message, 'STORAGE_POSTGRES_QUERY', options);
|
|
78
|
+
this.name = 'PostgresQueryError';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Сетевые коды Node, сигнализирующие о недоступности/обрыве соединения. */
|
|
82
|
+
const CONNECTION_ERRNO = new Set([
|
|
83
|
+
'ECONNREFUSED',
|
|
84
|
+
'ECONNRESET',
|
|
85
|
+
'ETIMEDOUT',
|
|
86
|
+
'ENOTFOUND',
|
|
87
|
+
'EHOSTUNREACH',
|
|
88
|
+
'ENETUNREACH',
|
|
89
|
+
'EPIPE',
|
|
90
|
+
'EAI_AGAIN',
|
|
91
|
+
]);
|
|
92
|
+
function isConnectionFailure(code) {
|
|
93
|
+
if (typeof code !== 'string')
|
|
94
|
+
return false;
|
|
95
|
+
if (CONNECTION_ERRNO.has(code))
|
|
96
|
+
return true;
|
|
97
|
+
// SQLSTATE: класс 08 — connection exceptions; 57P01/57P02/57P03 — shutdown/terminating.
|
|
98
|
+
return code.startsWith('08') || code === '57P01' || code === '57P02' || code === '57P03';
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Маппинг сырой ошибки `pg`/PostgreSQL в доменный класс драйвера.
|
|
102
|
+
*
|
|
103
|
+
* Идемпотентен: уже доменная `PostgresStorageError` возвращается как есть (важно
|
|
104
|
+
* для вложенных хелперов — `withTransaction`/`withAdvisoryLock` не оборачивают
|
|
105
|
+
* ошибки callback'а повторно).
|
|
106
|
+
*/
|
|
107
|
+
export function mapPgError(err) {
|
|
108
|
+
if (err instanceof PostgresStorageError)
|
|
109
|
+
return err;
|
|
110
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
111
|
+
const code = err?.code;
|
|
112
|
+
switch (code) {
|
|
113
|
+
case '23505':
|
|
114
|
+
return new PostgresUniqueViolationError(message, { cause: err });
|
|
115
|
+
case '42P01':
|
|
116
|
+
return new PostgresUndefinedTableError(message, { cause: err });
|
|
117
|
+
case '55P03':
|
|
118
|
+
case '55P02':
|
|
119
|
+
return new PostgresLockTimeoutError(message, { cause: err });
|
|
120
|
+
default:
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
if (isConnectionFailure(code))
|
|
124
|
+
return new PostgresConnectionError(message, { cause: err });
|
|
125
|
+
return new PostgresQueryError(message, { cause: err });
|
|
126
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Публичная поверхность `@itphx/synth-storage-postgres` — опциональный драйвер
|
|
3
|
+
* слоя хранения Synth на PostgreSQL (ADR-096/ADR-097, PROP-032).
|
|
4
|
+
*
|
|
5
|
+
* Импорт модуля не требует установленного `pg` — драйвер подключается лениво
|
|
6
|
+
* внутри `createPostgresConnection`/`createPostgresStorage`.
|
|
7
|
+
*
|
|
8
|
+
* Волна 3a: подключение (`pool.ts`), схема и миграции (`migrate.ts` +
|
|
9
|
+
* `migrations/*`), сборка контекста (`storage-context.ts`). Волна 3b: каркас
|
|
10
|
+
* портов разложен по четырём файлам-группам `ports/*` (сейчас — заглушки),
|
|
11
|
+
* реализация доменных портов — следующая волна.
|
|
12
|
+
*/
|
|
13
|
+
export { createPostgresStorage, validatePostgresConfig } from './postgres-storage.js';
|
|
14
|
+
export type { PostgresStorageConfig } from './postgres-storage.js';
|
|
15
|
+
export * from './errors.js';
|
|
16
|
+
export { createPostgresConnection, PostgresConnection, advisoryLockKeyToBigInt, loadPgModule, sanitizeQueryParams, } from './pool.js';
|
|
17
|
+
export type { PostgresPoolConfig, PostgresConnectionConfig, PostgresExecutor, HeldPostgresClient, } from './pool.js';
|
|
18
|
+
export { PgMutex, PgLeader, createPostgresLocks, postgresLockKey, DEFAULT_LEADER_LOCK_NAME } from './locks.js';
|
|
19
|
+
export type { PgMutexOptions, PgLeaderOptions } from './locks.js';
|
|
20
|
+
export { runMigrations, assertSchemaCurrent, readSchemaVersion, planMigrations, MIGRATIONS_TABLE } from './migrate.js';
|
|
21
|
+
export type { RunMigrationsOptions, MigrationResult, PlannedMigrations } from './migrate.js';
|
|
22
|
+
export { MIGRATIONS, latestSchemaVersion } from './migrations/index.js';
|
|
23
|
+
export type { PostgresMigration } from './migrations/index.js';
|
|
24
|
+
export { DEFAULT_SCHEMA, assertValidSchema, quoteIdent } from './schema.js';
|
|
25
|
+
export { buildPostgresStorageContext } from './storage-context.js';
|
|
26
|
+
export type { BuildPostgresContextOptions } from './storage-context.js';
|
|
27
|
+
export { notImplementedPort } from './ports/stub.js';
|
|
28
|
+
export type { PortDeps, CoreSyncDeps } from './ports/deps.js';
|
|
29
|
+
export { resolveCoreSyncDeps, POSTGRES_EMPTY_USER_DICTIONARIES_SUBDIR } from './ports/core-sync.js';
|
|
30
|
+
export { buildSessionPorts } from './ports/sessions.js';
|
|
31
|
+
export type { SessionPorts } from './ports/sessions.js';
|
|
32
|
+
export { buildPrincipalPorts } from './ports/principals.js';
|
|
33
|
+
export type { PrincipalPorts } from './ports/principals.js';
|
|
34
|
+
export { buildEventPorts } from './ports/events.js';
|
|
35
|
+
export type { EventPorts } from './ports/events.js';
|
|
36
|
+
export { buildContentPorts } from './ports/content.js';
|
|
37
|
+
export type { ContentPorts } from './ports/content.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Публичная поверхность `@itphx/synth-storage-postgres` — опциональный драйвер
|
|
3
|
+
* слоя хранения Synth на PostgreSQL (ADR-096/ADR-097, PROP-032).
|
|
4
|
+
*
|
|
5
|
+
* Импорт модуля не требует установленного `pg` — драйвер подключается лениво
|
|
6
|
+
* внутри `createPostgresConnection`/`createPostgresStorage`.
|
|
7
|
+
*
|
|
8
|
+
* Волна 3a: подключение (`pool.ts`), схема и миграции (`migrate.ts` +
|
|
9
|
+
* `migrations/*`), сборка контекста (`storage-context.ts`). Волна 3b: каркас
|
|
10
|
+
* портов разложен по четырём файлам-группам `ports/*` (сейчас — заглушки),
|
|
11
|
+
* реализация доменных портов — следующая волна.
|
|
12
|
+
*/
|
|
13
|
+
export { createPostgresStorage, validatePostgresConfig } from './postgres-storage.js';
|
|
14
|
+
// Ошибки драйвера + маппинг сырых ошибок `pg` в доменные классы.
|
|
15
|
+
export * from './errors.js';
|
|
16
|
+
// Пул/подключение и низкоуровневые хелперы (запросы, транзакции, advisory-локи).
|
|
17
|
+
export { createPostgresConnection, PostgresConnection, advisoryLockKeyToBigInt, loadPgModule, sanitizeQueryParams, } from './pool.js';
|
|
18
|
+
// PROP-032: БД-механизмы координации (advisory-локи) — мьютекс, лидер-выбор,
|
|
19
|
+
// фабрика `StorageLocks` для `StorageContext.locks`.
|
|
20
|
+
export { PgMutex, PgLeader, createPostgresLocks, postgresLockKey, DEFAULT_LEADER_LOCK_NAME } from './locks.js';
|
|
21
|
+
// Схема и миграции.
|
|
22
|
+
export { runMigrations, assertSchemaCurrent, readSchemaVersion, planMigrations, MIGRATIONS_TABLE } from './migrate.js';
|
|
23
|
+
export { MIGRATIONS, latestSchemaVersion } from './migrations/index.js';
|
|
24
|
+
// Идентификаторы схемы.
|
|
25
|
+
export { DEFAULT_SCHEMA, assertValidSchema, quoteIdent } from './schema.js';
|
|
26
|
+
// Сборка контекста: четыре группы портов (`ports/*`) + файловые FS-порты.
|
|
27
|
+
export { buildPostgresStorageContext } from './storage-context.js';
|
|
28
|
+
// Группы портов (владелец каждого файла — один агент волны реализации).
|
|
29
|
+
export { notImplementedPort } from './ports/stub.js';
|
|
30
|
+
export { resolveCoreSyncDeps, POSTGRES_EMPTY_USER_DICTIONARIES_SUBDIR } from './ports/core-sync.js';
|
|
31
|
+
export { buildSessionPorts } from './ports/sessions.js';
|
|
32
|
+
export { buildPrincipalPorts } from './ports/principals.js';
|
|
33
|
+
export { buildEventPorts } from './ports/events.js';
|
|
34
|
+
export { buildContentPorts } from './ports/content.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Сериализация значений в `jsonb`-параметры PostgreSQL.
|
|
3
|
+
*
|
|
4
|
+
* PostgreSQL не принимает U+0000 в `jsonb`: `JSON.stringify` превращает реальный
|
|
5
|
+
* NUL в escape `\u0000`, и сервер отвечает «unsupported Unicode escape sequence».
|
|
6
|
+
* Поэтому значение очищается `stripNullBytesDeep` **до** сериализации — это
|
|
7
|
+
* единственное место, где NUL-байты в JSON-строках ещё различимы как данные
|
|
8
|
+
* (в готовой JSON-строке escape `\u0000` уже неотличим от литеральной
|
|
9
|
+
* последовательности, которую трогать нельзя).
|
|
10
|
+
*/
|
|
11
|
+
/** JSON-строка для `jsonb`-параметра; `null`/`undefined` → SQL `NULL`. */
|
|
12
|
+
export declare function jsonbParam(value: unknown): string | null;
|
|
13
|
+
/** JSON-строка для `jsonb`-параметра без схлопывания `null` в SQL `NULL`. */
|
|
14
|
+
export declare function jsonbLiteral(value: unknown): string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Сериализация значений в `jsonb`-параметры PostgreSQL.
|
|
3
|
+
*
|
|
4
|
+
* PostgreSQL не принимает U+0000 в `jsonb`: `JSON.stringify` превращает реальный
|
|
5
|
+
* NUL в escape `\u0000`, и сервер отвечает «unsupported Unicode escape sequence».
|
|
6
|
+
* Поэтому значение очищается `stripNullBytesDeep` **до** сериализации — это
|
|
7
|
+
* единственное место, где NUL-байты в JSON-строках ещё различимы как данные
|
|
8
|
+
* (в готовой JSON-строке escape `\u0000` уже неотличим от литеральной
|
|
9
|
+
* последовательности, которую трогать нельзя).
|
|
10
|
+
*/
|
|
11
|
+
import { stripNullBytesDeep } from '@itphx/synth-shared';
|
|
12
|
+
/** JSON-строка для `jsonb`-параметра; `null`/`undefined` → SQL `NULL`. */
|
|
13
|
+
export function jsonbParam(value) {
|
|
14
|
+
if (value === undefined || value === null)
|
|
15
|
+
return null;
|
|
16
|
+
const json = JSON.stringify(stripNullBytesDeep(value));
|
|
17
|
+
return json === undefined ? null : json;
|
|
18
|
+
}
|
|
19
|
+
/** JSON-строка для `jsonb`-параметра без схлопывания `null` в SQL `NULL`. */
|
|
20
|
+
export function jsonbLiteral(value) {
|
|
21
|
+
return JSON.stringify(stripNullBytesDeep(value ?? null));
|
|
22
|
+
}
|
package/dist/locks.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PROP-032: БД-механизмы межпроцессной координации — мьютекс и лидер-выбор
|
|
3
|
+
* поверх session-level advisory-локов PostgreSQL.
|
|
4
|
+
*
|
|
5
|
+
* Заменяют файловые примитивы core (`FileMutex`/`FileLeader`) при
|
|
6
|
+
* `storage.backend=postgres`: файловый лок работает только на общем FS, а в
|
|
7
|
+
* кластере реплики могут не иметь общего диска. Advisory-лок БД, напротив,
|
|
8
|
+
* разделяется всеми соединениями к одной БД независимо от хоста.
|
|
9
|
+
*
|
|
10
|
+
* Ключи. Имя лока namespaced-ится префиксом `synth:` и превращается в 64-битный
|
|
11
|
+
* знаковый ключ детерминированным хешем (`advisoryLockKeyToBigInt`, sha256) —
|
|
12
|
+
* тот же способ, что в `PostgresConnection.withAdvisoryLock`, поэтому ключи разных
|
|
13
|
+
* подсистем (`synth:migrate:<schema>`, `synth:scheduler/leader`, …) не пересекаются.
|
|
14
|
+
*
|
|
15
|
+
* Session-level лок удерживается **соединением**, а не транзакцией: он
|
|
16
|
+
* автоматически снимается при его разрыве/закрытии (свойство PostgreSQL —
|
|
17
|
+
* используем его как надёжный механизм освобождения, а не боремся с ним).
|
|
18
|
+
*
|
|
19
|
+
* Пул. Удерживаемое соединение не возвращается в пул до снятия лока, поэтому под
|
|
20
|
+
* PG-лидера расходуется один постоянный клиент на процесс; учитывайте это при
|
|
21
|
+
* `poolMax` (по умолчанию 10, `pool.ts`).
|
|
22
|
+
*/
|
|
23
|
+
import { type PostgresConnection } from './pool.js';
|
|
24
|
+
import type { LockOptions, Mutex, SchedulerLeader, StorageLocks } from '@itphx/synth-core';
|
|
25
|
+
/** Имя лока лидера планировщика по умолчанию. */
|
|
26
|
+
export declare const DEFAULT_LEADER_LOCK_NAME = "scheduler/leader";
|
|
27
|
+
/** Namespaced-имя → строка 64-битного advisory-ключа. */
|
|
28
|
+
export declare function postgresLockKey(name: string): string;
|
|
29
|
+
/** Опции `PgMutex`. */
|
|
30
|
+
export interface PgMutexOptions {
|
|
31
|
+
/** Соединение драйвера (пул); под лок берётся выделенный клиент. */
|
|
32
|
+
connection: PostgresConnection;
|
|
33
|
+
/** Namespaced-имя лока (без префикса `synth:`). */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Общий таймаут захвата, мс (по умолчанию 5_000). */
|
|
36
|
+
timeoutMs?: number;
|
|
37
|
+
/** Пауза между попытками захвата, мс (по умолчанию 25). */
|
|
38
|
+
retryMs?: number;
|
|
39
|
+
/** Принято для совместимости с `MutexFactoryOptions`; advisory-лок не стареет. */
|
|
40
|
+
staleMs?: number;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* PROP-032: мьютекс на session-level `pg_advisory_lock` (выделенное соединение).
|
|
44
|
+
*
|
|
45
|
+
* Семантика (паритет с `FileMutex`, ADR-051/ADR-089):
|
|
46
|
+
* - захват с ретраями `pg_try_advisory_lock` до `timeoutMs`;
|
|
47
|
+
* - по истечении — `warn` и выполнение `fn` **без** лока (осознанный fail-open);
|
|
48
|
+
* - освобождение — `pg_advisory_unlock` в `finally` + возврат соединения в пул;
|
|
49
|
+
* - при **недоступной БД** (не удалось получить соединение/выполнить запрос) —
|
|
50
|
+
* ошибка пробрасывается наружу (не зависание и не «тихий» fail-open: без БД
|
|
51
|
+
* backend всё равно неработоспособен).
|
|
52
|
+
*/
|
|
53
|
+
export declare class PgMutex implements Mutex {
|
|
54
|
+
private readonly _connection;
|
|
55
|
+
private readonly _key;
|
|
56
|
+
private readonly _name;
|
|
57
|
+
private readonly _timeoutMs;
|
|
58
|
+
private readonly _retryMs;
|
|
59
|
+
constructor(options: PgMutexOptions);
|
|
60
|
+
withLock<T>(fn: () => Promise<T>, _opts?: LockOptions): Promise<T>;
|
|
61
|
+
}
|
|
62
|
+
/** Опции `PgLeader`. */
|
|
63
|
+
export interface PgLeaderOptions {
|
|
64
|
+
/** Соединение драйвера (пул); под лидерство берётся постоянный клиент. */
|
|
65
|
+
connection: PostgresConnection;
|
|
66
|
+
/** Namespaced-имя лока (по умолчанию `scheduler/leader`). */
|
|
67
|
+
name?: string;
|
|
68
|
+
/** Принято для совместимости с `LeaderFactoryOptions`; advisory-лок не стареет. */
|
|
69
|
+
tickMs?: number;
|
|
70
|
+
/** Принято для совместимости; advisory-лок не стареет. */
|
|
71
|
+
staleMs?: number;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* PROP-032: лидер-выбор планировщика на удерживаемом session-level advisory-локе
|
|
75
|
+
* (ADR-051/ADR-089). Совместим с `SchedulerLeader`.
|
|
76
|
+
*
|
|
77
|
+
* - `acquire()` — одна попытка `pg_try_advisory_lock` на **постоянном** соединении:
|
|
78
|
+
* `true` — мы лидер (соединение удерживается всё время лидерства), `false` —
|
|
79
|
+
* лок занят другим процессом. Ошибка БД пробрасывается (не зависание).
|
|
80
|
+
* - `touch()` — no-op: в отличие от файлового лиза, advisory-лок живёт, пока живо
|
|
81
|
+
* соединение, и не требует heartbeat.
|
|
82
|
+
* - `release()` — `pg_advisory_unlock` + возврат соединения в пул.
|
|
83
|
+
* - **Разрыв соединения** (сервер/сеть) эмитит `error` у клиента: лидер явно
|
|
84
|
+
* снимает себя (`isLeader === false`) и логирует — «молчаливым» лидером после
|
|
85
|
+
* потери лока процесс не остаётся.
|
|
86
|
+
*/
|
|
87
|
+
export declare class PgLeader implements SchedulerLeader {
|
|
88
|
+
private readonly _connection;
|
|
89
|
+
private readonly _key;
|
|
90
|
+
private readonly _name;
|
|
91
|
+
private _held;
|
|
92
|
+
private _isLeader;
|
|
93
|
+
constructor(options: PgLeaderOptions);
|
|
94
|
+
/** Держим ли лидерство прямо сейчас (с учётом детекта разрыва соединения). */
|
|
95
|
+
get isLeader(): boolean;
|
|
96
|
+
acquire(): Promise<boolean>;
|
|
97
|
+
touch(): Promise<void>;
|
|
98
|
+
release(): Promise<void>;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* PROP-032: примитивы координации PG, публикуемые в `StorageContext.locks`
|
|
102
|
+
* (`StorageLocks`) — composition root подставляет их вместо файловых.
|
|
103
|
+
*/
|
|
104
|
+
export declare function createPostgresLocks(connection: PostgresConnection): StorageLocks;
|