@things-factory/id-rule 10.1.291 → 10.1.297

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.
@@ -9,5 +9,17 @@ export declare function generateId({ domain, type, seed }: {
9
9
  type: any;
10
10
  seed: any;
11
11
  }): Promise<any>;
12
+ /**
13
+ * **The next number of a pattern** - in its own transaction, under the sequence row's lock (2026-11-19).
14
+ *
15
+ * It used to read the row, add one and save, outside any transaction: two callers at once got the same number. Now the row
16
+ * is inserted insert-or-nothing (two first callers do not fail each other at `ix_sequence_0`), locked, and raised. The
17
+ * expiry keeps its meaning - a sequence past its `expiresAt` starts again at 1 (rules use it to reset a pattern daily);
18
+ * every take moves the expiry to `expirationDate` or six months on, as before.
19
+ *
20
+ * Its own transaction because a rule is evaluated without the caller's: the number commits even if the caller's write
21
+ * later fails (a gap, never a duplicate). A product that needs the number to roll back with its row uses shell's
22
+ * `takeSequence` inside its transaction instead.
23
+ */
12
24
  export declare function getNext({ domain, pattern, expirationDate }: getNextArgs): Promise<number>;
13
25
  export {};
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateId = generateId;
4
4
  exports.getNext = getNext;
5
- const typeorm_1 = require("typeorm");
6
5
  const shell_1 = require("@things-factory/shell");
7
6
  const id_rule_1 = require("../service/id-rule/id-rule");
8
7
  const sequence_1 = require("../service/sequence/sequence");
@@ -30,32 +29,31 @@ async function generateId({ domain, type, seed }) {
30
29
  }, getNext);
31
30
  return nextId;
32
31
  }
32
+ /**
33
+ * **The next number of a pattern** - in its own transaction, under the sequence row's lock (2026-11-19).
34
+ *
35
+ * It used to read the row, add one and save, outside any transaction: two callers at once got the same number. Now the row
36
+ * is inserted insert-or-nothing (two first callers do not fail each other at `ix_sequence_0`), locked, and raised. The
37
+ * expiry keeps its meaning - a sequence past its `expiresAt` starts again at 1 (rules use it to reset a pattern daily);
38
+ * every take moves the expiry to `expirationDate` or six months on, as before.
39
+ *
40
+ * Its own transaction because a rule is evaluated without the caller's: the number commits even if the caller's write
41
+ * later fails (a gap, never a duplicate). A product that needs the number to roll back with its row uses shell's
42
+ * `takeSequence` inside its transaction instead.
43
+ */
33
44
  async function getNext({ domain, pattern, expirationDate }) {
34
- const seqRepo = (0, shell_1.getRepository)(sequence_1.Sequence);
35
- const now = new Date();
36
- let last = await seqRepo.findOneBy({
37
- domain: { id: domain.id },
38
- pattern,
39
- expiresAt: (0, typeorm_1.MoreThan)(now)
45
+ return (0, shell_1.getRepository)(sequence_1.Sequence).manager.transaction(async (tx) => {
46
+ const now = new Date();
47
+ const expiresAt = expirationDate ?? new Date(new Date(now).setMonth(now.getMonth() + 6));
48
+ const where = { domain: { id: domain.id }, pattern };
49
+ await tx.createQueryBuilder().insert().into(sequence_1.Sequence).values({ domain: { id: domain.id }, pattern, seq: 0, expiresAt }).orIgnore().execute();
50
+ const row = await tx.findOne(sequence_1.Sequence, { where: where, ...(0, shell_1.writeLockOn)(tx, sequence_1.Sequence) });
51
+ if (!row)
52
+ throw new Error(`id-rule: the sequence ${pattern} disappeared while numbering`);
53
+ const expired = row.expiresAt && new Date(row.expiresAt).getTime() <= now.getTime();
54
+ const seq = expired ? 1 : Number(row.seq) + 1;
55
+ await tx.update(sequence_1.Sequence, { id: row.id }, { seq, expiresAt });
56
+ return seq;
40
57
  });
41
- var expiresAt = expirationDate;
42
- if (!expirationDate)
43
- expiresAt = new Date(now.setMonth(now.getMonth() + 6));
44
- if (last) {
45
- last.seq++;
46
- last.expiresAt = expiresAt;
47
- await seqRepo.save(last);
48
- }
49
- else {
50
- if (!expirationDate)
51
- now.setMonth(now.getMonth() + 6);
52
- last = await seqRepo.save({
53
- domain,
54
- pattern,
55
- seq: 1,
56
- expiresAt
57
- });
58
- }
59
- return last.seq;
60
58
  }
61
59
  //# sourceMappingURL=id-generator.js.map
@@ -0,0 +1,5 @@
1
+ import { MigrationInterface, QueryRunner } from 'typeorm';
2
+ export declare class WidenSequenceSeq1795132800001 implements MigrationInterface {
3
+ up(queryRunner: QueryRunner): Promise<void>;
4
+ down(): Promise<void>;
5
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WidenSequenceSeq1795132800001 = void 0;
4
+ const typeorm_1 = require("typeorm");
5
+ /**
6
+ * `sequences.seq` smallint → int (2026-11-19). A smallint stops at 32,767 - a busy pattern (labels, a day's orders) passes it
7
+ * and the save fails. Widening keeps every value. idempotent: does nothing when the column is already an int (synchronize).
8
+ */
9
+ const TABLE_NAME = 'sequences';
10
+ class WidenSequenceSeq1795132800001 {
11
+ async up(queryRunner) {
12
+ const table = await queryRunner.getTable(TABLE_NAME);
13
+ const column = table?.findColumnByName('seq');
14
+ if (!table || !column || column.type !== 'smallint')
15
+ return;
16
+ await queryRunner.changeColumn(table, column, new typeorm_1.TableColumn({ ...column, type: 'int' }));
17
+ }
18
+ async down() {
19
+ /* Narrowing back could lose numbers past 32,767 - not done. */
20
+ }
21
+ }
22
+ exports.WidenSequenceSeq1795132800001 = WidenSequenceSeq1795132800001;
23
+ //# sourceMappingURL=1795132800001-WidenSequenceSeq.js.map
@@ -2,4 +2,4 @@ import { DocNumber } from './doc-number';
2
2
  import { DocNumberQuery } from './doc-number-query';
3
3
  import { DocNumberMutation } from './doc-number-mutation';
4
4
  export declare const entities: (typeof DocNumber)[];
5
- export declare const resolvers: (typeof DocNumberQuery | typeof DocNumberMutation)[];
5
+ export declare const resolvers: (typeof DocNumberMutation | typeof DocNumberQuery)[];
@@ -2,4 +2,4 @@ import { IdRule } from './id-rule';
2
2
  import { IdRuleMutation } from './id-rule-mutation';
3
3
  import { IdRuleQuery } from './id-rule-query';
4
4
  export declare const entities: (typeof IdRule)[];
5
- export declare const resolvers: (typeof IdRuleMutation | typeof IdRuleQuery)[];
5
+ export declare const resolvers: (typeof IdRuleQuery | typeof IdRuleMutation)[];
@@ -2,7 +2,7 @@ export * from './id-rule/id-rule';
2
2
  export * from './id-rule/id-rule-types';
3
3
  export * from './sequence/sequence';
4
4
  export * from './doc-number/doc-number';
5
- export declare const entities: (typeof import("./id-rule/id-rule").IdRule | typeof import("./sequence/sequence").Sequence | typeof import("./doc-number/doc-number").DocNumber)[];
5
+ export declare const entities: (typeof import("./doc-number/doc-number").DocNumber | typeof import("./sequence/sequence").Sequence | typeof import("./id-rule/id-rule").IdRule)[];
6
6
  export declare const schema: {
7
- resolverClasses: (typeof import("./id-rule/id-rule-mutation").IdRuleMutation | typeof import("./id-rule/id-rule-query").IdRuleQuery | typeof import("./sequence/sequence-mutation").SequenceMutation | typeof import("./doc-number/doc-number-query").DocNumberQuery | typeof import("./doc-number/doc-number-mutation").DocNumberMutation)[];
7
+ resolverClasses: (typeof import("./doc-number/doc-number-mutation").DocNumberMutation | typeof import("./doc-number/doc-number-query").DocNumberQuery | typeof import("./sequence/sequence-mutation").SequenceMutation | typeof import("./id-rule/id-rule-query").IdRuleQuery | typeof import("./id-rule/id-rule-mutation").IdRuleMutation)[];
8
8
  };
@@ -9,36 +9,22 @@ const sequence_1 = require("./sequence");
9
9
  let SequenceMutation = class SequenceMutation {
10
10
  async upsertSequence(type, counter, bizplaceId, context) {
11
11
  const { domain } = context.state;
12
- const seqRepo = (0, shell_1.getRepository)(sequence_1.Sequence);
13
12
  const now = new Date();
14
- const expiresAt = new Date(now.setMonth(now.getMonth() + 12));
15
- const patternObj = {
16
- type,
17
- date: new Date().toISOString().split('T')[0],
18
- bizplaceId
19
- };
20
- const pattern = JSON.stringify(patternObj);
21
- const foundSeq = await seqRepo.findOne({
22
- where: { pattern, type: constants_1.SEQUENCE_TYPE.PRODUCT_LABEL_COUNTER, domain: { id: domain.id } }
13
+ const expiresAt = new Date(new Date(now).setMonth(now.getMonth() + 12));
14
+ const pattern = JSON.stringify({ type, date: now.toISOString().split('T')[0], bizplaceId });
15
+ /*
16
+ * In one transaction under the row's lock (2026-11-19) - it used to read, add and save outside one, so two label prints
17
+ * at once got the same counter. Insert-or-nothing first, so two first prints do not fail each other at `ix_sequence_0`.
18
+ */
19
+ return (0, shell_1.getRepository)(sequence_1.Sequence).manager.transaction(async (tx) => {
20
+ const where = { domain: { id: domain.id }, pattern };
21
+ await tx.createQueryBuilder().insert().into(sequence_1.Sequence).values({ domain: { id: domain.id }, pattern, seq: 0, expiresAt, type: constants_1.SEQUENCE_TYPE.PRODUCT_LABEL_COUNTER }).orIgnore().execute();
22
+ const row = await tx.findOne(sequence_1.Sequence, { where: where, ...(0, shell_1.writeLockOn)(tx, sequence_1.Sequence) });
23
+ if (!row)
24
+ throw new Error(`id-rule: the label counter ${pattern} disappeared while counting`);
25
+ await tx.update(sequence_1.Sequence, { id: row.id }, { seq: Number(row.seq) + (counter || 1), expiresAt });
26
+ return tx.findOne(sequence_1.Sequence, { where: { id: row.id } });
23
27
  });
24
- if (foundSeq) {
25
- await seqRepo.update({ id: foundSeq.id }, {
26
- pattern,
27
- seq: counter ? foundSeq.seq + counter : foundSeq.seq + 1,
28
- expiresAt,
29
- updatedAt: now
30
- });
31
- return await seqRepo.findOneBy({ id: foundSeq.id });
32
- }
33
- else {
34
- return await seqRepo.save({
35
- domain,
36
- pattern,
37
- seq: counter || 1,
38
- expiresAt,
39
- type: constants_1.SEQUENCE_TYPE.PRODUCT_LABEL_COUNTER
40
- });
41
- }
42
28
  }
43
29
  };
44
30
  exports.SequenceMutation = SequenceMutation;
@@ -4,6 +4,7 @@ export declare class Sequence {
4
4
  domain: Domain;
5
5
  domainId?: string;
6
6
  pattern: string;
7
+ /** An int, not a smallint: a busy daily pattern passes 32,767 (2026-11-19 - `1795132800001-WidenSequenceSeq`). */
7
8
  seq: number;
8
9
  type: string;
9
10
  expiresAt: Date;
@@ -29,7 +29,7 @@ tslib_1.__decorate([
29
29
  ], Sequence.prototype, "pattern", void 0);
30
30
  tslib_1.__decorate([
31
31
  (0, typeorm_1.Column)({
32
- type: 'smallint'
32
+ type: 'int'
33
33
  }),
34
34
  (0, type_graphql_1.Field)(),
35
35
  tslib_1.__metadata("design:type", Number)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/id-rule",
3
- "version": "10.1.291",
3
+ "version": "10.1.297",
4
4
  "main": "dist-server/index.js",
5
5
  "browser": "dist-client/index.js",
6
6
  "files": [
@@ -43,9 +43,9 @@
43
43
  "dependencies": {
44
44
  "@operato/data-grist": "^10.29.69",
45
45
  "@operato/input": "^10.0.0",
46
- "@things-factory/i18n-base": "^10.1.291",
47
- "@things-factory/setting-base": "^10.1.291",
48
- "@things-factory/shell": "^10.1.291"
46
+ "@things-factory/i18n-base": "^10.1.297",
47
+ "@things-factory/setting-base": "^10.1.297",
48
+ "@things-factory/shell": "^10.1.297"
49
49
  },
50
- "gitHead": "994bc91b2d71513039c204560bb0571baa92ca0b"
50
+ "gitHead": "656ec78e5adf500b3b636eb9790cfe22f2a49ba9"
51
51
  }