File size: 12,384 Bytes
0b75d30
aa89cb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b75d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa89cb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b75d30
 
aa89cb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b75d30
aa89cb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b75d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { CheckException, CheckResult, EntityChecker, EntityRoot, FixedBusinessClock, MutationIntent, ObjectLocation, RuntimeModule, UserContext } from '../src';
import { AbstractSQLTeaQLClient, TeaQLSqlDriver } from '../src/sql/core';

class Driver implements TeaQLSqlDriver {
  readonly databaseKind = 'sqlite' as const;
  transactions = 0;
  statements: string[] = [];
  query = async (sql: string) => { this.statements.push(sql); return { rows: sql.startsWith('SELECT') ? [{ id: '1', version: 1, userEmail: 'a@b.test' }] : [], rowCount: 1 }; };
  stream = async function* () {};
  identifier = (value: string) => `"${value}"`;
  placeholder = () => '?';
  encode = (value: any) => value;
  contains = () => '';
  aggregateFunction = (name: string) => name;
  ensureSchema = async () => {};
  transaction = async <T>(work: (session: any) => Promise<T>) => { this.transactions++; return work(this); };
  nextId = async () => '1';
  ensureIdFloor = async () => {};
  close = async () => {};
}

class Client extends AbstractSQLTeaQLClient {
  constructor(driver: Driver) { super(driver, {}); }
}

test.each([undefined, '', '  '])('checker binds an absent declaring type (%p) before localization without SQL', async entityType => {
  const driver = new Driver();
  const context = new UserContext();
  const violation: CheckResult = {ruleId: 'required', entityType,
    location: ObjectLocation.property('contact_phone'), sourceInstancePath: '/legacy~1phone~0',
    inputValue: null, systemValue: 'required'};
  const translated: CheckResult[] = [];
  const translate = context.i18nCatalog.translate.bind(context.i18nCatalog);
  // Do not mutate the shared built-in catalog while observing the boundary.
  context.installI18nCatalog({translate: (result: CheckResult, locale: any) => {
    expect(result.entityType).toBe('Task'); translated.push({...result});
    return translate(result, locale);
  }} as any);
  const client = new Client(driver).setUserContext(context).install(new RuntimeModule({
    Task: {table: 'task', columns: {}},
  }, {Task: {checkAndFix: (_ctx, _mutation, results) => { results.push({...violation}); }}}));
  for (let attempt = 0; attempt < 2; attempt++) {
    let failure: CheckException | undefined;
    try { await client.executeMutation({entity: 'Task', action: 'Create', payload: {}, comment: 'Require Checker identity'}); }
    catch (error) { if (!(error instanceof CheckException)) throw error; failure = error; }
    expect(failure).toBeInstanceOf(CheckException);
    expect(failure!.violations).toHaveLength(1);
    expect(failure!.violations[0]).toMatchObject({...violation, entityType: 'Task'});
    expect(failure!.violations[0].message).toContain('contactPhone');
    expect(context.getResource('fixTime')).toBeUndefined();
  }
  expect(translated).toHaveLength(2);
  expect(violation.entityType).toBe(entityType);
  expect(driver.transactions).toBe(0); expect(driver.statements).toEqual([]);
});

test('checker preserves a specialized nested type, canonical indices and submitted pointer', async () => {
  const driver = new Driver();
  const context = new UserContext();
  const location = ObjectLocation.property('order_item_list').index(1).property('product_name');
  const result: CheckResult = {ruleId: 'required', entityType: 'SpecialOrderItem', location,
    sourceInstancePath: '/old~1items/1/old~0name', inputValue: null, systemValue: 'required'};
  const client = new Client(driver).setUserContext(context).install(new RuntimeModule({
    Task: {table: 'task', columns: {}},
  }, {Task: {checkAndFix: (_ctx, _mutation, results) => { results.push({...result}); }}}));
  let failure: CheckException | undefined;
  try { await client.executeMutation({entity: 'Task', action: 'Create', payload: {}, comment: 'Preserve the child Checker type'}); }
  catch (error) { if (!(error instanceof CheckException)) throw error; failure = error; }
  expect(failure).toBeInstanceOf(CheckException);
  expect(failure!.violations[0]).toMatchObject(result);
  expect(failure!.violations[0].location).toBe(location);
  expect(failure!.message).toContain('The product name is required.\nLocation: the 2nd order item list');
  expect(failure!.violations[0].location.instancePath()).toBe('/orderItemList/1/productName');
  expect(driver.transactions).toBe(0); expect(driver.statements).toEqual([]);
});

test('independent declaring types do not leak through a shared Context', () => {
  const context = new UserContext();
  const result = (): CheckResult => ({ruleId: 'required', location: ObjectLocation.property('name')});
  const first = context.translateCheckResults([result()], 'First')[0];
  const second = context.translateCheckResults([result()], 'Second')[0];
  const unknown = context.translateCheckResults([result()])[0];
  expect(first.entityType).toBe('First'); expect(second.entityType).toBe('Second');
  expect(unknown.entityType).toBeUndefined();
});

test('checker failure is structured, save scoped, and runs before SQL transaction', async () => {
  const driver = new Driver();
  const context = new UserContext();
  let calls = 0;
  const checker: EntityChecker = {
    checkAndFix(ctx, mutation, results: CheckResult[]) {
      calls++;
      expect(ctx.getResource('fixTime')).toBeInstanceOf(Date);
      if (!mutation.payload.name) results.push({ ruleId: 'required', location: ObjectLocation.property('name') });
    },
  };
  const client = new Client(driver).setUserContext(context).install(new RuntimeModule({
    Task: { table: 'task', columns: {} },
  }, { Task: checker }));
  const mutation = { entity: 'Task', action: 'Create', payload: {}, comment: 'test' };

  for (let attempt = 0; attempt < 2; attempt++) {
    await expect(client.executeMutation(mutation)).rejects.toBeInstanceOf(CheckException);
  }
  expect(calls).toBe(2);
  expect(driver.transactions).toBe(0);
  expect(context.getResource('fixTime')).toBeUndefined();
});

test('canonical multiword mutation key reaches checker and native SQL schema', async () => {
  const driver = new Driver();
  const checker: EntityChecker = {
    checkAndFix(_context, mutation, results) {
      if (!mutation.payload.user_email) {
        results.push({ ruleId: 'required', location: ObjectLocation.property('user_email') });
      }
    },
  };
  const client = new Client(driver).setUserContext(new UserContext()).install(new RuntimeModule({
    User: { table: 'user_data', columns: {
      id: { columnName: 'id', logicalType: 'integer', decode: 'string' },
      version: { columnName: 'version', logicalType: 'integer', decode: 'number' },
      userEmail: { columnName: 'email_address', modelName: 'user_email', logicalType: 'text', decode: 'native' },
    } },
  }, { User: checker }));

  const result = await client.executeMutation({
    entity: 'User', action: 'Create', payload: { user_email: 'a@b.test' }, comment: 'test canonical key',
  });
  expect(result.persistedRecord?.userEmail).toBe('a@b.test');
  expect(driver.statements.some(sql => sql.includes('"email_address"'))).toBe(true);
});

test('update checker can add fixes to an immutable mutation ledger snapshot', async () => {
  const driver = new Driver();
  const context = new UserContext();
  const ledgerRoot = new EntityRoot();
  const ledgerKey = { entity: 'Task', id: '1' } as const;
  const checker: EntityChecker = {
    checkAndFix(ctx, mutation) {
      expect(ctx.getResource('fixTime')).toBeInstanceOf(Date);
      mutation.payload.update_time = ctx.getResource('fixTime');
    },
  };
  const client = new Client(driver).setUserContext(context).install(new RuntimeModule({
    Task: { table: 'task_data', columns: {
      id: { columnName: 'id', logicalType: 'integer', decode: 'string' },
      version: { columnName: 'version', logicalType: 'integer', decode: 'number' },
      name: { columnName: 'name', logicalType: 'text', decode: 'native' },
      updateTime: { columnName: 'update_time', modelName: 'update_time', logicalType: 'datetime', decode: 'date' },
    } },
  }, { Task: checker }));

  const immutableLedgerPayload = Object.freeze({ name: 'Updated task' });
  await expect(client.executeMutation({
    entity: 'Task', action: 'Update', payload: immutableLedgerPayload,
    id: '1', version: 1, comment: 'update task', ledgerKey, ledgerRoot,
  })).resolves.toBeDefined();

  expect(Object.isFrozen(immutableLedgerPayload)).toBe(true);
  expect((immutableLedgerPayload as Record<string, unknown>).update_time).toBeUndefined();
  expect(ledgerRoot.change(ledgerKey).update_time).toBeInstanceOf(Date);
  expect(driver.statements.some(sql => sql.includes('"update_time" = ?'))).toBe(true);
});

test('one graph captures one fix clock and clears it after commit', async () => {
  const driver = new Driver();
  const expected = new Date('2032-02-29T10:15:30.000Z');
  const context = new UserContext().withBusinessClock(new FixedBusinessClock(expected));
  const observed: Date[] = [];
  const checker: EntityChecker = {
    checkAndFix(ctx, mutation) {
      const now = ctx.requireResource<Date>('fixTime');
      observed.push(now);
      mutation.payload.create_time = now;
    },
  };
  const client = new Client(driver).setUserContext(context).install(new RuntimeModule({
    Task: { table: 'task_data', columns: {
      id: { columnName: 'id', logicalType: 'integer', decode: 'string' },
      version: { columnName: 'version', logicalType: 'integer', decode: 'number' },
      createTime: { columnName: 'create_time', modelName: 'create_time', logicalType: 'datetime', decode: 'date' },
    } },
  }, { Task: checker }));

  await client.executeGraphSave(new MutationIntent('fix graph'), async graph => {
    await client.executeMutation(graph.request({ entity: 'Task', action: 'Create', payload: {} }));
    await new Promise(resolve => setTimeout(resolve, 5));
    await client.executeMutation(graph.request({ entity: 'Task', action: 'Create', payload: {} }));
  });

  expect(observed).toHaveLength(2);
  expect(observed[0].getTime()).toBe(expected.getTime());
  expect(observed[0]).toBe(observed[1]);
  expect(driver.transactions).toBe(1);
  expect(context.getResource('fixTime')).toBeUndefined();
});

test('independent concurrent graph saves are serialized instead of joining', async () => {
  const driver = new Driver();
  const client = new Client(driver).install(new RuntimeModule({
    Task: { table: 'task_data', columns: {
      id: { columnName: 'id', logicalType: 'integer', decode: 'string' },
      version: { columnName: 'version', logicalType: 'integer', decode: 'number' },
      name: { columnName: 'name', logicalType: 'text', decode: 'string' },
    } },
  }));
  const events: string[] = [];

  const first = client.executeGraphSave(new MutationIntent('first'), async graph => {
    events.push('first:start');
    await new Promise(resolve => setTimeout(resolve, 10));
    await client.executeMutation(graph.request({ entity: 'Task', action: 'Create', payload: { name: 'first' } }));
    events.push('first:end');
  });
  const second = client.executeGraphSave(new MutationIntent('second'), async graph => {
    events.push('second:start');
    await client.executeMutation(graph.request({ entity: 'Task', action: 'Create', payload: { name: 'second' } }));
    events.push('second:end');
  });

  await Promise.all([first, second]);
  expect(events).toEqual(['first:start', 'first:end', 'second:start', 'second:end']);
  expect(driver.transactions).toBe(2);
});

test('failed graph releases its captured business time and the next graph captures anew', async () => {
  const start = Date.parse('2032-02-29T10:15:30.000Z');
  let ticks = start;
  const context = new UserContext().withBusinessClock({ now: () => new Date(ticks++) });
  const client = new Client(new Driver()).setUserContext(context);
  await expect(client.executeGraphSave(new MutationIntent('failed graph'), async () => {
    expect(context.requireResource<Date>('fixTime').getTime()).toBe(start);
    expect(context.requireResource<Date>('fixTime').getTime()).toBe(start);
    throw new Error('injected failure');
  })).rejects.toThrow('injected failure');
  expect(context.getResource('fixTime')).toBeUndefined();
  await client.executeGraphSave(new MutationIntent('next graph'), async () => {
    expect(context.requireResource<Date>('fixTime').getTime()).toBe(start + 1);
  });
  expect(ticks).toBe(start + 2);
  expect(context.getResource('fixTime')).toBeUndefined();
});