@coopenomics/extension-kit 2026.9.30 → 2026.10.11
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 +1318 -348
- package/dist/index.d.cts +693 -169
- package/dist/index.d.mts +693 -169
- package/dist/index.d.ts +693 -169
- package/dist/index.mjs +1257 -329
- package/dist/shared/extension-kit.9c3dd9f1.d.cts +196 -0
- package/dist/shared/extension-kit.9c3dd9f1.d.mts +196 -0
- package/dist/shared/extension-kit.9c3dd9f1.d.ts +196 -0
- package/dist/shared/extension-kit.d5437cba.mjs +398 -0
- package/dist/shared/extension-kit.e25d0843.cjs +424 -0
- package/dist/sync/index.cjs +170 -633
- package/dist/sync/index.d.cts +70 -312
- package/dist/sync/index.d.mts +70 -312
- package/dist/sync/index.d.ts +70 -312
- package/dist/sync/index.mjs +170 -633
- package/package.json +9 -9
package/dist/sync/index.cjs
CHANGED
|
@@ -1,50 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const typeorm = require('typeorm');
|
|
4
3
|
const crypto = require('crypto');
|
|
5
4
|
const graphql = require('@nestjs/graphql');
|
|
6
5
|
const common = require('@nestjs/common');
|
|
7
|
-
const
|
|
6
|
+
const transaction = require('../shared/extension-kit.e25d0843.cjs');
|
|
8
7
|
const server = require('@coopenomics/i18n/server');
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
var __getOwnPropDesc$a = Object.getOwnPropertyDescriptor;
|
|
12
|
-
var __decorateClass$a = (decorators, target, key, kind) => {
|
|
13
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$a(target, key) : target;
|
|
14
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
15
|
-
if (decorator = decorators[i])
|
|
16
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
17
|
-
if (kind && result)
|
|
18
|
-
__defProp$a(target, key, result);
|
|
19
|
-
return result;
|
|
20
|
-
};
|
|
21
|
-
class BaseTypeormEntity {
|
|
22
|
-
/**
|
|
23
|
-
* Получить имя таблицы для сущности
|
|
24
|
-
* ДОЛЖЕН БЫТЬ ПЕРЕОПРЕДЕЛЕН в каждом наследнике!
|
|
25
|
-
*/
|
|
26
|
-
static getTableName() {
|
|
27
|
-
throw new Error("getTableName() must be implemented in subclass");
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
__decorateClass$a([
|
|
31
|
-
typeorm.PrimaryGeneratedColumn("uuid")
|
|
32
|
-
], BaseTypeormEntity.prototype, "_id", 2);
|
|
33
|
-
__decorateClass$a([
|
|
34
|
-
typeorm.Column({ type: "integer", default: 0 })
|
|
35
|
-
], BaseTypeormEntity.prototype, "block_num", 2);
|
|
36
|
-
__decorateClass$a([
|
|
37
|
-
typeorm.Column({ type: "boolean", default: false })
|
|
38
|
-
], BaseTypeormEntity.prototype, "present", 2);
|
|
39
|
-
__decorateClass$a([
|
|
40
|
-
typeorm.Column({ type: "varchar", default: "UNDEFINED" })
|
|
41
|
-
], BaseTypeormEntity.prototype, "status", 2);
|
|
42
|
-
__decorateClass$a([
|
|
43
|
-
typeorm.CreateDateColumn({ type: "timestamp" })
|
|
44
|
-
], BaseTypeormEntity.prototype, "_created_at", 2);
|
|
45
|
-
__decorateClass$a([
|
|
46
|
-
typeorm.UpdateDateColumn({ type: "timestamp" })
|
|
47
|
-
], BaseTypeormEntity.prototype, "_updated_at", 2);
|
|
8
|
+
require('kysely');
|
|
9
|
+
require('node:async_hooks');
|
|
48
10
|
|
|
49
11
|
class BaseDomainEntity {
|
|
50
12
|
// Дата последнего обновления в базе данных
|
|
@@ -79,46 +41,46 @@ class BaseDomainEntity {
|
|
|
79
41
|
}
|
|
80
42
|
}
|
|
81
43
|
|
|
82
|
-
var __defProp$
|
|
83
|
-
var __getOwnPropDesc$
|
|
84
|
-
var __decorateClass$
|
|
85
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
44
|
+
var __defProp$3 = Object.defineProperty;
|
|
45
|
+
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
|
|
46
|
+
var __decorateClass$3 = (decorators, target, key, kind) => {
|
|
47
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
|
|
86
48
|
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
87
49
|
if (decorator = decorators[i])
|
|
88
50
|
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
89
51
|
if (kind && result)
|
|
90
|
-
__defProp$
|
|
52
|
+
__defProp$3(target, key, result);
|
|
91
53
|
return result;
|
|
92
54
|
};
|
|
93
55
|
exports.BaseOutputDTO = class BaseOutputDTO {
|
|
94
56
|
};
|
|
95
|
-
__decorateClass$
|
|
57
|
+
__decorateClass$3([
|
|
96
58
|
graphql.Field(() => String, {
|
|
97
59
|
description: "\u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0438\u0439 ID \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445"
|
|
98
60
|
})
|
|
99
61
|
], exports.BaseOutputDTO.prototype, "_id", 2);
|
|
100
|
-
__decorateClass$
|
|
62
|
+
__decorateClass$3([
|
|
101
63
|
graphql.Field(() => Boolean, {
|
|
102
64
|
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"
|
|
103
65
|
})
|
|
104
66
|
], exports.BaseOutputDTO.prototype, "present", 2);
|
|
105
|
-
__decorateClass$
|
|
67
|
+
__decorateClass$3([
|
|
106
68
|
graphql.Field(() => Number, {
|
|
107
69
|
nullable: true,
|
|
108
70
|
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"
|
|
109
71
|
})
|
|
110
72
|
], exports.BaseOutputDTO.prototype, "block_num", 2);
|
|
111
|
-
__decorateClass$
|
|
73
|
+
__decorateClass$3([
|
|
112
74
|
graphql.Field(() => Date, {
|
|
113
75
|
description: "\u0414\u0430\u0442\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
|
|
114
76
|
})
|
|
115
77
|
], exports.BaseOutputDTO.prototype, "_created_at", 2);
|
|
116
|
-
__decorateClass$
|
|
78
|
+
__decorateClass$3([
|
|
117
79
|
graphql.Field(() => Date, {
|
|
118
80
|
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"
|
|
119
81
|
})
|
|
120
82
|
], exports.BaseOutputDTO.prototype, "_updated_at", 2);
|
|
121
|
-
exports.BaseOutputDTO = __decorateClass$
|
|
83
|
+
exports.BaseOutputDTO = __decorateClass$3([
|
|
122
84
|
graphql.ObjectType("BaseEntity", {
|
|
123
85
|
description: "\u0411\u0430\u0437\u043E\u0432\u044B\u0435 \u043F\u043E\u043B\u044F \u0441\u0443\u0449\u043D\u043E\u0441\u0442\u0438"
|
|
124
86
|
})
|
|
@@ -172,15 +134,15 @@ function syncPolicy() {
|
|
|
172
134
|
return policy;
|
|
173
135
|
}
|
|
174
136
|
|
|
175
|
-
var __defProp$
|
|
176
|
-
var __getOwnPropDesc$
|
|
177
|
-
var __decorateClass$
|
|
178
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
137
|
+
var __defProp$2 = Object.defineProperty;
|
|
138
|
+
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
|
|
139
|
+
var __decorateClass$2 = (decorators, target, key, kind) => {
|
|
140
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
|
|
179
141
|
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
180
142
|
if (decorator = decorators[i])
|
|
181
143
|
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
182
144
|
if (kind && result)
|
|
183
|
-
__defProp$
|
|
145
|
+
__defProp$2(target, key, result);
|
|
184
146
|
return result;
|
|
185
147
|
};
|
|
186
148
|
var _a;
|
|
@@ -360,310 +322,12 @@ exports.AbstractEntitySyncService = class AbstractEntitySyncService {
|
|
|
360
322
|
return "fork::*";
|
|
361
323
|
}
|
|
362
324
|
};
|
|
363
|
-
exports.AbstractEntitySyncService = __decorateClass$
|
|
325
|
+
exports.AbstractEntitySyncService = __decorateClass$2([
|
|
364
326
|
common.Injectable()
|
|
365
327
|
], exports.AbstractEntitySyncService);
|
|
366
328
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
var __decorateClass$7 = (decorators, target, key, kind) => {
|
|
370
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
|
|
371
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
372
|
-
if (decorator = decorators[i])
|
|
373
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
374
|
-
if (kind && result)
|
|
375
|
-
__defProp$7(target, key, result);
|
|
376
|
-
return result;
|
|
377
|
-
};
|
|
378
|
-
exports.EntityVersionTypeormEntity = class EntityVersionTypeormEntity {
|
|
379
|
-
};
|
|
380
|
-
__decorateClass$7([
|
|
381
|
-
typeorm.PrimaryGeneratedColumn("uuid")
|
|
382
|
-
], exports.EntityVersionTypeormEntity.prototype, "id", 2);
|
|
383
|
-
__decorateClass$7([
|
|
384
|
-
typeorm.Column({ type: "varchar", length: 100 })
|
|
385
|
-
], exports.EntityVersionTypeormEntity.prototype, "entity_table", 2);
|
|
386
|
-
__decorateClass$7([
|
|
387
|
-
typeorm.Column({ type: "varchar", length: 36 })
|
|
388
|
-
], exports.EntityVersionTypeormEntity.prototype, "entity_id", 2);
|
|
389
|
-
__decorateClass$7([
|
|
390
|
-
typeorm.Column({ type: "jsonb" })
|
|
391
|
-
], exports.EntityVersionTypeormEntity.prototype, "previous_data", 2);
|
|
392
|
-
__decorateClass$7([
|
|
393
|
-
typeorm.Column({ type: "integer", nullable: true })
|
|
394
|
-
], exports.EntityVersionTypeormEntity.prototype, "block_num", 2);
|
|
395
|
-
__decorateClass$7([
|
|
396
|
-
typeorm.Column({ type: "varchar", length: 50 })
|
|
397
|
-
], exports.EntityVersionTypeormEntity.prototype, "change_type", 2);
|
|
398
|
-
__decorateClass$7([
|
|
399
|
-
typeorm.Column({ type: "jsonb", nullable: true })
|
|
400
|
-
], exports.EntityVersionTypeormEntity.prototype, "metadata", 2);
|
|
401
|
-
__decorateClass$7([
|
|
402
|
-
typeorm.CreateDateColumn({ type: "timestamp" })
|
|
403
|
-
], exports.EntityVersionTypeormEntity.prototype, "created_at", 2);
|
|
404
|
-
exports.EntityVersionTypeormEntity = __decorateClass$7([
|
|
405
|
-
typeorm.Entity("entity_versions"),
|
|
406
|
-
typeorm.Index("idx_entity_versions_entity_table_id", ["entity_table", "entity_id"]),
|
|
407
|
-
typeorm.Index("idx_entity_versions_block_num", ["block_num"])
|
|
408
|
-
], exports.EntityVersionTypeormEntity);
|
|
409
|
-
|
|
410
|
-
var __defProp$6 = Object.defineProperty;
|
|
411
|
-
var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
|
|
412
|
-
var __decorateClass$6 = (decorators, target, key, kind) => {
|
|
413
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
|
|
414
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
415
|
-
if (decorator = decorators[i])
|
|
416
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
417
|
-
if (kind && result)
|
|
418
|
-
__defProp$6(target, key, result);
|
|
419
|
-
return result;
|
|
420
|
-
};
|
|
421
|
-
var __decorateParam$3 = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
422
|
-
exports.EntityVersionRepository = class EntityVersionRepository {
|
|
423
|
-
constructor(repository) {
|
|
424
|
-
this.repository = repository;
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Соединение, на котором работает репозиторий.
|
|
428
|
-
*
|
|
429
|
-
* Нужно тем, кому требуется транзакция на несколько таблиц. Инжектить
|
|
430
|
-
* `DataSource` через `@InjectDataSource()` в пакете нельзя: pnpm вшивает в
|
|
431
|
-
* путь хэш peer-зависимостей, у пакета и контроллера оказываются разные
|
|
432
|
-
* экземпляры `@nestjs/typeorm`, и токен не совпадает — Nest не находит
|
|
433
|
-
* провайдера. Токен `@InjectRepository` такой беды не знает: он считается от
|
|
434
|
-
* класса сущности, а она в пакете одна.
|
|
435
|
-
*/
|
|
436
|
-
get dataSource() {
|
|
437
|
-
return this.repository.manager.connection;
|
|
438
|
-
}
|
|
439
|
-
/**
|
|
440
|
-
* Сохранить предыдущую версию сущности
|
|
441
|
-
*/
|
|
442
|
-
async saveVersion(entityTable, entityId, previousData, blockNum, changeType, metadata) {
|
|
443
|
-
const version = this.repository.create({
|
|
444
|
-
entity_table: entityTable,
|
|
445
|
-
entity_id: entityId,
|
|
446
|
-
previous_data: previousData,
|
|
447
|
-
block_num: blockNum,
|
|
448
|
-
change_type: changeType,
|
|
449
|
-
metadata
|
|
450
|
-
});
|
|
451
|
-
return await this.repository.save(version);
|
|
452
|
-
}
|
|
453
|
-
/**
|
|
454
|
-
* Получить последнюю версию сущности до указанного блока
|
|
455
|
-
*/
|
|
456
|
-
async getLastVersionBeforeBlock(entityTable, entityId, blockNum) {
|
|
457
|
-
return await this.repository.createQueryBuilder("version").where("version.entity_table = :entityTable", { entityTable }).andWhere("version.entity_id = :entityId", { entityId }).andWhere("version.block_num <= :blockNum", { blockNum }).orderBy("version.block_num", "DESC").addOrderBy("version.created_at", "DESC").getOne();
|
|
458
|
-
}
|
|
459
|
-
/**
|
|
460
|
-
* Удалить все версии после указанного блока (локальные изменения остаются)
|
|
461
|
-
*/
|
|
462
|
-
async deleteVersionsAfterBlock(blockNum) {
|
|
463
|
-
const result = await this.repository.createQueryBuilder().delete().from(exports.EntityVersionTypeormEntity).where("block_num > :blockNum AND block_num IS NOT NULL", { blockNum }).execute();
|
|
464
|
-
return result.affected || 0;
|
|
465
|
-
}
|
|
466
|
-
/**
|
|
467
|
-
* Получить все версии для сущностей, которые нужно восстановить
|
|
468
|
-
*/
|
|
469
|
-
async getVersionsForRecovery(entityTable, maxBlockNum) {
|
|
470
|
-
return await this.repository.createQueryBuilder("version").where("version.entity_table = :entityTable", { entityTable }).andWhere("(version.block_num <= :maxBlockNum OR version.block_num IS NULL)", { maxBlockNum }).orderBy("version.entity_table", "ASC").addOrderBy("version.entity_id", "ASC").addOrderBy("version.block_num", "DESC").addOrderBy("version.created_at", "DESC").getMany();
|
|
471
|
-
}
|
|
472
|
-
/**
|
|
473
|
-
* Очистить версии для указанной сущности
|
|
474
|
-
*/
|
|
475
|
-
async clearVersionsForEntity(entityTable, entityId) {
|
|
476
|
-
const result = await this.repository.createQueryBuilder().delete().from(exports.EntityVersionTypeormEntity).where("entity_table = :entityTable", { entityTable }).andWhere("entity_id = :entityId", { entityId }).execute();
|
|
477
|
-
return result.affected || 0;
|
|
478
|
-
}
|
|
479
|
-
};
|
|
480
|
-
exports.EntityVersionRepository = __decorateClass$6([
|
|
481
|
-
common.Injectable(),
|
|
482
|
-
__decorateParam$3(0, typeorm$1.InjectRepository(exports.EntityVersionTypeormEntity))
|
|
483
|
-
], exports.EntityVersionRepository);
|
|
484
|
-
|
|
485
|
-
var __defProp$5 = Object.defineProperty;
|
|
486
|
-
var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
|
|
487
|
-
var __decorateClass$5 = (decorators, target, key, kind) => {
|
|
488
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
|
|
489
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
490
|
-
if (decorator = decorators[i])
|
|
491
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
492
|
-
if (kind && result)
|
|
493
|
-
__defProp$5(target, key, result);
|
|
494
|
-
return result;
|
|
495
|
-
};
|
|
496
|
-
exports.InvalidatedEntityTypeormEntity = class InvalidatedEntityTypeormEntity {
|
|
497
|
-
};
|
|
498
|
-
__decorateClass$5([
|
|
499
|
-
typeorm.PrimaryGeneratedColumn("uuid")
|
|
500
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "id", 2);
|
|
501
|
-
__decorateClass$5([
|
|
502
|
-
typeorm.Column({ type: "varchar", length: 100 })
|
|
503
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "entity_table", 2);
|
|
504
|
-
__decorateClass$5([
|
|
505
|
-
typeorm.Column({ type: "varchar", length: 64 })
|
|
506
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "entity_id", 2);
|
|
507
|
-
__decorateClass$5([
|
|
508
|
-
typeorm.Column({ type: "jsonb" })
|
|
509
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "data", 2);
|
|
510
|
-
__decorateClass$5([
|
|
511
|
-
typeorm.Column({ type: "integer" })
|
|
512
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "invalidated_by_block", 2);
|
|
513
|
-
__decorateClass$5([
|
|
514
|
-
typeorm.Column({ type: "varchar", length: 128, nullable: true })
|
|
515
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "fork_event_id", 2);
|
|
516
|
-
__decorateClass$5([
|
|
517
|
-
typeorm.CreateDateColumn({ type: "timestamp" })
|
|
518
|
-
], exports.InvalidatedEntityTypeormEntity.prototype, "created_at", 2);
|
|
519
|
-
exports.InvalidatedEntityTypeormEntity = __decorateClass$5([
|
|
520
|
-
typeorm.Entity("invalidated_entities"),
|
|
521
|
-
typeorm.Index("idx_invalidated_entities_block", ["invalidated_by_block"]),
|
|
522
|
-
typeorm.Index("idx_invalidated_entities_fork_event", ["fork_event_id"]),
|
|
523
|
-
typeorm.Index("idx_invalidated_entities_table_id", ["entity_table", "entity_id"])
|
|
524
|
-
], exports.InvalidatedEntityTypeormEntity);
|
|
525
|
-
|
|
526
|
-
var __defProp$4 = Object.defineProperty;
|
|
527
|
-
var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
|
|
528
|
-
var __decorateClass$4 = (decorators, target, key, kind) => {
|
|
529
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
|
|
530
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
531
|
-
if (decorator = decorators[i])
|
|
532
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
533
|
-
if (kind && result)
|
|
534
|
-
__defProp$4(target, key, result);
|
|
535
|
-
return result;
|
|
536
|
-
};
|
|
537
|
-
var __decorateParam$2 = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
538
|
-
exports.InvalidatedEntityRepository = class InvalidatedEntityRepository {
|
|
539
|
-
constructor(repository) {
|
|
540
|
-
this.repository = repository;
|
|
541
|
-
}
|
|
542
|
-
async bulkInsert(records) {
|
|
543
|
-
if (records.length === 0)
|
|
544
|
-
return 0;
|
|
545
|
-
const entities = records.map((r) => this.repository.create(r));
|
|
546
|
-
const saved = await this.repository.save(entities);
|
|
547
|
-
return saved.length;
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Retention: удалить архив старше указанного блока. Делается отдельной транзакцией,
|
|
551
|
-
* не транзакционно с архивированием — это фоновая очистка.
|
|
552
|
-
*/
|
|
553
|
-
async deleteOlderThan(minInvalidatedByBlock) {
|
|
554
|
-
const result = await this.repository.createQueryBuilder().delete().where("invalidated_by_block < :minInvalidatedByBlock", { minInvalidatedByBlock }).execute();
|
|
555
|
-
return result.affected ?? 0;
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Forensic-read для AC «список из invalidated_entities, сгруппированный по fork_event_id».
|
|
559
|
-
* UI/CLI обёртка — Epic 9 (out of scope 4.4); сам repository-метод доступен из backend-кода.
|
|
560
|
-
*/
|
|
561
|
-
async findGroupedByForkEventId(opts) {
|
|
562
|
-
const qb = this.repository.createQueryBuilder("inv").orderBy("inv.fork_event_id", "ASC").addOrderBy("inv.created_at", "DESC");
|
|
563
|
-
if (opts.blockNum != null) {
|
|
564
|
-
qb.where("inv.invalidated_by_block = :blockNum", { blockNum: opts.blockNum });
|
|
565
|
-
}
|
|
566
|
-
if (opts.limit != null) {
|
|
567
|
-
qb.limit(opts.limit);
|
|
568
|
-
}
|
|
569
|
-
const rows = await qb.getMany();
|
|
570
|
-
const grouped = /* @__PURE__ */ new Map();
|
|
571
|
-
for (const row of rows) {
|
|
572
|
-
const key = row.fork_event_id ?? null;
|
|
573
|
-
const bucket = grouped.get(key) ?? [];
|
|
574
|
-
bucket.push(row);
|
|
575
|
-
grouped.set(key, bucket);
|
|
576
|
-
}
|
|
577
|
-
return grouped;
|
|
578
|
-
}
|
|
579
|
-
};
|
|
580
|
-
exports.InvalidatedEntityRepository = __decorateClass$4([
|
|
581
|
-
common.Injectable(),
|
|
582
|
-
__decorateParam$2(0, typeorm$1.InjectRepository(exports.InvalidatedEntityTypeormEntity))
|
|
583
|
-
], exports.InvalidatedEntityRepository);
|
|
584
|
-
|
|
585
|
-
var __defProp$3 = Object.defineProperty;
|
|
586
|
-
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
|
|
587
|
-
var __decorateClass$3 = (decorators, target, key, kind) => {
|
|
588
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
|
|
589
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
590
|
-
if (decorator = decorators[i])
|
|
591
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
592
|
-
if (kind && result)
|
|
593
|
-
__defProp$3(target, key, result);
|
|
594
|
-
return result;
|
|
595
|
-
};
|
|
596
|
-
exports.InvalidatedEntityVersionTypeormEntity = class InvalidatedEntityVersionTypeormEntity {
|
|
597
|
-
};
|
|
598
|
-
__decorateClass$3([
|
|
599
|
-
typeorm.PrimaryGeneratedColumn("uuid")
|
|
600
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "id", 2);
|
|
601
|
-
__decorateClass$3([
|
|
602
|
-
typeorm.Column({ type: "varchar", length: 100 })
|
|
603
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "entity_table", 2);
|
|
604
|
-
__decorateClass$3([
|
|
605
|
-
typeorm.Column({ type: "varchar", length: 64 })
|
|
606
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "entity_id", 2);
|
|
607
|
-
__decorateClass$3([
|
|
608
|
-
typeorm.Column({ type: "jsonb" })
|
|
609
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "previous_data", 2);
|
|
610
|
-
__decorateClass$3([
|
|
611
|
-
typeorm.Column({ type: "integer", nullable: true })
|
|
612
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "original_block_num", 2);
|
|
613
|
-
__decorateClass$3([
|
|
614
|
-
typeorm.Column({ type: "integer" })
|
|
615
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "invalidated_by_block", 2);
|
|
616
|
-
__decorateClass$3([
|
|
617
|
-
typeorm.Column({ type: "varchar", length: 128, nullable: true })
|
|
618
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "fork_event_id", 2);
|
|
619
|
-
__decorateClass$3([
|
|
620
|
-
typeorm.Column({ type: "varchar", length: 50 })
|
|
621
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "change_type", 2);
|
|
622
|
-
__decorateClass$3([
|
|
623
|
-
typeorm.Column({ type: "jsonb", nullable: true })
|
|
624
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "metadata", 2);
|
|
625
|
-
__decorateClass$3([
|
|
626
|
-
typeorm.CreateDateColumn({ type: "timestamp" })
|
|
627
|
-
], exports.InvalidatedEntityVersionTypeormEntity.prototype, "created_at", 2);
|
|
628
|
-
exports.InvalidatedEntityVersionTypeormEntity = __decorateClass$3([
|
|
629
|
-
typeorm.Entity("invalidated_entity_versions"),
|
|
630
|
-
typeorm.Index("idx_invalidated_versions_block", ["invalidated_by_block"]),
|
|
631
|
-
typeorm.Index("idx_invalidated_versions_fork_event", ["fork_event_id"]),
|
|
632
|
-
typeorm.Index("idx_invalidated_versions_table_id", ["entity_table", "entity_id"])
|
|
633
|
-
], exports.InvalidatedEntityVersionTypeormEntity);
|
|
634
|
-
|
|
635
|
-
var __defProp$2 = Object.defineProperty;
|
|
636
|
-
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
|
|
637
|
-
var __decorateClass$2 = (decorators, target, key, kind) => {
|
|
638
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
|
|
639
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
640
|
-
if (decorator = decorators[i])
|
|
641
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
642
|
-
if (kind && result)
|
|
643
|
-
__defProp$2(target, key, result);
|
|
644
|
-
return result;
|
|
645
|
-
};
|
|
646
|
-
var __decorateParam$1 = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
647
|
-
exports.InvalidatedEntityVersionRepository = class InvalidatedEntityVersionRepository {
|
|
648
|
-
constructor(repository) {
|
|
649
|
-
this.repository = repository;
|
|
650
|
-
}
|
|
651
|
-
async bulkInsert(records) {
|
|
652
|
-
if (records.length === 0)
|
|
653
|
-
return 0;
|
|
654
|
-
const entities = records.map((r) => this.repository.create(r));
|
|
655
|
-
const saved = await this.repository.save(entities);
|
|
656
|
-
return saved.length;
|
|
657
|
-
}
|
|
658
|
-
async deleteOlderThan(minInvalidatedByBlock) {
|
|
659
|
-
const result = await this.repository.createQueryBuilder().delete().where("invalidated_by_block < :minInvalidatedByBlock", { minInvalidatedByBlock }).execute();
|
|
660
|
-
return result.affected ?? 0;
|
|
661
|
-
}
|
|
662
|
-
};
|
|
663
|
-
exports.InvalidatedEntityVersionRepository = __decorateClass$2([
|
|
664
|
-
common.Injectable(),
|
|
665
|
-
__decorateParam$1(0, typeorm$1.InjectRepository(exports.InvalidatedEntityVersionTypeormEntity))
|
|
666
|
-
], exports.InvalidatedEntityVersionRepository);
|
|
329
|
+
class ChainRecord {
|
|
330
|
+
}
|
|
667
331
|
|
|
668
332
|
var __defProp$1 = Object.defineProperty;
|
|
669
333
|
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
@@ -677,170 +341,123 @@ var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
|
677
341
|
return result;
|
|
678
342
|
};
|
|
679
343
|
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
680
|
-
exports.
|
|
681
|
-
//
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
}
|
|
689
|
-
/**
|
|
690
|
-
* Соединение берём у репозитория, а не инъекцией `@InjectDataSource()`:
|
|
691
|
-
* у пакета и контроллера разные экземпляры `@nestjs/typeorm`, и токен
|
|
692
|
-
* источника данных не совпал бы — Nest не нашёл бы провайдера.
|
|
693
|
-
*/
|
|
694
|
-
get dataSource() {
|
|
695
|
-
return this.entityVersionRepository.dataSource;
|
|
696
|
-
}
|
|
697
|
-
/**
|
|
698
|
-
* Сохранить версию сущности перед её изменением
|
|
699
|
-
*/
|
|
700
|
-
async saveVersionBeforeUpdate(repository, entityTable, updatedEntity, blockNum, changeType, metadata) {
|
|
701
|
-
const existingEntity = await repository.findOne({
|
|
702
|
-
where: { _id: updatedEntity._id }
|
|
703
|
-
});
|
|
704
|
-
if (!existingEntity) {
|
|
344
|
+
exports.ChainVersioningService = class ChainVersioningService {
|
|
345
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
346
|
+
constructor(db) {
|
|
347
|
+
this.db = db;
|
|
348
|
+
}
|
|
349
|
+
/** Кладёт в версии состояние записи перед её изменением; новой записи версионировать нечего. */
|
|
350
|
+
async saveVersionBeforeUpdate(store, updated, blockNum, changeType, metadata) {
|
|
351
|
+
if (!updated._id)
|
|
705
352
|
return;
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
/**
|
|
718
|
-
* Восстановить версии сущностей после форка
|
|
719
|
-
*/
|
|
720
|
-
async restoreVersionsAfterFork(repository, entityTable, forkBlockNum) {
|
|
721
|
-
const versionsToRestore = await this.entityVersionRepository.getVersionsForRecovery(entityTable, forkBlockNum);
|
|
722
|
-
const latestVersions = /* @__PURE__ */ new Map();
|
|
723
|
-
for (const version of versionsToRestore) {
|
|
724
|
-
const existingVersion = latestVersions.get(version.entity_id);
|
|
725
|
-
if (!existingVersion) {
|
|
726
|
-
latestVersions.set(version.entity_id, version);
|
|
727
|
-
continue;
|
|
728
|
-
}
|
|
729
|
-
const shouldReplace = this.shouldReplaceVersion(existingVersion, version);
|
|
730
|
-
if (shouldReplace) {
|
|
731
|
-
latestVersions.set(version.entity_id, version);
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
for (const [entityId, version] of latestVersions) {
|
|
735
|
-
const existingEntity = await repository.findOne({
|
|
736
|
-
where: { _id: entityId }
|
|
737
|
-
});
|
|
738
|
-
if (existingEntity) {
|
|
739
|
-
Object.assign(existingEntity, version.previous_data);
|
|
740
|
-
await repository.save(existingEntity);
|
|
741
|
-
} else {
|
|
742
|
-
const restoredEntity = repository.create(version.previous_data);
|
|
743
|
-
await repository.save(restoredEntity);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
353
|
+
const existing = await store.findOne({ _id: updated._id });
|
|
354
|
+
if (!existing)
|
|
355
|
+
return;
|
|
356
|
+
await this.db.insertInto("entity_versions").values({
|
|
357
|
+
entity_table: store.table,
|
|
358
|
+
entity_id: existing._id,
|
|
359
|
+
previous_data: JSON.stringify(existing),
|
|
360
|
+
block_num: blockNum,
|
|
361
|
+
change_type: changeType,
|
|
362
|
+
metadata: metadata ? JSON.stringify(metadata) : null
|
|
363
|
+
}).execute();
|
|
746
364
|
}
|
|
747
365
|
/**
|
|
748
|
-
*
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
366
|
+
* Возвращает записи таблицы к состоянию на блоке форка.
|
|
367
|
+
*
|
|
368
|
+
* Версия хранит состояние записи ДО изменения и блок самого изменения. После
|
|
369
|
+
* форка недействительны изменения с блоком больше блока форка, поэтому для
|
|
370
|
+
* каждой записи берётся самое раннее такое изменение: состояние перед ним и
|
|
371
|
+
* есть состояние на блоке форка. Запись без изменений после форка остаётся
|
|
372
|
+
* как есть.
|
|
373
|
+
*/
|
|
374
|
+
async restoreVersionsAfterFork(store, forkBlockNum) {
|
|
375
|
+
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();
|
|
376
|
+
const firstInvalidated = /* @__PURE__ */ new Map();
|
|
377
|
+
for (const version of invalidated) {
|
|
378
|
+
if (!firstInvalidated.has(version.entity_id))
|
|
379
|
+
firstInvalidated.set(version.entity_id, version);
|
|
761
380
|
}
|
|
762
|
-
|
|
763
|
-
|
|
381
|
+
for (const [entityId, version] of firstInvalidated) {
|
|
382
|
+
const state = version.previous_data;
|
|
383
|
+
if (!state || appearedAfter(state, forkBlockNum))
|
|
384
|
+
continue;
|
|
385
|
+
const existing = await store.findOne({ _id: entityId });
|
|
386
|
+
await store.save(Object.assign(existing ?? {}, state));
|
|
764
387
|
}
|
|
765
|
-
return newVersion.created_at > existingVersion.created_at;
|
|
766
388
|
}
|
|
767
389
|
/**
|
|
768
|
-
*
|
|
390
|
+
* Переносит записи таблицы с блоком больше блока форка в архив
|
|
391
|
+
* `invalidated_entities` и убирает их из таблицы — одной транзакцией.
|
|
392
|
+
* Возвращает число перенесённых записей.
|
|
769
393
|
*/
|
|
770
|
-
async
|
|
771
|
-
return
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
* Story 4.4: атомарно перенести live-ряды WHERE block_num > forkBlockNum в архив
|
|
775
|
-
* `invalidated_entities` и удалить их из исходной таблицы. Возвращает количество
|
|
776
|
-
* перенесённых рядов. Транзакция через DataSource — INSERT и DELETE либо оба
|
|
777
|
-
* успешны, либо оба откатываются.
|
|
778
|
-
*
|
|
779
|
-
* Заменяет прежнюю пару findByBlockNumGreaterThan + deleteByBlockNumGreaterThan
|
|
780
|
-
* в hot-path handleFork (sequence сейчас: archive → restoreFromVersions →
|
|
781
|
-
* archiveVersions).
|
|
782
|
-
*/
|
|
783
|
-
async archiveAndDeleteLiveAfterFork(repository, entityTable, forkBlockNum, forkEventId) {
|
|
784
|
-
return this.dataSource.transaction(async (manager) => {
|
|
785
|
-
const txRepo = manager.getRepository(repository.target);
|
|
786
|
-
const txInvalidated = manager.getRepository(exports.InvalidatedEntityTypeormEntity);
|
|
787
|
-
const rows = await txRepo.createQueryBuilder("e").where("e.block_num > :forkBlockNum", { forkBlockNum }).getMany();
|
|
394
|
+
async archiveAndDeleteLiveAfterFork(store, forkBlockNum, forkEventId) {
|
|
395
|
+
return transaction.inTransaction(this.db, async (trx) => {
|
|
396
|
+
const live = store.on(trx);
|
|
397
|
+
const rows = await live.find({ block_num: transaction.moreThan(forkBlockNum) });
|
|
788
398
|
if (rows.length === 0)
|
|
789
399
|
return 0;
|
|
790
|
-
|
|
791
|
-
(row) =>
|
|
792
|
-
entity_table:
|
|
400
|
+
await trx.insertInto("invalidated_entities").values(
|
|
401
|
+
rows.map((row) => ({
|
|
402
|
+
entity_table: store.table,
|
|
793
403
|
entity_id: row._id,
|
|
794
|
-
data:
|
|
404
|
+
data: JSON.stringify(row),
|
|
795
405
|
invalidated_by_block: forkBlockNum,
|
|
796
406
|
fork_event_id: forkEventId ?? null
|
|
797
|
-
})
|
|
798
|
-
);
|
|
799
|
-
await
|
|
800
|
-
await txRepo.createQueryBuilder().delete().where("block_num > :forkBlockNum", { forkBlockNum }).execute();
|
|
407
|
+
}))
|
|
408
|
+
).execute();
|
|
409
|
+
await live.delete({ block_num: transaction.moreThan(forkBlockNum) });
|
|
801
410
|
return rows.length;
|
|
802
411
|
});
|
|
803
412
|
}
|
|
804
413
|
/**
|
|
805
|
-
*
|
|
806
|
-
*
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
414
|
+
* Чистит архив форка: записи и версии, отменённые блоком раньше заданного.
|
|
415
|
+
* Возвращает число удалённых записей и версий.
|
|
416
|
+
*/
|
|
417
|
+
async deleteArchiveOlderThan(minInvalidatedByBlock) {
|
|
418
|
+
const entities = await this.db.deleteFrom("invalidated_entities").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
|
|
419
|
+
const versions = await this.db.deleteFrom("invalidated_entity_versions").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
|
|
420
|
+
return { entities: transaction.affectedCount(entities), versions: transaction.affectedCount(versions) };
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Переносит версии таблицы с блоком больше блока форка в архив
|
|
424
|
+
* `invalidated_entity_versions` и убирает их из `entity_versions` — одной
|
|
425
|
+
* транзакцией. Зовётся ПОСЛЕ восстановления: оно читает эти версии.
|
|
811
426
|
*/
|
|
812
427
|
async archiveAndDeleteVersionsAfterFork(entityTable, forkBlockNum, forkEventId) {
|
|
813
|
-
return this.
|
|
814
|
-
const
|
|
815
|
-
const txArchive = manager.getRepository(exports.InvalidatedEntityVersionTypeormEntity);
|
|
816
|
-
const versions = await txVersions.createQueryBuilder("v").where("v.entity_table = :entityTable", { entityTable }).andWhere("v.block_num > :forkBlockNum", { forkBlockNum }).getMany();
|
|
428
|
+
return transaction.inTransaction(this.db, async (trx) => {
|
|
429
|
+
const versions = await trx.selectFrom("entity_versions").selectAll().where("entity_table", "=", entityTable).where("block_num", ">", forkBlockNum).execute();
|
|
817
430
|
if (versions.length === 0)
|
|
818
431
|
return 0;
|
|
819
|
-
|
|
820
|
-
(
|
|
821
|
-
entity_table:
|
|
822
|
-
entity_id:
|
|
823
|
-
previous_data:
|
|
824
|
-
original_block_num:
|
|
432
|
+
await trx.insertInto("invalidated_entity_versions").values(
|
|
433
|
+
versions.map((version) => ({
|
|
434
|
+
entity_table: version.entity_table,
|
|
435
|
+
entity_id: version.entity_id,
|
|
436
|
+
previous_data: JSON.stringify(version.previous_data),
|
|
437
|
+
original_block_num: version.block_num ?? null,
|
|
825
438
|
invalidated_by_block: forkBlockNum,
|
|
826
439
|
fork_event_id: forkEventId ?? null,
|
|
827
|
-
change_type:
|
|
828
|
-
metadata:
|
|
829
|
-
})
|
|
830
|
-
);
|
|
831
|
-
await
|
|
832
|
-
|
|
833
|
-
|
|
440
|
+
change_type: version.change_type,
|
|
441
|
+
metadata: version.metadata ? JSON.stringify(version.metadata) : null
|
|
442
|
+
}))
|
|
443
|
+
).execute();
|
|
444
|
+
await trx.deleteFrom("entity_versions").where(
|
|
445
|
+
"id",
|
|
446
|
+
"in",
|
|
447
|
+
versions.map((version) => version.id)
|
|
448
|
+
).execute();
|
|
834
449
|
return versions.length;
|
|
835
450
|
});
|
|
836
451
|
}
|
|
837
452
|
};
|
|
838
|
-
exports.
|
|
453
|
+
exports.ChainVersioningService = __decorateClass$1([
|
|
839
454
|
common.Injectable(),
|
|
840
|
-
__decorateParam(0, common.Inject(
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
455
|
+
__decorateParam(0, common.Inject(transaction.KYSELY))
|
|
456
|
+
], exports.ChainVersioningService);
|
|
457
|
+
function appearedAfter(state, forkBlockNum) {
|
|
458
|
+
const block = state.block_num;
|
|
459
|
+
return block !== null && block !== void 0 && Number(block) > forkBlockNum;
|
|
460
|
+
}
|
|
844
461
|
|
|
845
462
|
var __defProp = Object.defineProperty;
|
|
846
463
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -853,176 +470,83 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
853
470
|
__defProp(target, key, result);
|
|
854
471
|
return result;
|
|
855
472
|
};
|
|
856
|
-
exports.
|
|
857
|
-
constructor(repository,
|
|
473
|
+
exports.BaseChainRepository = class BaseChainRepository {
|
|
474
|
+
constructor(repository, versioning) {
|
|
858
475
|
this.repository = repository;
|
|
859
|
-
this.
|
|
476
|
+
this.versioning = versioning;
|
|
860
477
|
}
|
|
861
|
-
/**
|
|
862
|
-
* Получить имя таблицы сущности
|
|
863
|
-
*/
|
|
864
478
|
getEntityTableName() {
|
|
865
|
-
|
|
866
|
-
if (typeof entityClass.getTableName === "function") {
|
|
867
|
-
return entityClass.getTableName();
|
|
868
|
-
}
|
|
869
|
-
return this.repository.metadata.tableName;
|
|
479
|
+
return this.repository.table;
|
|
870
480
|
}
|
|
871
|
-
/**
|
|
872
|
-
* Найти сущность по кастомному ключу синхронизации
|
|
873
|
-
*/
|
|
874
481
|
async findBySyncKey(syncKey, syncValue) {
|
|
875
|
-
const
|
|
876
|
-
|
|
877
|
-
where: whereCondition
|
|
878
|
-
});
|
|
879
|
-
return entity ? this.getMapper().toDomain(entity) : null;
|
|
482
|
+
const record = await this.repository.findOne({ [syncKey]: String(syncValue).toLowerCase() });
|
|
483
|
+
return record ? this.getMapper().toDomain(record) : null;
|
|
880
484
|
}
|
|
881
|
-
/**
|
|
882
|
-
* Найти сущности с номером блока больше указанного
|
|
883
|
-
*/
|
|
884
485
|
async findByBlockNumGreaterThan(blockNum) {
|
|
885
|
-
const
|
|
886
|
-
return
|
|
486
|
+
const records = await this.repository.find({ block_num: transaction.moreThan(blockNum) });
|
|
487
|
+
return records.map((record) => this.getMapper().toDomain(record));
|
|
887
488
|
}
|
|
888
|
-
/**
|
|
889
|
-
|
|
890
|
-
* Используется для синхронизации данных из блокчейна
|
|
891
|
-
*/
|
|
489
|
+
/** Создаёт запись из данных цепи либо обновляет существующую. */
|
|
490
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
892
491
|
async createIfNotExists(blockchainData, blockNum, present = true) {
|
|
893
492
|
const syncKey = this.getSyncKey();
|
|
894
493
|
const syncValue = this.extractSyncValueFromBlockchainData(blockchainData, syncKey);
|
|
895
494
|
const existing = await this.findBySyncKey(syncKey, syncValue);
|
|
896
|
-
if (existing) {
|
|
897
|
-
const existingBlockNum = existing.getBlockNum();
|
|
898
|
-
if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum)) {
|
|
899
|
-
return existing;
|
|
900
|
-
}
|
|
901
|
-
existing.updateFromBlockchain(blockchainData, blockNum, present);
|
|
902
|
-
return await this.save(existing);
|
|
903
|
-
} else {
|
|
495
|
+
if (!existing) {
|
|
904
496
|
const now = /* @__PURE__ */ new Date();
|
|
905
|
-
const
|
|
906
|
-
_id: "",
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
_updated_at: now,
|
|
911
|
-
[syncKey]: String(syncValue).toLowerCase()
|
|
912
|
-
// ключ синхронизации
|
|
913
|
-
};
|
|
914
|
-
const newEntity = this.createDomainEntity(minimalDatabaseData, blockchainData);
|
|
915
|
-
return await this.save(newEntity);
|
|
497
|
+
const created = this.createDomainEntity(
|
|
498
|
+
{ _id: "", block_num: blockNum, present, _created_at: now, _updated_at: now, [syncKey]: String(syncValue).toLowerCase() },
|
|
499
|
+
blockchainData
|
|
500
|
+
);
|
|
501
|
+
return this.save(created);
|
|
916
502
|
}
|
|
503
|
+
const existingBlockNum = existing.getBlockNum();
|
|
504
|
+
if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum))
|
|
505
|
+
return existing;
|
|
506
|
+
existing.updateFromBlockchain(blockchainData, blockNum, present);
|
|
507
|
+
return this.save(existing);
|
|
917
508
|
}
|
|
918
|
-
/**
|
|
919
|
-
* Удалить сущности с номером блока больше указанного (для обработки форков)
|
|
920
|
-
*/
|
|
921
509
|
async deleteByBlockNumGreaterThan(blockNum) {
|
|
922
|
-
await this.repository.
|
|
510
|
+
await this.repository.delete({ block_num: transaction.moreThan(blockNum) });
|
|
923
511
|
}
|
|
924
|
-
/**
|
|
925
|
-
* Восстановить сущности из версий после форка
|
|
926
|
-
*/
|
|
927
512
|
async restoreFromVersions(forkBlockNum) {
|
|
928
|
-
await this.
|
|
513
|
+
await this.versioning.restoreVersionsAfterFork(this.repository, forkBlockNum);
|
|
929
514
|
}
|
|
930
|
-
/**
|
|
931
|
-
* Story 4.4: архивировать live-ряды WHERE block_num > forkBlockNum в invalidated_entities
|
|
932
|
-
* и удалить из исходной таблицы (атомарно). Возвращает count. Заменяет в hot-path
|
|
933
|
-
* handleFork прежнюю пару findByBlockNumGreaterThan + deleteByBlockNumGreaterThan.
|
|
934
|
-
*/
|
|
515
|
+
/** Переносит записи после блока форка в архив и убирает их из таблицы. */
|
|
935
516
|
async archiveInvalidatedSince(forkBlockNum, forkEventId) {
|
|
936
|
-
return this.
|
|
937
|
-
this.repository,
|
|
938
|
-
this.getEntityTableName(),
|
|
939
|
-
forkBlockNum,
|
|
940
|
-
forkEventId
|
|
941
|
-
);
|
|
517
|
+
return this.versioning.archiveAndDeleteLiveAfterFork(this.repository, forkBlockNum, forkEventId);
|
|
942
518
|
}
|
|
943
|
-
/**
|
|
944
|
-
* Story 4.4: архивировать entity_versions WHERE entity_table=... AND block_num > forkBlockNum
|
|
945
|
-
* в invalidated_entity_versions и удалить из entity_versions (атомарно). Возвращает count.
|
|
946
|
-
* Должен вызываться ПОСЛЕ restoreFromVersions — иначе restore не сможет прочитать ещё-живые версии.
|
|
947
|
-
*/
|
|
519
|
+
/** Переносит версии после блока форка в архив; зовётся после восстановления. */
|
|
948
520
|
async archiveInvalidatedVersionsSince(forkBlockNum, forkEventId) {
|
|
949
|
-
return this.
|
|
950
|
-
this.getEntityTableName(),
|
|
951
|
-
forkBlockNum,
|
|
952
|
-
forkEventId
|
|
953
|
-
);
|
|
521
|
+
return this.versioning.archiveAndDeleteVersionsAfterFork(this.getEntityTableName(), forkBlockNum, forkEventId);
|
|
954
522
|
}
|
|
955
|
-
/**
|
|
956
|
-
* Обновить сущность
|
|
957
|
-
*/
|
|
958
523
|
async update(entity) {
|
|
959
|
-
|
|
960
|
-
await this.entityVersioningService.saveVersionBeforeUpdate(
|
|
961
|
-
this.repository,
|
|
962
|
-
this.getEntityTableName(),
|
|
963
|
-
typeormEntity,
|
|
964
|
-
typeormEntity.block_num || null,
|
|
965
|
-
"update"
|
|
966
|
-
);
|
|
967
|
-
const savedEntity = await this.repository.save(typeormEntity);
|
|
968
|
-
return this.getMapper().toDomain(savedEntity);
|
|
524
|
+
return this.persist(entity, "update");
|
|
969
525
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
*/
|
|
973
|
-
async create(entity) {
|
|
974
|
-
const typeormEntity = this.getMapper().toEntity(entity);
|
|
975
|
-
return this.repository.create(typeormEntity);
|
|
526
|
+
async save(entity) {
|
|
527
|
+
return this.persist(entity, "save");
|
|
976
528
|
}
|
|
977
|
-
/**
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const savedEntity = await this.repository.save(entity);
|
|
982
|
-
return this.getMapper().toDomain(savedEntity);
|
|
529
|
+
/** Заготовка записи без сохранения в базу. */
|
|
530
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
531
|
+
async create(entity) {
|
|
532
|
+
return this.repository.create(this.getMapper().toEntity(entity));
|
|
983
533
|
}
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
async save(entity) {
|
|
988
|
-
const typeormEntity = this.getMapper().toEntity(entity);
|
|
989
|
-
if (typeormEntity._id) {
|
|
990
|
-
await this.entityVersioningService.saveVersionBeforeUpdate(
|
|
991
|
-
this.repository,
|
|
992
|
-
this.getEntityTableName(),
|
|
993
|
-
typeormEntity,
|
|
994
|
-
typeormEntity.block_num || null,
|
|
995
|
-
"save"
|
|
996
|
-
);
|
|
997
|
-
}
|
|
998
|
-
const savedEntity = await this.repository.save(typeormEntity);
|
|
999
|
-
return this.getMapper().toDomain(savedEntity);
|
|
534
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
535
|
+
async saveCreated(record) {
|
|
536
|
+
return this.getMapper().toDomain(await this.repository.save(withoutEmptyKey(record)));
|
|
1000
537
|
}
|
|
1001
|
-
/**
|
|
1002
|
-
* Найти все сущности
|
|
1003
|
-
*/
|
|
1004
538
|
async findAll() {
|
|
1005
|
-
const
|
|
1006
|
-
return
|
|
539
|
+
const records = await this.repository.find();
|
|
540
|
+
return records.map((record) => this.getMapper().toDomain(record));
|
|
1007
541
|
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Найти сущность по внутреннему ID базы данных
|
|
1010
|
-
*/
|
|
1011
542
|
async findById(_id) {
|
|
1012
|
-
const
|
|
1013
|
-
|
|
1014
|
-
});
|
|
1015
|
-
return entity ? this.getMapper().toDomain(entity) : null;
|
|
543
|
+
const record = await this.repository.findOne({ _id });
|
|
544
|
+
return record ? this.getMapper().toDomain(record) : null;
|
|
1016
545
|
}
|
|
1017
|
-
/**
|
|
1018
|
-
* Удалить сущность по внутреннему ID базы данных
|
|
1019
|
-
*/
|
|
1020
546
|
async delete(_id) {
|
|
1021
|
-
await this.repository.delete(_id);
|
|
547
|
+
await this.repository.delete({ _id });
|
|
1022
548
|
}
|
|
1023
|
-
|
|
1024
|
-
* Извлечь значение ключа синхронизации из блокчейн данных
|
|
1025
|
-
*/
|
|
549
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1026
550
|
extractSyncValueFromBlockchainData(blockchainData, syncKey) {
|
|
1027
551
|
const value = blockchainData[syncKey];
|
|
1028
552
|
if (value === null || value === void 0) {
|
|
@@ -1030,10 +554,23 @@ exports.BaseBlockchainRepository = class BaseBlockchainRepository {
|
|
|
1030
554
|
}
|
|
1031
555
|
return value.toString().toLowerCase();
|
|
1032
556
|
}
|
|
557
|
+
/** Сохраняет запись; у существующей перед изменением кладёт прежнее состояние в версии. */
|
|
558
|
+
async persist(entity, changeType) {
|
|
559
|
+
const record = withoutEmptyKey(this.getMapper().toEntity(entity));
|
|
560
|
+
if (record._id) {
|
|
561
|
+
await this.versioning.saveVersionBeforeUpdate(this.repository, record, record.block_num || null, changeType);
|
|
562
|
+
}
|
|
563
|
+
return this.getMapper().toDomain(await this.repository.save(record));
|
|
564
|
+
}
|
|
1033
565
|
};
|
|
1034
|
-
exports.
|
|
566
|
+
exports.BaseChainRepository = __decorateClass([
|
|
1035
567
|
common.Injectable()
|
|
1036
|
-
], exports.
|
|
568
|
+
], exports.BaseChainRepository);
|
|
569
|
+
function withoutEmptyKey(record) {
|
|
570
|
+
if (!record._id)
|
|
571
|
+
delete record._id;
|
|
572
|
+
return record;
|
|
573
|
+
}
|
|
1037
574
|
|
|
1038
575
|
function auditUnknownStatus(entityName, receivedStatus, logger, allowedStatuses) {
|
|
1039
576
|
if (receivedStatus === void 0 || receivedStatus === null || receivedStatus === "") {
|
|
@@ -1061,7 +598,7 @@ function auditLogger() {
|
|
|
1061
598
|
|
|
1062
599
|
exports.AbstractBlockchainDeltaMapper = AbstractBlockchainDeltaMapper;
|
|
1063
600
|
exports.BaseDomainEntity = BaseDomainEntity;
|
|
1064
|
-
exports.
|
|
601
|
+
exports.ChainRecord = ChainRecord;
|
|
1065
602
|
exports.FORK_AWARE_MARKER = FORK_AWARE_MARKER;
|
|
1066
603
|
exports.UnsupportedContractVersionError = UnsupportedContractVersionError;
|
|
1067
604
|
exports.auditLogger = auditLogger;
|