@coopenomics/extension-kit 2026.12.1 → 2026.12.3-dev.2
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/dist/index.cjs +558 -1092
- package/dist/index.d.cts +6 -208
- package/dist/index.d.mts +6 -208
- package/dist/index.d.ts +6 -208
- package/dist/index.mjs +312 -868
- package/dist/sync/index.cjs +4 -602
- package/dist/sync/index.d.cts +1 -501
- package/dist/sync/index.d.mts +1 -501
- package/dist/sync/index.d.ts +1 -501
- package/dist/sync/index.mjs +1 -595
- package/package.json +6 -6
package/dist/sync/index.cjs
CHANGED
|
@@ -1,607 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const graphql = require('@nestjs/graphql');
|
|
5
|
-
const common = require('@nestjs/common');
|
|
6
|
-
const database = require('@coopenomics/extension-sdk/database');
|
|
7
|
-
const server = require('@coopenomics/i18n/server');
|
|
3
|
+
const sync = require('@coopenomics/extension-sdk/sync');
|
|
8
4
|
|
|
9
|
-
class BaseDomainEntity {
|
|
10
|
-
// Дата последнего обновления в базе данных
|
|
11
|
-
/**
|
|
12
|
-
* Конструктор базового класса
|
|
13
|
-
*
|
|
14
|
-
* @param databaseData - данные из базы данных
|
|
15
|
-
* @param defaultStatus - статус по умолчанию, если не указан
|
|
16
|
-
*/
|
|
17
|
-
constructor(databaseData, defaultStatus) {
|
|
18
|
-
this._id = databaseData._id === "" ? crypto.randomUUID().toString() : databaseData._id;
|
|
19
|
-
this.block_num = databaseData.block_num ?? 0;
|
|
20
|
-
this.present = databaseData.present;
|
|
21
|
-
this.status = databaseData.status ?? defaultStatus;
|
|
22
|
-
this._created_at = databaseData._created_at ? new Date(databaseData._created_at) : /* @__PURE__ */ new Date();
|
|
23
|
-
this._updated_at = databaseData._updated_at ? new Date(databaseData._updated_at) : /* @__PURE__ */ new Date();
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Обновление базовых данных сущности
|
|
27
|
-
*/
|
|
28
|
-
updateBase(data) {
|
|
29
|
-
if (data.block_num !== void 0)
|
|
30
|
-
this.block_num = data.block_num;
|
|
31
|
-
if (data.present !== void 0)
|
|
32
|
-
this.present = data.present;
|
|
33
|
-
if (data.status !== void 0)
|
|
34
|
-
this.status = data.status;
|
|
35
|
-
if (data._created_at !== void 0)
|
|
36
|
-
this._created_at = data._created_at;
|
|
37
|
-
if (data._updated_at !== void 0)
|
|
38
|
-
this._updated_at = data._updated_at;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
5
|
|
|
42
|
-
var __defProp$3 = Object.defineProperty;
|
|
43
|
-
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
|
|
44
|
-
var __decorateClass$3 = (decorators, target, key, kind) => {
|
|
45
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
|
|
46
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
47
|
-
if (decorator = decorators[i])
|
|
48
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
49
|
-
if (kind && result)
|
|
50
|
-
__defProp$3(target, key, result);
|
|
51
|
-
return result;
|
|
52
|
-
};
|
|
53
|
-
exports.BaseOutputDTO = class BaseOutputDTO {
|
|
54
|
-
};
|
|
55
|
-
__decorateClass$3([
|
|
56
|
-
graphql.Field(() => String, {
|
|
57
|
-
description: "\u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0438\u0439 ID \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445"
|
|
58
|
-
})
|
|
59
|
-
], exports.BaseOutputDTO.prototype, "_id", 2);
|
|
60
|
-
__decorateClass$3([
|
|
61
|
-
graphql.Field(() => Boolean, {
|
|
62
|
-
description: "\u0424\u043B\u0430\u0433 \u043F\u0440\u0438\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438 \u0432 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D\u0435"
|
|
63
|
-
})
|
|
64
|
-
], exports.BaseOutputDTO.prototype, "present", 2);
|
|
65
|
-
__decorateClass$3([
|
|
66
|
-
graphql.Field(() => Number, {
|
|
67
|
-
nullable: true,
|
|
68
|
-
description: "\u041D\u043E\u043C\u0435\u0440 \u0431\u043B\u043E\u043A\u0430 \u043A\u0440\u0430\u0439\u043D\u0435\u0439 \u0441\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0430\u0446\u0438\u0438 \u0441 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D\u043E\u043C"
|
|
69
|
-
})
|
|
70
|
-
], exports.BaseOutputDTO.prototype, "block_num", 2);
|
|
71
|
-
__decorateClass$3([
|
|
72
|
-
graphql.Field(() => Date, {
|
|
73
|
-
description: "\u0414\u0430\u0442\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
|
|
74
|
-
})
|
|
75
|
-
], exports.BaseOutputDTO.prototype, "_created_at", 2);
|
|
76
|
-
__decorateClass$3([
|
|
77
|
-
graphql.Field(() => Date, {
|
|
78
|
-
description: "\u0414\u0430\u0442\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0433\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
|
|
79
|
-
})
|
|
80
|
-
], exports.BaseOutputDTO.prototype, "_updated_at", 2);
|
|
81
|
-
exports.BaseOutputDTO = __decorateClass$3([
|
|
82
|
-
graphql.ObjectType("BaseEntity", {
|
|
83
|
-
description: "\u0411\u0430\u0437\u043E\u0432\u044B\u0435 \u043F\u043E\u043B\u044F \u0441\u0443\u0449\u043D\u043E\u0441\u0442\u0438"
|
|
84
|
-
})
|
|
85
|
-
], exports.BaseOutputDTO);
|
|
86
6
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
* Возвращает массив паттернов типа "delta::contract::table"
|
|
91
|
-
*/
|
|
92
|
-
getAllEventPatterns() {
|
|
93
|
-
const patterns = [];
|
|
94
|
-
const supportedContracts = this.getSupportedContractNames();
|
|
95
|
-
const supportedTables = this.getSupportedTableNames();
|
|
96
|
-
for (const contractName of supportedContracts) {
|
|
97
|
-
for (const tableName of supportedTables) {
|
|
98
|
-
patterns.push(`delta::${contractName}::${tableName}`);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
return patterns;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const FORK_AWARE_MARKER = Symbol.for("mono.controller.shared.sync.ForkAware");
|
|
106
|
-
function isForkAware(candidate) {
|
|
107
|
-
if (candidate == null)
|
|
108
|
-
return false;
|
|
109
|
-
const obj = candidate;
|
|
110
|
-
return obj[FORK_AWARE_MARKER] === true && typeof obj.handleFork === "function";
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
class UnsupportedContractVersionError extends Error {
|
|
114
|
-
constructor(entityName, context) {
|
|
115
|
-
super(
|
|
116
|
-
`Unsupported contract version while mapping delta for ${entityName}: ${JSON.stringify(context)}`
|
|
117
|
-
);
|
|
118
|
-
this.entityName = entityName;
|
|
119
|
-
this.context = context;
|
|
120
|
-
this.name = "UnsupportedContractVersionError";
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const DEFAULTS = {
|
|
125
|
-
unsupportedVersionStrict: false
|
|
126
|
-
};
|
|
127
|
-
let policy = DEFAULTS;
|
|
128
|
-
function configureSyncPolicy(next) {
|
|
129
|
-
policy = { ...DEFAULTS, ...next };
|
|
130
|
-
}
|
|
131
|
-
function syncPolicy() {
|
|
132
|
-
return policy;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
var __defProp$2 = Object.defineProperty;
|
|
136
|
-
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
|
|
137
|
-
var __decorateClass$2 = (decorators, target, key, kind) => {
|
|
138
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
|
|
139
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
140
|
-
if (decorator = decorators[i])
|
|
141
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
142
|
-
if (kind && result)
|
|
143
|
-
__defProp$2(target, key, result);
|
|
144
|
-
return result;
|
|
145
|
-
};
|
|
146
|
-
var _a;
|
|
147
|
-
exports.AbstractEntitySyncService = class AbstractEntitySyncService {
|
|
148
|
-
constructor(repository, mapper, logger) {
|
|
149
|
-
this.repository = repository;
|
|
150
|
-
this.mapper = mapper;
|
|
151
|
-
this.logger = logger;
|
|
152
|
-
/**
|
|
153
|
-
* Symbol-маркер для ForkRegistryService (Story 4.1). Все 20+ наследников
|
|
154
|
-
* автоматически попадают в реестр через bootstrap-сканирование Discovery —
|
|
155
|
-
* без правок их onModuleInit.
|
|
156
|
-
*/
|
|
157
|
-
this[_a] = true;
|
|
158
|
-
this.logger.setContext(`${this.constructor.name}`);
|
|
159
|
-
}
|
|
160
|
-
static {
|
|
161
|
-
_a = FORK_AWARE_MARKER;
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* Обработка дельты блокчейна
|
|
165
|
-
*/
|
|
166
|
-
async processDelta(delta) {
|
|
167
|
-
try {
|
|
168
|
-
this.logger.debug(`Processing ${this.entityName} delta for table ${delta.table} with key ${delta.primary_key}`);
|
|
169
|
-
const syncValue = this.mapper.extractSyncValue(delta);
|
|
170
|
-
const syncKey = this.mapper.extractSyncKey();
|
|
171
|
-
const blockchainData = this.mapper.mapDeltaToBlockchainData(delta);
|
|
172
|
-
if (!blockchainData) {
|
|
173
|
-
const ctx = {
|
|
174
|
-
contract: delta.contract ?? delta.code,
|
|
175
|
-
table: delta.table,
|
|
176
|
-
primary_key: delta.primary_key,
|
|
177
|
-
block_num: Number(delta.block_num)
|
|
178
|
-
};
|
|
179
|
-
this.logger.error(
|
|
180
|
-
`UNSUPPORTED_CONTRACT_VERSION: mapDeltaToBlockchainData returned null for ${this.entityName} ${syncValue}`,
|
|
181
|
-
{ entity: this.entityName, syncValue, ...ctx }
|
|
182
|
-
);
|
|
183
|
-
if (syncPolicy().unsupportedVersionStrict) {
|
|
184
|
-
throw new UnsupportedContractVersionError(this.entityName, ctx);
|
|
185
|
-
}
|
|
186
|
-
return null;
|
|
187
|
-
}
|
|
188
|
-
const blockNum = Number(delta.block_num);
|
|
189
|
-
const present = delta.present !== false;
|
|
190
|
-
return await this.handleSyncDelta(syncKey, syncValue, blockchainData, blockNum, present);
|
|
191
|
-
} catch (error) {
|
|
192
|
-
if (error instanceof UnsupportedContractVersionError)
|
|
193
|
-
throw error;
|
|
194
|
-
this.logger.error(`Error processing ${this.entityName} delta: ${error.message}`, error.stack);
|
|
195
|
-
return null;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Обработка создания/обновления сущности
|
|
200
|
-
*/
|
|
201
|
-
async handleSyncDelta(syncKey, syncValue, blockchainData, blockNum, present = true) {
|
|
202
|
-
const existingEntity = await this.repository.findBySyncKey(syncKey, syncValue);
|
|
203
|
-
if (existingEntity) {
|
|
204
|
-
const currentBlockNum = existingEntity.getBlockNum();
|
|
205
|
-
if (currentBlockNum && blockNum < currentBlockNum) {
|
|
206
|
-
this.logger.debug(
|
|
207
|
-
`Skipping outdated update for ${this.entityName} ${syncValue}: block ${blockNum} <= ${currentBlockNum}`
|
|
208
|
-
);
|
|
209
|
-
return {
|
|
210
|
-
created: false,
|
|
211
|
-
updated: false,
|
|
212
|
-
blockchainId: syncValue,
|
|
213
|
-
blockNum: currentBlockNum
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
existingEntity.updateFromBlockchain(blockchainData, blockNum, present);
|
|
217
|
-
await this.repository.update(existingEntity);
|
|
218
|
-
this.logger.debug(`\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D ${this.entityName} ${syncValue} \u0432 \u0431\u043B\u043E\u043A\u0435 ${blockNum}`);
|
|
219
|
-
return {
|
|
220
|
-
created: false,
|
|
221
|
-
updated: true,
|
|
222
|
-
blockchainId: syncValue,
|
|
223
|
-
blockNum
|
|
224
|
-
};
|
|
225
|
-
} else {
|
|
226
|
-
await this.repository.createIfNotExists(blockchainData, blockNum, present);
|
|
227
|
-
this.logger.debug(`\u0421\u043E\u0437\u0434\u0430\u043D ${this.entityName} ${syncValue} \u0432 \u0431\u043B\u043E\u043A\u0435 ${blockNum}`);
|
|
228
|
-
return {
|
|
229
|
-
created: true,
|
|
230
|
-
updated: false,
|
|
231
|
-
blockchainId: syncValue,
|
|
232
|
-
blockNum
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Обработка удаления сущности
|
|
238
|
-
*/
|
|
239
|
-
async handleEntityDeletion(syncValue, blockNum) {
|
|
240
|
-
this.logger.debug(`Entity ${this.entityName} ${syncValue} was deleted at block ${blockNum}`);
|
|
241
|
-
return {
|
|
242
|
-
created: false,
|
|
243
|
-
updated: false,
|
|
244
|
-
blockchainId: syncValue,
|
|
245
|
-
blockNum
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Обработка форка — архивирование снесённых сущностей + восстановление из versions
|
|
250
|
-
* + архивирование инвалидированных версий.
|
|
251
|
-
*
|
|
252
|
-
* Story 4.1: ошибки больше НЕ глотаются — обязательный re-throw для контракта
|
|
253
|
-
* sequential ForkRegistry.runAll (INV-T03). Если rollback упадёт — parser2 не
|
|
254
|
-
* ACK'нет fork-event, повторная доставка пересыграет цепочку. Уже отработавшие
|
|
255
|
-
* syncer'ы в цепи будут no-op (versions уже подняты), сбойный — попробует ещё раз.
|
|
256
|
-
*
|
|
257
|
-
* Story 4.4: hard-delete заменён на «архив + delete» атомарно. Порядок:
|
|
258
|
-
* 1) archiveInvalidatedSince — live-ряды WHERE block_num > N переезжают в
|
|
259
|
-
* invalidated_entities, оригинал удаляется (одна транзакция).
|
|
260
|
-
* 2) restoreFromVersions — поднять previous_data из ещё-живых entity_versions.
|
|
261
|
-
* 3) archiveInvalidatedVersionsSince — entity_versions WHERE entity_table=... AND
|
|
262
|
-
* block_num > N переезжают в invalidated_entity_versions, оригинал удаляется.
|
|
263
|
-
* Запускается ПОСЛЕ restore, иначе restore не сможет прочитать живые версии.
|
|
264
|
-
* Если репо не реализует archive методы (off-chain) — graceful no-op + fallback
|
|
265
|
-
* на старую findByBlockNumGreaterThan/deleteByBlockNumGreaterThan для бэк-совместимости.
|
|
266
|
-
*/
|
|
267
|
-
async handleFork(forkBlockNum, forkEventId) {
|
|
268
|
-
this.logger.log(`Handling fork for ${this.entityName} at block ${forkBlockNum} (eventId=${forkEventId ?? "n/a"})`);
|
|
269
|
-
let archivedLive = 0;
|
|
270
|
-
if (this.repository.archiveInvalidatedSince) {
|
|
271
|
-
archivedLive = await this.repository.archiveInvalidatedSince(forkBlockNum, forkEventId);
|
|
272
|
-
this.logger.log(
|
|
273
|
-
`\u0410\u0440\u0445\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D\u043E ${archivedLive} live-\u0440\u044F\u0434\u043E\u0432 ${this.entityName} \u043D\u0430 \u0444\u043E\u0440\u043A\u0435 ${forkBlockNum}`
|
|
274
|
-
);
|
|
275
|
-
} else {
|
|
276
|
-
const affected = await this.repository.findByBlockNumGreaterThan(forkBlockNum);
|
|
277
|
-
await this.repository.deleteByBlockNumGreaterThan(forkBlockNum);
|
|
278
|
-
archivedLive = affected.length;
|
|
279
|
-
this.logger.warn(
|
|
280
|
-
`${this.entityName}: archiveInvalidatedSince \u043D\u0435 \u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u043D \u2014 fallback \u043D\u0430 hard-delete (${archivedLive} \u0440\u044F\u0434\u043E\u0432)`
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
if (this.repository.restoreFromVersions) {
|
|
284
|
-
await this.repository.restoreFromVersions(forkBlockNum);
|
|
285
|
-
this.logger.log(`Restored ${this.entityName} entities from versions after fork at block ${forkBlockNum}`);
|
|
286
|
-
}
|
|
287
|
-
if (this.repository.archiveInvalidatedVersionsSince) {
|
|
288
|
-
const archivedVersions = await this.repository.archiveInvalidatedVersionsSince(forkBlockNum, forkEventId);
|
|
289
|
-
this.logger.log(
|
|
290
|
-
`\u0410\u0440\u0445\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D\u043E ${archivedVersions} \u0432\u0435\u0440\u0441\u0438\u0439 ${this.entityName} \u043D\u0430 \u0444\u043E\u0440\u043A\u0435 ${forkBlockNum}`
|
|
291
|
-
);
|
|
292
|
-
}
|
|
293
|
-
await this.afterForkProcessing(forkBlockNum, []);
|
|
294
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Дополнительные действия после обработки форка
|
|
297
|
-
* Может быть переопределен в наследниках
|
|
298
|
-
*/
|
|
299
|
-
async afterForkProcessing(_forkBlockNum, _affectedEntities) {
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Получение всех возможных имен событий для подписки
|
|
303
|
-
*/
|
|
304
|
-
getAllEventPatterns() {
|
|
305
|
-
return this.mapper.getAllEventPatterns();
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Получение всех поддерживаемых таблиц и контрактов для логирования
|
|
309
|
-
*/
|
|
310
|
-
getSupportedVersions() {
|
|
311
|
-
return {
|
|
312
|
-
contracts: this.mapper.getSupportedContractNames(),
|
|
313
|
-
tables: this.mapper.getSupportedTableNames()
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
/**
|
|
317
|
-
* Получение имени события для подписки на форки
|
|
318
|
-
*/
|
|
319
|
-
getForkEventPattern() {
|
|
320
|
-
return "fork::*";
|
|
321
|
-
}
|
|
322
|
-
};
|
|
323
|
-
exports.AbstractEntitySyncService = __decorateClass$2([
|
|
324
|
-
common.Injectable()
|
|
325
|
-
], exports.AbstractEntitySyncService);
|
|
326
|
-
|
|
327
|
-
class ChainRecord {
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
var __defProp$1 = Object.defineProperty;
|
|
331
|
-
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
332
|
-
var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
333
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
334
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
335
|
-
if (decorator = decorators[i])
|
|
336
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
337
|
-
if (kind && result)
|
|
338
|
-
__defProp$1(target, key, result);
|
|
339
|
-
return result;
|
|
340
|
-
};
|
|
341
|
-
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
342
|
-
exports.ChainVersioningService = class ChainVersioningService {
|
|
343
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
344
|
-
constructor(db) {
|
|
345
|
-
this.db = db;
|
|
346
|
-
}
|
|
347
|
-
/** Кладёт в версии состояние записи перед её изменением; новой записи версионировать нечего. */
|
|
348
|
-
async saveVersionBeforeUpdate(store, updated, blockNum, changeType, metadata) {
|
|
349
|
-
if (!updated._id)
|
|
350
|
-
return;
|
|
351
|
-
const existing = await store.findOne({ _id: updated._id });
|
|
352
|
-
if (!existing)
|
|
353
|
-
return;
|
|
354
|
-
await this.db.insertInto("entity_versions").values({
|
|
355
|
-
entity_table: store.table,
|
|
356
|
-
entity_id: existing._id,
|
|
357
|
-
previous_data: JSON.stringify(existing),
|
|
358
|
-
block_num: blockNum,
|
|
359
|
-
change_type: changeType,
|
|
360
|
-
metadata: metadata ? JSON.stringify(metadata) : null
|
|
361
|
-
}).execute();
|
|
362
|
-
}
|
|
363
|
-
/**
|
|
364
|
-
* Возвращает записи таблицы к состоянию на блоке форка.
|
|
365
|
-
*
|
|
366
|
-
* Версия хранит состояние записи ДО изменения и блок самого изменения. После
|
|
367
|
-
* форка недействительны изменения с блоком больше блока форка, поэтому для
|
|
368
|
-
* каждой записи берётся самое раннее такое изменение: состояние перед ним и
|
|
369
|
-
* есть состояние на блоке форка. Запись без изменений после форка остаётся
|
|
370
|
-
* как есть.
|
|
371
|
-
*/
|
|
372
|
-
async restoreVersionsAfterFork(store, forkBlockNum) {
|
|
373
|
-
const invalidated = await this.db.selectFrom("entity_versions").selectAll().where("entity_table", "=", store.table).where("block_num", ">", forkBlockNum).orderBy("entity_id", "asc").orderBy("block_num", "asc").orderBy("created_at", "asc").execute();
|
|
374
|
-
const firstInvalidated = /* @__PURE__ */ new Map();
|
|
375
|
-
for (const version of invalidated) {
|
|
376
|
-
if (!firstInvalidated.has(version.entity_id))
|
|
377
|
-
firstInvalidated.set(version.entity_id, version);
|
|
378
|
-
}
|
|
379
|
-
for (const [entityId, version] of firstInvalidated) {
|
|
380
|
-
const state = version.previous_data;
|
|
381
|
-
if (!state || appearedAfter(state, forkBlockNum))
|
|
382
|
-
continue;
|
|
383
|
-
const existing = await store.findOne({ _id: entityId });
|
|
384
|
-
await store.save(Object.assign(existing ?? {}, state));
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* Переносит записи таблицы с блоком больше блока форка в архив
|
|
389
|
-
* `invalidated_entities` и убирает их из таблицы — одной транзакцией.
|
|
390
|
-
* Возвращает число перенесённых записей.
|
|
391
|
-
*/
|
|
392
|
-
async archiveAndDeleteLiveAfterFork(store, forkBlockNum, forkEventId) {
|
|
393
|
-
return database.inTransaction(this.db, async (trx) => {
|
|
394
|
-
const live = store.on(trx);
|
|
395
|
-
const rows = await live.find({ block_num: database.moreThan(forkBlockNum) });
|
|
396
|
-
if (rows.length === 0)
|
|
397
|
-
return 0;
|
|
398
|
-
await trx.insertInto("invalidated_entities").values(
|
|
399
|
-
rows.map((row) => ({
|
|
400
|
-
entity_table: store.table,
|
|
401
|
-
entity_id: row._id,
|
|
402
|
-
data: JSON.stringify(row),
|
|
403
|
-
invalidated_by_block: forkBlockNum,
|
|
404
|
-
fork_event_id: forkEventId ?? null
|
|
405
|
-
}))
|
|
406
|
-
).execute();
|
|
407
|
-
await live.delete({ block_num: database.moreThan(forkBlockNum) });
|
|
408
|
-
return rows.length;
|
|
409
|
-
});
|
|
410
|
-
}
|
|
411
|
-
/**
|
|
412
|
-
* Чистит архив форка: записи и версии, отменённые блоком раньше заданного.
|
|
413
|
-
* Возвращает число удалённых записей и версий.
|
|
414
|
-
*/
|
|
415
|
-
async deleteArchiveOlderThan(minInvalidatedByBlock) {
|
|
416
|
-
const entities = await this.db.deleteFrom("invalidated_entities").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
|
|
417
|
-
const versions = await this.db.deleteFrom("invalidated_entity_versions").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
|
|
418
|
-
return { entities: database.affectedCount(entities), versions: database.affectedCount(versions) };
|
|
419
|
-
}
|
|
420
|
-
/**
|
|
421
|
-
* Переносит версии таблицы с блоком больше блока форка в архив
|
|
422
|
-
* `invalidated_entity_versions` и убирает их из `entity_versions` — одной
|
|
423
|
-
* транзакцией. Зовётся ПОСЛЕ восстановления: оно читает эти версии.
|
|
424
|
-
*/
|
|
425
|
-
async archiveAndDeleteVersionsAfterFork(entityTable, forkBlockNum, forkEventId) {
|
|
426
|
-
return database.inTransaction(this.db, async (trx) => {
|
|
427
|
-
const versions = await trx.selectFrom("entity_versions").selectAll().where("entity_table", "=", entityTable).where("block_num", ">", forkBlockNum).execute();
|
|
428
|
-
if (versions.length === 0)
|
|
429
|
-
return 0;
|
|
430
|
-
await trx.insertInto("invalidated_entity_versions").values(
|
|
431
|
-
versions.map((version) => ({
|
|
432
|
-
entity_table: version.entity_table,
|
|
433
|
-
entity_id: version.entity_id,
|
|
434
|
-
previous_data: JSON.stringify(version.previous_data),
|
|
435
|
-
original_block_num: version.block_num ?? null,
|
|
436
|
-
invalidated_by_block: forkBlockNum,
|
|
437
|
-
fork_event_id: forkEventId ?? null,
|
|
438
|
-
change_type: version.change_type,
|
|
439
|
-
metadata: version.metadata ? JSON.stringify(version.metadata) : null
|
|
440
|
-
}))
|
|
441
|
-
).execute();
|
|
442
|
-
await trx.deleteFrom("entity_versions").where(
|
|
443
|
-
"id",
|
|
444
|
-
"in",
|
|
445
|
-
versions.map((version) => version.id)
|
|
446
|
-
).execute();
|
|
447
|
-
return versions.length;
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
};
|
|
451
|
-
exports.ChainVersioningService = __decorateClass$1([
|
|
452
|
-
common.Injectable(),
|
|
453
|
-
__decorateParam(0, common.Inject(database.KYSELY))
|
|
454
|
-
], exports.ChainVersioningService);
|
|
455
|
-
function appearedAfter(state, forkBlockNum) {
|
|
456
|
-
const block = state.block_num;
|
|
457
|
-
return block !== null && block !== void 0 && Number(block) > forkBlockNum;
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
var __defProp = Object.defineProperty;
|
|
461
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
462
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
463
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
464
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
465
|
-
if (decorator = decorators[i])
|
|
466
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
467
|
-
if (kind && result)
|
|
468
|
-
__defProp(target, key, result);
|
|
469
|
-
return result;
|
|
470
|
-
};
|
|
471
|
-
exports.BaseChainRepository = class BaseChainRepository {
|
|
472
|
-
constructor(repository, versioning) {
|
|
473
|
-
this.repository = repository;
|
|
474
|
-
this.versioning = versioning;
|
|
475
|
-
}
|
|
476
|
-
getEntityTableName() {
|
|
477
|
-
return this.repository.table;
|
|
478
|
-
}
|
|
479
|
-
async findBySyncKey(syncKey, syncValue) {
|
|
480
|
-
const record = await this.repository.findOne({ [syncKey]: String(syncValue).toLowerCase() });
|
|
481
|
-
return record ? this.getMapper().toDomain(record) : null;
|
|
482
|
-
}
|
|
483
|
-
async findByBlockNumGreaterThan(blockNum) {
|
|
484
|
-
const records = await this.repository.find({ block_num: database.moreThan(blockNum) });
|
|
485
|
-
return records.map((record) => this.getMapper().toDomain(record));
|
|
486
|
-
}
|
|
487
|
-
/** Создаёт запись из данных цепи либо обновляет существующую. */
|
|
488
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
489
|
-
async createIfNotExists(blockchainData, blockNum, present = true) {
|
|
490
|
-
const syncKey = this.getSyncKey();
|
|
491
|
-
const syncValue = this.extractSyncValueFromBlockchainData(blockchainData, syncKey);
|
|
492
|
-
const existing = await this.findBySyncKey(syncKey, syncValue);
|
|
493
|
-
if (!existing) {
|
|
494
|
-
const now = /* @__PURE__ */ new Date();
|
|
495
|
-
const created = this.createDomainEntity(
|
|
496
|
-
{ _id: "", block_num: blockNum, present, _created_at: now, _updated_at: now, [syncKey]: String(syncValue).toLowerCase() },
|
|
497
|
-
blockchainData
|
|
498
|
-
);
|
|
499
|
-
return this.save(created);
|
|
500
|
-
}
|
|
501
|
-
const existingBlockNum = existing.getBlockNum();
|
|
502
|
-
if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum))
|
|
503
|
-
return existing;
|
|
504
|
-
existing.updateFromBlockchain(blockchainData, blockNum, present);
|
|
505
|
-
return this.save(existing);
|
|
506
|
-
}
|
|
507
|
-
async deleteByBlockNumGreaterThan(blockNum) {
|
|
508
|
-
await this.repository.delete({ block_num: database.moreThan(blockNum) });
|
|
509
|
-
}
|
|
510
|
-
async restoreFromVersions(forkBlockNum) {
|
|
511
|
-
await this.versioning.restoreVersionsAfterFork(this.repository, forkBlockNum);
|
|
512
|
-
}
|
|
513
|
-
/** Переносит записи после блока форка в архив и убирает их из таблицы. */
|
|
514
|
-
async archiveInvalidatedSince(forkBlockNum, forkEventId) {
|
|
515
|
-
return this.versioning.archiveAndDeleteLiveAfterFork(this.repository, forkBlockNum, forkEventId);
|
|
516
|
-
}
|
|
517
|
-
/** Переносит версии после блока форка в архив; зовётся после восстановления. */
|
|
518
|
-
async archiveInvalidatedVersionsSince(forkBlockNum, forkEventId) {
|
|
519
|
-
return this.versioning.archiveAndDeleteVersionsAfterFork(this.getEntityTableName(), forkBlockNum, forkEventId);
|
|
520
|
-
}
|
|
521
|
-
async update(entity) {
|
|
522
|
-
return this.persist(entity, "update");
|
|
523
|
-
}
|
|
524
|
-
async save(entity) {
|
|
525
|
-
return this.persist(entity, "save");
|
|
526
|
-
}
|
|
527
|
-
/** Заготовка записи без сохранения в базу. */
|
|
528
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
529
|
-
async create(entity) {
|
|
530
|
-
return this.repository.create(this.getMapper().toEntity(entity));
|
|
531
|
-
}
|
|
532
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
533
|
-
async saveCreated(record) {
|
|
534
|
-
return this.getMapper().toDomain(await this.repository.save(withoutEmptyKey(record)));
|
|
535
|
-
}
|
|
536
|
-
async findAll() {
|
|
537
|
-
const records = await this.repository.find();
|
|
538
|
-
return records.map((record) => this.getMapper().toDomain(record));
|
|
539
|
-
}
|
|
540
|
-
async findById(_id) {
|
|
541
|
-
const record = await this.repository.findOne({ _id });
|
|
542
|
-
return record ? this.getMapper().toDomain(record) : null;
|
|
543
|
-
}
|
|
544
|
-
async delete(_id) {
|
|
545
|
-
await this.repository.delete({ _id });
|
|
546
|
-
}
|
|
547
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
548
|
-
extractSyncValueFromBlockchainData(blockchainData, syncKey) {
|
|
549
|
-
const value = blockchainData[syncKey];
|
|
550
|
-
if (value === null || value === void 0) {
|
|
551
|
-
throw new Error(`Sync key '${syncKey}' not found in blockchain data`);
|
|
552
|
-
}
|
|
553
|
-
return value.toString().toLowerCase();
|
|
554
|
-
}
|
|
555
|
-
/** Сохраняет запись; у существующей перед изменением кладёт прежнее состояние в версии. */
|
|
556
|
-
async persist(entity, changeType) {
|
|
557
|
-
const record = withoutEmptyKey(this.getMapper().toEntity(entity));
|
|
558
|
-
if (record._id) {
|
|
559
|
-
await this.versioning.saveVersionBeforeUpdate(this.repository, record, record.block_num || null, changeType);
|
|
560
|
-
}
|
|
561
|
-
return this.getMapper().toDomain(await this.repository.save(record));
|
|
562
|
-
}
|
|
563
|
-
};
|
|
564
|
-
exports.BaseChainRepository = __decorateClass([
|
|
565
|
-
common.Injectable()
|
|
566
|
-
], exports.BaseChainRepository);
|
|
567
|
-
function withoutEmptyKey(record) {
|
|
568
|
-
if (!record._id)
|
|
569
|
-
delete record._id;
|
|
570
|
-
return record;
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
function auditUnknownStatus(entityName, receivedStatus, logger, allowedStatuses) {
|
|
574
|
-
if (receivedStatus === void 0 || receivedStatus === null || receivedStatus === "") {
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
const expected = allowedStatuses && allowedStatuses.length > 0 ? `[${allowedStatuses.join(", ")}]` : server.t("kit.syncAudit.notSpecified");
|
|
578
|
-
logger.error(
|
|
579
|
-
`UNKNOWN_ENTITY_STATUS ${entityName}: \u043F\u043E\u043B\u0443\u0447\u0435\u043D '${String(receivedStatus)}', \u043E\u0436\u0438\u0434\u0430\u044E\u0442\u0441\u044F ${expected}`,
|
|
580
|
-
{ entityName, receivedStatus, allowedStatuses }
|
|
581
|
-
);
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
const consoleAuditLogger = {
|
|
585
|
-
error(message, ...meta) {
|
|
586
|
-
console.error(message, ...meta);
|
|
587
|
-
}
|
|
588
|
-
};
|
|
589
|
-
let currentAuditLogger = consoleAuditLogger;
|
|
590
|
-
function configureAuditLogger(logger) {
|
|
591
|
-
currentAuditLogger = logger;
|
|
592
|
-
}
|
|
593
|
-
function auditLogger() {
|
|
594
|
-
return currentAuditLogger;
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
exports.AbstractBlockchainDeltaMapper = AbstractBlockchainDeltaMapper;
|
|
598
|
-
exports.BaseDomainEntity = BaseDomainEntity;
|
|
599
|
-
exports.ChainRecord = ChainRecord;
|
|
600
|
-
exports.FORK_AWARE_MARKER = FORK_AWARE_MARKER;
|
|
601
|
-
exports.UnsupportedContractVersionError = UnsupportedContractVersionError;
|
|
602
|
-
exports.auditLogger = auditLogger;
|
|
603
|
-
exports.auditUnknownStatus = auditUnknownStatus;
|
|
604
|
-
exports.configureAuditLogger = configureAuditLogger;
|
|
605
|
-
exports.configureSyncPolicy = configureSyncPolicy;
|
|
606
|
-
exports.isForkAware = isForkAware;
|
|
607
|
-
exports.syncPolicy = syncPolicy;
|
|
7
|
+
Object.keys(sync).forEach(function (k) {
|
|
8
|
+
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = sync[k];
|
|
9
|
+
});
|