@coopenomics/extension-sdk 2026.11.25 → 2026.12.1

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.
@@ -0,0 +1,20 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { Kysely } from 'kysely';
3
+ /** Изменение строки таблицы, о котором лента изменений узнаёт после фиксации записи. */
4
+ export interface PendingLocalChange {
5
+ table: string;
6
+ primary_key: string;
7
+ row: Record<string, unknown>;
8
+ }
9
+ type Publisher = (change: PendingLocalChange) => void;
10
+ /** Изменения текущей транзакции: копятся здесь и публикуются после фиксации. */
11
+ export declare const pendingLocalChanges: AsyncLocalStorage<PendingLocalChange[]>;
12
+ /** Ядро сообщает, куда публиковать изменения после фиксации транзакции. */
13
+ export declare function configureLocalChangePublisher(publish: Publisher): void;
14
+ /**
15
+ * Транзакция Kysely. Сигналы ленты изменений уходят после фиксации: стол по
16
+ * ним читает уже записанное, откаченная запись сигнала не даёт. Голый
17
+ * `db.transaction()` этого не делает — транзакции открывать только здесь.
18
+ */
19
+ export declare function inTransaction<TDatabase, TResult>(db: Kysely<TDatabase>, work: (trx: Kysely<TDatabase>) => Promise<TResult>): Promise<TResult>;
20
+ export {};
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pendingLocalChanges = void 0;
4
+ exports.configureLocalChangePublisher = configureLocalChangePublisher;
5
+ exports.inTransaction = inTransaction;
6
+ const node_async_hooks_1 = require("node:async_hooks");
7
+ // Состояние одно на процесс, даже если пакет загружен двумя копиями: изменения
8
+ // копит слой базы ядра, а транзакцию открывает расширение.
9
+ const STATE_KEY = Symbol.for('Controller.Database.Transaction');
10
+ const globals = globalThis;
11
+ const state = (globals[STATE_KEY] ??= { pending: new node_async_hooks_1.AsyncLocalStorage() });
12
+ /** Изменения текущей транзакции: копятся здесь и публикуются после фиксации. */
13
+ exports.pendingLocalChanges = state.pending;
14
+ /** Ядро сообщает, куда публиковать изменения после фиксации транзакции. */
15
+ function configureLocalChangePublisher(publish) {
16
+ state.publish = publish;
17
+ }
18
+ /**
19
+ * Транзакция Kysely. Сигналы ленты изменений уходят после фиксации: стол по
20
+ * ним читает уже записанное, откаченная запись сигнала не даёт. Голый
21
+ * `db.transaction()` этого не делает — транзакции открывать только здесь.
22
+ */
23
+ async function inTransaction(db, work) {
24
+ const changes = [];
25
+ const result = await state.pending.run(changes, () => db.transaction().execute((trx) => work(trx)));
26
+ changes.forEach((change) => state.publish?.(change));
27
+ return result;
28
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Чтение шины событий узла приложением каталога (487-42).
3
+ *
4
+ * Шина — потоки Redis узла `bus:<кооператив>:<тема>`; издаёт их ядро после
5
+ * собственной обработки события. Приложение читает потоки блокирующим
6
+ * чтением: соединение открыто постоянно, приложение получает событие без опроса.
7
+ *
8
+ * Гарантии:
9
+ * - порядок внутри темы — как у ядра; события обрабатываются по одному;
10
+ * - доставка «хотя бы раз»: закладка (идентификатор последней записи потока)
11
+ * сохраняется ПОСЛЕ обработчиков. Упавшее между ними приложение получит
12
+ * событие снова — обработчик обязан выдерживать повтор. Закладка в базе
13
+ * приложения, сохранённая одной транзакцией с изменениями обработчика,
14
+ * делает повтор невидимым;
15
+ * - повтор от издателя (одно событие в двух записях потока) отсекается по
16
+ * идентификатору события;
17
+ * - пропуск: ядро нумерует события темы подряд (`seq`). Разрыв номеров
18
+ * значит, что часть событий стёрта из потока до чтения (приложение не
19
+ * работало дольше срока хранения) — читатель объявляет событие
20
+ * {@link BUS_GAP_EVENT}, приложение пересчитывает данные целиком.
21
+ */
22
+ /** Событие шины, как его получает обработчик. */
23
+ export interface BusEvent<T = unknown> {
24
+ /** Тема шины: `chain`, `core`. */
25
+ topic: string;
26
+ /** Идентификатор события: по нему отсекаются повторы. */
27
+ id: string;
28
+ /** Имя события: `delta::soviet::decisions`, `participant::registered`, `fork`. */
29
+ type: string;
30
+ /** О ком или о чём событие. */
31
+ subject: string | null;
32
+ /** Номер блока цепи; у событий ядра его нет. */
33
+ blockNum: number | null;
34
+ /** Время события у ядра (ISO 8601). */
35
+ time: string | null;
36
+ /** Порядковый номер события в теме: номера идут подряд. */
37
+ seq: number | null;
38
+ /** Данные события. */
39
+ data: T;
40
+ }
41
+ /** Событие «пропуск в теме»: часть событий стёрта из потока до того, как приложение их прочло. */
42
+ export declare const BUS_GAP_EVENT = "bus::gap";
43
+ /** Данные события пропуска. */
44
+ export interface BusGap {
45
+ topic: string;
46
+ /** Номер последнего события, которое приложение обработало. */
47
+ lastSeq: number;
48
+ /** Номер события, полученного следом: события между ними стёрты. */
49
+ nextSeq: number;
50
+ }
51
+ /** Хранилище закладок тем: приложение держит его в своей базе. */
52
+ export interface BusCursorStore {
53
+ /** Закладка темы; `null` — приложение тему ещё не читало. */
54
+ load(topic: string): Promise<string | null>;
55
+ save(topic: string, cursor: string): Promise<void>;
56
+ }
57
+ /** Закладки в памяти: для приложения без базы. Перезапуск начинает с новых событий. */
58
+ export declare class MemoryCursorStore implements BusCursorStore {
59
+ private readonly cursors;
60
+ load(topic: string): Promise<string | null>;
61
+ save(topic: string, cursor: string): Promise<void>;
62
+ }
63
+ /** Запись потока Redis: идентификатор и плоский список «поле, значение». */
64
+ export type StreamEntry = [id: string, fields: string[]];
65
+ /** Соединение с Redis в объёме, нужном читателю. */
66
+ export interface BusRedis {
67
+ /** `XREAD BLOCK … COUNT … STREAMS …` — `null`, если за время ожидания событий нет. */
68
+ xread(streams: string[], cursors: string[], blockMs: number, count: number): Promise<Array<[stream: string, entries: StreamEntry[]]> | null>;
69
+ /** Последняя запись потока; `null` — поток пуст либо его нет. */
70
+ last(stream: string): Promise<StreamEntry | null>;
71
+ }
72
+ export interface BusReaderOptions {
73
+ redis: BusRedis;
74
+ /** Префикс потоков шины (`EVENTS_STREAM_PREFIX`), например `bus:voskhod:`. */
75
+ streamPrefix: string;
76
+ /** Темы, заявленные приложением (`EVENTS_TOPICS`). */
77
+ topics: string[];
78
+ cursors: BusCursorStore;
79
+ /** Обработка события приложением; исключение — событие будет получено снова. */
80
+ handle: (event: BusEvent) => Promise<void>;
81
+ log?: (message: string) => void;
82
+ /** Ожидание событий одним запросом, мс. */
83
+ blockMs?: number;
84
+ /** Пауза перед повтором после сбоя чтения или обработки, мс. */
85
+ retryMs?: number;
86
+ }
87
+ /** Событие из записи потока — конверт CloudEvents ядра. */
88
+ export declare function parseBusEntry(topic: string, fields: string[]): BusEvent;
89
+ export declare class BusReader {
90
+ private readonly opts;
91
+ private readonly cursors;
92
+ private readonly seen;
93
+ private running;
94
+ private loop;
95
+ constructor(opts: BusReaderOptions);
96
+ /** Запустить чтение. Возвращается после определения закладок; чтение идёт в фоне. */
97
+ start(): Promise<void>;
98
+ /** Остановить чтение; ждёт завершения обработчика события в полёте. */
99
+ stop(): Promise<void>;
100
+ /** Определить закладки без запуска цикла — для тестов. */
101
+ init(): Promise<void>;
102
+ /** Один проход чтения: получить события и обработать по порядку. */
103
+ poll(): Promise<number>;
104
+ private stream;
105
+ private log;
106
+ /**
107
+ * Закладка темы при старте. Первое чтение начинается с конца потока:
108
+ * прошлое приложение собирает само при установке.
109
+ */
110
+ private initCursor;
111
+ private run;
112
+ private deliver;
113
+ }
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ /**
3
+ * Чтение шины событий узла приложением каталога (487-42).
4
+ *
5
+ * Шина — потоки Redis узла `bus:<кооператив>:<тема>`; издаёт их ядро после
6
+ * собственной обработки события. Приложение читает потоки блокирующим
7
+ * чтением: соединение открыто постоянно, приложение получает событие без опроса.
8
+ *
9
+ * Гарантии:
10
+ * - порядок внутри темы — как у ядра; события обрабатываются по одному;
11
+ * - доставка «хотя бы раз»: закладка (идентификатор последней записи потока)
12
+ * сохраняется ПОСЛЕ обработчиков. Упавшее между ними приложение получит
13
+ * событие снова — обработчик обязан выдерживать повтор. Закладка в базе
14
+ * приложения, сохранённая одной транзакцией с изменениями обработчика,
15
+ * делает повтор невидимым;
16
+ * - повтор от издателя (одно событие в двух записях потока) отсекается по
17
+ * идентификатору события;
18
+ * - пропуск: ядро нумерует события темы подряд (`seq`). Разрыв номеров
19
+ * значит, что часть событий стёрта из потока до чтения (приложение не
20
+ * работало дольше срока хранения) — читатель объявляет событие
21
+ * {@link BUS_GAP_EVENT}, приложение пересчитывает данные целиком.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.BusReader = exports.MemoryCursorStore = exports.BUS_GAP_EVENT = void 0;
25
+ exports.parseBusEntry = parseBusEntry;
26
+ /** Событие «пропуск в теме»: часть событий стёрта из потока до того, как приложение их прочло. */
27
+ exports.BUS_GAP_EVENT = 'bus::gap';
28
+ /** Закладки в памяти: для приложения без базы. Перезапуск начинает с новых событий. */
29
+ class MemoryCursorStore {
30
+ cursors = new Map();
31
+ async load(topic) {
32
+ return this.cursors.get(topic) ?? null;
33
+ }
34
+ async save(topic, cursor) {
35
+ this.cursors.set(topic, cursor);
36
+ }
37
+ }
38
+ exports.MemoryCursorStore = MemoryCursorStore;
39
+ /** Событие из записи потока — конверт CloudEvents ядра. */
40
+ function parseBusEntry(topic, fields) {
41
+ const map = new Map();
42
+ for (let i = 0; i + 1 < fields.length; i += 2)
43
+ map.set(fields[i], fields[i + 1]);
44
+ let data = null;
45
+ try {
46
+ data = JSON.parse(map.get('data') ?? 'null');
47
+ }
48
+ catch {
49
+ data = null;
50
+ }
51
+ const blockNum = map.get('blocknum');
52
+ const seq = map.get('seq');
53
+ return {
54
+ topic,
55
+ id: map.get('id') ?? '',
56
+ type: map.get('type') ?? '',
57
+ subject: map.get('subject') ?? null,
58
+ blockNum: blockNum !== undefined ? Number(blockNum) : null,
59
+ time: map.get('time') ?? null,
60
+ seq: seq !== undefined ? Number(seq) : null,
61
+ data,
62
+ };
63
+ }
64
+ /** Сколько последних идентификаторов событий темы читатель помнит для отсева повторов издателя. */
65
+ const SEEN_LIMIT = 2000;
66
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
67
+ function parseCursor(value) {
68
+ const [entryId, seq] = value.split('|');
69
+ return { entryId, seq: seq !== undefined && seq !== '' ? Number(seq) : null };
70
+ }
71
+ function formatCursor(cursor) {
72
+ return cursor.seq === null ? cursor.entryId : `${cursor.entryId}|${cursor.seq}`;
73
+ }
74
+ class BusReader {
75
+ opts;
76
+ cursors = new Map();
77
+ seen = new Map();
78
+ running = false;
79
+ loop = null;
80
+ constructor(opts) {
81
+ this.opts = opts;
82
+ }
83
+ /** Запустить чтение. Возвращается после определения закладок; чтение идёт в фоне. */
84
+ async start() {
85
+ if (this.running || this.opts.topics.length === 0)
86
+ return;
87
+ this.running = true;
88
+ for (const topic of this.opts.topics)
89
+ await this.initCursor(topic);
90
+ this.loop = this.run();
91
+ }
92
+ /** Остановить чтение; ждёт завершения обработчика события в полёте. */
93
+ async stop() {
94
+ this.running = false;
95
+ await this.loop?.catch(() => undefined);
96
+ this.loop = null;
97
+ }
98
+ /** Определить закладки без запуска цикла — для тестов. */
99
+ async init() {
100
+ for (const topic of this.opts.topics)
101
+ await this.initCursor(topic);
102
+ }
103
+ /** Один проход чтения: получить события и обработать по порядку. */
104
+ async poll() {
105
+ const topics = this.opts.topics;
106
+ const streams = topics.map((topic) => this.stream(topic));
107
+ const from = topics.map((topic) => this.cursors.get(topic).entryId);
108
+ const batches = await this.opts.redis.xread(streams, from, this.opts.blockMs ?? 15_000, 100);
109
+ let handled = 0;
110
+ for (const [stream, entries] of batches ?? []) {
111
+ const topic = topics[streams.indexOf(stream)];
112
+ for (const [entryId, fields] of entries) {
113
+ await this.deliver(topic, entryId, parseBusEntry(topic, fields));
114
+ handled += 1;
115
+ }
116
+ }
117
+ return handled;
118
+ }
119
+ stream(topic) {
120
+ return `${this.opts.streamPrefix}${topic}`;
121
+ }
122
+ log(message) {
123
+ (this.opts.log ?? console.log)(`[extension-sdk] ${message}`);
124
+ }
125
+ /**
126
+ * Закладка темы при старте. Первое чтение начинается с конца потока:
127
+ * прошлое приложение собирает само при установке.
128
+ */
129
+ async initCursor(topic) {
130
+ const saved = await this.opts.cursors.load(topic);
131
+ if (saved !== null) {
132
+ this.cursors.set(topic, parseCursor(saved));
133
+ return;
134
+ }
135
+ const last = await this.opts.redis.last(this.stream(topic));
136
+ const cursor = last ? { entryId: last[0], seq: parseBusEntry(topic, last[1]).seq } : { entryId: '0-0', seq: null };
137
+ await this.opts.cursors.save(topic, formatCursor(cursor));
138
+ this.cursors.set(topic, cursor);
139
+ }
140
+ async run() {
141
+ while (this.running) {
142
+ try {
143
+ await this.poll();
144
+ }
145
+ catch (error) {
146
+ if (!this.running)
147
+ return;
148
+ // Сбой чтения (Redis перезапущен, роль ещё не выдана заново) и сбой
149
+ // обработчика лечатся одинаково: пауза и повтор с той же закладки.
150
+ this.log(`чтение шины отложено: ${error instanceof Error ? error.message : String(error)}`);
151
+ await sleep(this.opts.retryMs ?? 5_000);
152
+ }
153
+ }
154
+ }
155
+ async deliver(topic, entryId, event) {
156
+ const cursor = this.cursors.get(topic);
157
+ // Разрыв номеров: события между закладкой и этой записью стёрты из потока.
158
+ // Номер меньше ожидаемого — поток заведён заново; для приложения это тот же пропуск.
159
+ if (cursor.seq !== null && event.seq !== null && event.seq !== cursor.seq + 1) {
160
+ this.log(`пропуск в теме ${topic}: после события ${cursor.seq} получено ${event.seq}`);
161
+ await this.opts.handle({
162
+ topic,
163
+ id: `gap:${topic}:${cursor.seq}:${event.seq}`,
164
+ type: exports.BUS_GAP_EVENT,
165
+ subject: null,
166
+ blockNum: null,
167
+ time: null,
168
+ seq: null,
169
+ data: { topic, lastSeq: cursor.seq, nextSeq: event.seq },
170
+ });
171
+ }
172
+ const seen = this.seen.get(topic) ?? new Set();
173
+ this.seen.set(topic, seen);
174
+ if (event.id === '' || !seen.has(event.id)) {
175
+ // Исключение обработчика поднимается в цикл: закладка не двигается, читатель получит событие снова.
176
+ await this.opts.handle(event);
177
+ if (event.id !== '') {
178
+ seen.add(event.id);
179
+ if (seen.size > SEEN_LIMIT)
180
+ seen.delete(seen.values().next().value);
181
+ }
182
+ }
183
+ const next = { entryId, seq: event.seq ?? cursor.seq };
184
+ await this.opts.cursors.save(topic, formatCursor(next));
185
+ this.cursors.set(topic, next);
186
+ }
187
+ }
188
+ exports.BusReader = BusReader;
@@ -0,0 +1,76 @@
1
+ import { DynamicModule, type OnApplicationBootstrap, type OnModuleDestroy } from '@nestjs/common';
2
+ import { EventEmitter2 } from '@nestjs/event-emitter';
3
+ import { type BusCursorStore, type BusRedis, type StreamEntry } from './bus-reader';
4
+ export interface ExtensionEventsOptions {
5
+ /** Адрес Redis шины с ролью приложения (`EVENTS_REDIS_URL`). */
6
+ redisUrl: string;
7
+ /** Префикс потоков шины (`EVENTS_STREAM_PREFIX`). */
8
+ streamPrefix: string;
9
+ /** Темы шины, заявленные в манифесте (`EVENTS_TOPICS`). */
10
+ topics: string[];
11
+ /**
12
+ * Адрес базы приложения (`DATABASE_URL`): закладки тем хранятся в таблице
13
+ * `app_event_cursors`. Без базы закладки живут в памяти, и перезапуск
14
+ * приложения начинает чтение с новых событий.
15
+ */
16
+ databaseUrl?: string;
17
+ }
18
+ export declare const EXTENSION_EVENTS_OPTIONS: unique symbol;
19
+ /** Redis шины для читателя: отдельное соединение под блокирующее чтение. */
20
+ export declare class IoredisBus implements BusRedis {
21
+ private readonly client;
22
+ constructor(url: string, onError: (message: string) => void);
23
+ xread(streams: string[], cursors: string[], blockMs: number, count: number): Promise<Array<[string, StreamEntry[]]> | null>;
24
+ last(stream: string): Promise<StreamEntry | null>;
25
+ close(): Promise<void>;
26
+ }
27
+ /** Закладки тем в базе приложения: таблица `app_event_cursors`. */
28
+ export declare class PostgresCursorStore implements BusCursorStore {
29
+ private ready;
30
+ /** Одно соединение: закладка сохраняется после каждого события, по очереди. */
31
+ private readonly pool;
32
+ constructor(databaseUrl: string);
33
+ private query;
34
+ private init;
35
+ load(topic: string): Promise<string | null>;
36
+ save(topic: string, cursor: string): Promise<void>;
37
+ }
38
+ /**
39
+ * Читатель шины в приложении Nest: событие шины объявляется в местной шине
40
+ * приложения под тем же именем, что в ядре, и его получают обработчики
41
+ * `@OnEvent`. Событие, полученное из шины, — {@link BusEvent}: данные лежат
42
+ * в `event.data`.
43
+ */
44
+ export declare class ExtensionEventsService implements OnApplicationBootstrap, OnModuleDestroy {
45
+ private readonly options;
46
+ private readonly emitter;
47
+ private readonly logger;
48
+ private reader;
49
+ private redis;
50
+ constructor(options: ExtensionEventsOptions, emitter: EventEmitter2);
51
+ onApplicationBootstrap(): Promise<void>;
52
+ onModuleDestroy(): Promise<void>;
53
+ /** Обработчики получают событие по очереди; ошибка обработчика возвращает событие на повтор. */
54
+ private dispatch;
55
+ }
56
+ /**
57
+ * Модуль шины событий узла для приложения каталога.
58
+ *
59
+ * ```ts
60
+ * ExtensionEventsModule.forRoot({
61
+ * redisUrl: cfg.eventsRedisUrl, streamPrefix: cfg.eventsStreamPrefix,
62
+ * topics: cfg.eventsTopics, databaseUrl: cfg.databaseUrl,
63
+ * })
64
+ * // в сервисе приложения — как в монолите:
65
+ * @OnEvent('participant::registered', { suppressErrors: false })
66
+ * async onRegistered(event: BusEvent<{ username: string }>) { … }
67
+ * ```
68
+ *
69
+ * `suppressErrors: false` обязателен: без него Nest проглатывает ошибку
70
+ * обработчика, закладка двигается, и событие теряется. Модуль сам подключает
71
+ * `EventEmitterModule`; приложению подключать его повторно нельзя — получится
72
+ * две несвязанные шины.
73
+ */
74
+ export declare class ExtensionEventsModule {
75
+ static forRoot(options: ExtensionEventsOptions): DynamicModule;
76
+ }
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ var ExtensionEventsModule_1;
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.ExtensionEventsModule = exports.ExtensionEventsService = exports.PostgresCursorStore = exports.IoredisBus = exports.EXTENSION_EVENTS_OPTIONS = void 0;
20
+ const common_1 = require("@nestjs/common");
21
+ const event_emitter_1 = require("@nestjs/event-emitter");
22
+ const ioredis_1 = __importDefault(require("ioredis"));
23
+ const pg_1 = require("pg");
24
+ const bus_reader_1 = require("./bus-reader");
25
+ exports.EXTENSION_EVENTS_OPTIONS = Symbol('ExtensionSdk.EventsOptions');
26
+ /** Redis шины для читателя: отдельное соединение под блокирующее чтение. */
27
+ class IoredisBus {
28
+ client;
29
+ constructor(url, onError) {
30
+ // Проверка готовности командой INFO роли приложения недоступна — отключена.
31
+ this.client = new ioredis_1.default(url, { enableReadyCheck: false, maxRetriesPerRequest: null });
32
+ this.client.on('error', (error) => onError(error.message));
33
+ }
34
+ async xread(streams, cursors, blockMs, count) {
35
+ const result = await this.client.xread('COUNT', count, 'BLOCK', blockMs, 'STREAMS', ...streams, ...cursors);
36
+ return result;
37
+ }
38
+ async last(stream) {
39
+ const rows = (await this.client.xrevrange(stream, '+', '-', 'COUNT', 1));
40
+ return rows[0] ?? null;
41
+ }
42
+ async close() {
43
+ this.client.disconnect();
44
+ }
45
+ }
46
+ exports.IoredisBus = IoredisBus;
47
+ /** Закладки тем в базе приложения: таблица `app_event_cursors`. */
48
+ class PostgresCursorStore {
49
+ ready = null;
50
+ /** Одно соединение: закладка сохраняется после каждого события, по очереди. */
51
+ pool;
52
+ constructor(databaseUrl) {
53
+ this.pool = new pg_1.Pool({ connectionString: databaseUrl, max: 1 });
54
+ // Обрыв простаивающего соединения пул восстанавливает сам; без слушателя Node уронил бы процесс.
55
+ this.pool.on('error', () => undefined);
56
+ }
57
+ async query(text, params = []) {
58
+ return (await this.pool.query(text, params)).rows;
59
+ }
60
+ init() {
61
+ this.ready ??= this.query(`CREATE TABLE IF NOT EXISTS "app_event_cursors" (
62
+ "topic" character varying(64) NOT NULL PRIMARY KEY,
63
+ "cursor" character varying(128) NOT NULL,
64
+ "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
65
+ )`).then(() => undefined);
66
+ return this.ready;
67
+ }
68
+ async load(topic) {
69
+ await this.init();
70
+ const rows = await this.query('SELECT "cursor" FROM "app_event_cursors" WHERE "topic" = $1', [topic]);
71
+ return rows[0]?.cursor ?? null;
72
+ }
73
+ async save(topic, cursor) {
74
+ await this.init();
75
+ await this.query(`INSERT INTO "app_event_cursors" ("topic", "cursor") VALUES ($1, $2)
76
+ ON CONFLICT ("topic") DO UPDATE SET "cursor" = EXCLUDED."cursor", "updated_at" = now()`, [topic, cursor]);
77
+ }
78
+ }
79
+ exports.PostgresCursorStore = PostgresCursorStore;
80
+ /**
81
+ * Читатель шины в приложении Nest: событие шины объявляется в местной шине
82
+ * приложения под тем же именем, что в ядре, и его получают обработчики
83
+ * `@OnEvent`. Событие, полученное из шины, — {@link BusEvent}: данные лежат
84
+ * в `event.data`.
85
+ */
86
+ let ExtensionEventsService = class ExtensionEventsService {
87
+ options;
88
+ emitter;
89
+ logger = new common_1.Logger('ExtensionEvents');
90
+ reader = null;
91
+ redis = null;
92
+ constructor(options, emitter) {
93
+ this.options = options;
94
+ this.emitter = emitter;
95
+ }
96
+ async onApplicationBootstrap() {
97
+ if (this.options.topics.length === 0)
98
+ return;
99
+ this.redis = new IoredisBus(this.options.redisUrl, (message) => this.logger.warn(`Redis шины событий: ${message}`));
100
+ this.reader = new bus_reader_1.BusReader({
101
+ redis: this.redis,
102
+ streamPrefix: this.options.streamPrefix,
103
+ topics: this.options.topics,
104
+ cursors: this.options.databaseUrl ? new PostgresCursorStore(this.options.databaseUrl) : new bus_reader_1.MemoryCursorStore(),
105
+ handle: (event) => this.dispatch(event),
106
+ log: (message) => this.logger.log(message),
107
+ });
108
+ // Чтение запускается в фоне: недоступный Redis не держит подъём приложения.
109
+ void this.reader.start().catch((error) => this.logger.error(`Чтение шины событий не запущено: ${error.message}`));
110
+ }
111
+ async onModuleDestroy() {
112
+ await this.reader?.stop();
113
+ await this.redis?.close();
114
+ }
115
+ /** Обработчики получают событие по очереди; ошибка обработчика возвращает событие на повтор. */
116
+ async dispatch(event) {
117
+ await this.emitter.emitAsync(event.type, event);
118
+ }
119
+ };
120
+ exports.ExtensionEventsService = ExtensionEventsService;
121
+ exports.ExtensionEventsService = ExtensionEventsService = __decorate([
122
+ (0, common_1.Injectable)(),
123
+ __param(0, (0, common_1.Inject)(exports.EXTENSION_EVENTS_OPTIONS)),
124
+ __metadata("design:paramtypes", [Object, event_emitter_1.EventEmitter2])
125
+ ], ExtensionEventsService);
126
+ /**
127
+ * Модуль шины событий узла для приложения каталога.
128
+ *
129
+ * ```ts
130
+ * ExtensionEventsModule.forRoot({
131
+ * redisUrl: cfg.eventsRedisUrl, streamPrefix: cfg.eventsStreamPrefix,
132
+ * topics: cfg.eventsTopics, databaseUrl: cfg.databaseUrl,
133
+ * })
134
+ * // в сервисе приложения — как в монолите:
135
+ * @OnEvent('participant::registered', { suppressErrors: false })
136
+ * async onRegistered(event: BusEvent<{ username: string }>) { … }
137
+ * ```
138
+ *
139
+ * `suppressErrors: false` обязателен: без него Nest проглатывает ошибку
140
+ * обработчика, закладка двигается, и событие теряется. Модуль сам подключает
141
+ * `EventEmitterModule`; приложению подключать его повторно нельзя — получится
142
+ * две несвязанные шины.
143
+ */
144
+ let ExtensionEventsModule = ExtensionEventsModule_1 = class ExtensionEventsModule {
145
+ static forRoot(options) {
146
+ return {
147
+ module: ExtensionEventsModule_1,
148
+ imports: [event_emitter_1.EventEmitterModule.forRoot({ wildcard: false })],
149
+ providers: [{ provide: exports.EXTENSION_EVENTS_OPTIONS, useValue: options }, ExtensionEventsService],
150
+ exports: [ExtensionEventsService],
151
+ };
152
+ }
153
+ };
154
+ exports.ExtensionEventsModule = ExtensionEventsModule;
155
+ exports.ExtensionEventsModule = ExtensionEventsModule = ExtensionEventsModule_1 = __decorate([
156
+ (0, common_1.Global)(),
157
+ (0, common_1.Module)({})
158
+ ], ExtensionEventsModule);
@@ -3,7 +3,7 @@ import { DynamicModule } from '@nestjs/common';
3
3
  * Опции для базового федеративного subgraph'а расширения.
4
4
  *
5
5
  * @property path — путь endpoint'а GraphQL (по умолчанию `/v1/graphql`).
6
- * @property schemaFile — куда писать сгенерированную SDL (`schema.gql` по умолчанию).
6
+ * @property schemaFile — куда писать сгенерированную SDL; не задан — схема только в памяти.
7
7
  * @property introspection — оставлять true даже в проде: gateway пользуется
8
8
  * introspection'ом для пересборки supergraph'а.
9
9
  * @property playground — Apollo Sandbox в development.
@@ -26,7 +26,7 @@ const apollo_1 = require("@nestjs/apollo");
26
26
  let ExtensionFederationModule = ExtensionFederationModule_1 = class ExtensionFederationModule {
27
27
  static forRoot(options = {}) {
28
28
  const path = options.path ?? '/v1/graphql';
29
- const schemaFile = options.schemaFile ?? 'schema.gql';
29
+ const schemaFile = options.schemaFile;
30
30
  const introspection = options.introspection ?? true;
31
31
  const playground = options.playground ?? false;
32
32
  return {
@@ -37,10 +37,10 @@ let ExtensionFederationModule = ExtensionFederationModule_1 = class ExtensionFed
37
37
  path,
38
38
  introspection,
39
39
  playground,
40
- autoSchemaFile: {
41
- path: schemaFile,
42
- federation: 2,
43
- },
40
+ // Схема по умолчанию держится в памяти. Файл пишется, только если
41
+ // приложение само задало путь: контейнер приложения работает без
42
+ // прав root, и запись в каталог приложения роняла его на старте.
43
+ autoSchemaFile: schemaFile === undefined ? { federation: 2 } : { path: schemaFile, federation: 2 },
44
44
  sortSchema: true,
45
45
  }),
46
46
  ],
package/dist/index.d.ts CHANGED
@@ -11,8 +11,11 @@
11
11
  * - cross-extension references на core entity (Cooperator, Cooperative,
12
12
  * Account) — через `SharedCooperator/SharedCooperative/SharedAccount`
13
13
  * stub'ы (`@key + @external`).
14
- * - JWT валидируется тем же секретом что и core; gateway forward'ит
15
- * Authorization-header в subgraph.
14
+ * - пайщика по токену опознаёт ядро (`ExtensionAccessGuard`, порт
15
+ * `accessToken`); секрет ядра приложению не передаётся. Gateway
16
+ * forward'ит Authorization-header в subgraph.
17
+ * - порты ядра (`@coopenomics/innercoop`) приложение получает по сети через
18
+ * `ExtensionPortsModule`; набор портов заявлен в манифесте пакета.
16
19
  * - healthcheck `GET /_health` обязателен — orchestrator опрашивает.
17
20
  *
18
21
  * См. подробнее: docs/epics/E10-federation-runtime.md в репо apps-catalog
@@ -27,3 +30,9 @@ export { SharedCooperative } from './entities/shared-cooperative.entity';
27
30
  export { SharedAccount } from './entities/shared-account.entity';
28
31
  export { HealthController } from './health/health.controller';
29
32
  export { loadExtensionConfig, ExtensionConfigError, type ExtensionConfig, } from './config/extension-config';
33
+ export { ExtensionAccessGuard, type ExtensionIdentity } from './auth/extension-access.guard';
34
+ export { CorePortsClient, CorePortError, type CorePortsClientOptions } from './ports/core-ports.client';
35
+ export { ExtensionPortsModule, LIVE_FEED_PORT, REMOTE_PORT_METHODS, REMOTE_PORT_TOKENS, remotePort, type AppLiveChange, type ExtensionPortsOptions, type IAppLiveFeed, type RemotePortName, } from './ports/extension-ports.module';
36
+ export { runAppMigrations, applyAppMigrations, readAppMigrations, migrationChecksum, AppMigrationError, type AppMigrationsOptions, type AppMigrationFile, type MigrationConnection, } from './database/app-migrations';
37
+ export { BusReader, MemoryCursorStore, BUS_GAP_EVENT, parseBusEntry, type BusEvent, type BusGap, type BusCursorStore, type BusRedis, type BusReaderOptions, type StreamEntry, } from './events/bus-reader';
38
+ export { ExtensionEventsModule, ExtensionEventsService, PostgresCursorStore, type ExtensionEventsOptions, } from './events/extension-events.module';