@ultimat3/entity 31.48.0 → 31.50.0

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.
@@ -16,14 +16,18 @@
16
16
 
17
17
  import { currentWriteOrigin, type EntityRowOp, instrument, subscribed } from '@ultimat3/core';
18
18
  import { expectedQueryLoop } from '@ultimat3/db';
19
+ import { conflictKeyOf } from './bulk-write';
19
20
  import { copyColumns } from './copy-plan';
20
21
  import { counterEcho, type RepoOf } from './counter-observed';
22
+ import { valueAt } from './cursor';
21
23
  import type { EntityCore } from './entity';
22
24
  import { MAX_PAGE_SIZE } from './plan';
25
+ import { AND_PROPERTY, OR_PROPERTY } from './predicate-node';
23
26
  import { readRecorder } from './read-capture';
24
27
  import type { FilteredWriteOptions, Repo, RepoOptions, UpsertArgs } from './repo';
25
28
  import { sealedFields } from './sealed';
26
29
  import { searchMirroredRepo } from './search-mirrored-repo';
30
+ import type { Predicate } from './tenancy';
27
31
  import type { IdOf, RowPatch } from './types';
28
32
  import { afterCommit } from './write-commit';
29
33
 
@@ -136,6 +140,64 @@ const beforeAllOf = async <Row>(
136
140
  return before;
137
141
  };
138
142
 
143
+ /** Tuples per composite before-read: `(a = $1 and b = $2) or …` binds `on.length` per tuple. */
144
+ const TUPLES_PER_READ = 1_000;
145
+
146
+ /**
147
+ * The rows named by `chunk`'s conflict keys. One column is one `in`. Several are an `or` of
148
+ * per-tuple `and`s — never an `in` per column, whose product a diagonal batch of n pairs turns
149
+ * into n² stored rows read and held before the write runs.
150
+ */
151
+ const conflictWhere = <Row>(on: readonly string[], chunk: readonly Row[]): Predicate[] => {
152
+ const [only] = on;
153
+ if (on.length === 1 && only !== undefined) {
154
+ return [
155
+ { column: only, op: 'in', value: [...new Set(chunk.map((row) => valueAt(row, only)))] },
156
+ ];
157
+ }
158
+ const tuple = (row: Row): Predicate => ({
159
+ column: AND_PROPERTY,
160
+ op: 'and',
161
+ value: on.map((column) => ({ column, op: 'eq', value: valueAt(row, column) })),
162
+ });
163
+ return [{ column: OR_PROPERTY, op: 'or', value: chunk.map(tuple) }];
164
+ };
165
+
166
+ /**
167
+ * `beforeAllOf` for an upsert matched on a NATURAL key: the input names no id (or a fresh one), so
168
+ * the stored rows are read by the conflict target, paged to the end, and keyed by `conflictKeyOf`,
169
+ * the spelling the write itself matched on. Same floor on failure.
170
+ */
171
+ const beforeByConflictOf = async <Row>(
172
+ entity: EntityCore<Row>,
173
+ repo: Repo<Row>,
174
+ on: readonly string[],
175
+ rows: readonly Row[],
176
+ ): Promise<ReadonlyMap<string, Row>> => {
177
+ const before = new Map<string, Row>();
178
+ const keyed = rows.filter((row) => conflictKeyOf(entity, on, row as RowPatch<Row>) !== undefined);
179
+ if (keyed.length === 0 || !readsById(entity as EntityCore<unknown>)) return before;
180
+ const asked = new Set(keyed.map((row) => conflictKeyOf(entity, on, row as RowPatch<Row>)));
181
+ const size = on.length === 1 ? MAX_PAGE_SIZE : TUPLES_PER_READ;
182
+ try {
183
+ for (let at = 0; at < keyed.length; at += size) {
184
+ const where = conflictWhere(on, keyed.slice(at, at + size));
185
+ let cursor: string | null = null;
186
+ do {
187
+ const page = await repo.findMany({ where, limit: MAX_PAGE_SIZE, cursor });
188
+ for (const row of page.rows) {
189
+ const key = conflictKeyOf(entity, on, row as RowPatch<Row>);
190
+ if (key !== undefined && asked.has(key)) before.set(key, row);
191
+ }
192
+ cursor = page.nextCursor;
193
+ } while (cursor !== null);
194
+ }
195
+ } catch {
196
+ before.clear();
197
+ }
198
+ return before;
199
+ };
200
+
139
201
  /**
140
202
  * Wrap one repository so its writes are reported. Applied by `database()` to every table it builds,
141
203
  * so an app opts in by subscribing to `entity.row` and never by choosing a different repository — the
@@ -246,13 +308,18 @@ export function observedRepo<Row>(
246
308
  */
247
309
  upsertAll: async (rows: readonly Row[], args: UpsertArgs<Row>): Promise<readonly Row[]> => {
248
310
  if (!subscribed(ROW)) return await repo.upsertAll(rows, args);
249
- const ids = [...new Set(rows.flatMap((row) => idOf(row) ?? []))];
250
- const before = await beforeAllOf(entity, repo, ids);
311
+ // Matched on `id`, the row's id finds it; matched on anything else, only that target does.
312
+ const on: readonly string[] = args.onConflict;
313
+ const byId = on.length === 1 && on[0] === 'id';
314
+ const ids = byId ? [...new Set(rows.flatMap((row) => idOf(row) ?? []))] : [];
315
+ const before = byId
316
+ ? await beforeAllOf(entity, repo, ids)
317
+ : await beforeByConflictOf(entity, repo, on, rows);
251
318
  const stored = await repo.upsertAll(rows, args);
252
319
  const changes: (readonly [unknown, unknown])[] = [];
253
320
  for (const row of stored) {
254
- const id = idOf(row);
255
- const previous = id === undefined ? null : (before.get(id) ?? null);
321
+ const key = byId ? idOf(row) : conflictKeyOf(entity, on, row as RowPatch<Row>);
322
+ const previous = key === undefined ? null : (before.get(key) ?? null);
256
323
  emit(previous === null ? 'insert' : 'update', previous, row, args);
257
324
  changes.push([previous, row]);
258
325
  }
@@ -1,9 +1,10 @@
1
1
  // The ONE search path: a chain's `.search(term)` asks the INSTALLED `SearchIndex`. The built-in
2
2
  // Postgres index answers inside the statement (its `matches` predicate, today's SQL, untouched);
3
- // any other index is asked for ids first, and the chain then reads those rows with its own
4
- // tenancy, soft delete, order and cursor — so a Meilisearch hit can never widen what the chain sees.
3
+ // any other index is asked for ids first — per tenant the chain names — and the chain then reads
4
+ // those rows with its own tenancy, soft delete, order and cursor: a hit never widens what it sees.
5
5
 
6
6
  import { tryUseContext } from '@ultimat3/core';
7
+ import { crossTenantReason } from './cross-tenant';
7
8
  import type { EntityCore } from './entity';
8
9
  import { EntityError } from './errors';
9
10
  import { MAX_PAGE_SIZE } from './plan';
@@ -16,13 +17,28 @@ import type { Predicate } from './tenancy';
16
17
  const isMatch = (predicate: Predicate): boolean =>
17
18
  predicate.column === SEARCH_PROPERTY && predicate.op === 'matches';
18
19
 
19
- /** The tenant the chain is scoped to: its own `eq` on the tenant column, else the actor's. */
20
- const tenantOf = (entity: EntityCore<unknown>, where: readonly Predicate[]): string | null => {
20
+ /**
21
+ * The tenants the index is asked for: the chain's own `eq` on the tenant column, else — under
22
+ * `crossTenant` only — each tenant of its `in` list, else the actor's. Never the actor's under a
23
+ * lifted guard: the chain reads every tenant there, and the actor's org alone is a silent sample.
24
+ */
25
+ const tenantsOf = (entity: EntityCore<unknown>, where: readonly Predicate[]): (string | null)[] => {
21
26
  const column = entity.$tenantColumn;
22
- if (column === null) return null;
27
+ if (column === null) return [null];
23
28
  const named = where.find((each) => each.column === column && each.op === 'eq');
24
- if (typeof named?.value === 'string') return named.value;
25
- return tryUseContext()?.actor.orgId ?? null;
29
+ if (typeof named?.value === 'string') return [named.value];
30
+ const reason = crossTenantReason();
31
+ if (reason === undefined) return [tryUseContext()?.actor.orgId ?? null];
32
+ const listed = where.find((each) => each.column === column && each.op === 'in');
33
+ const tenants = Array.isArray(listed?.value) ? listed.value : undefined;
34
+ if (tenants?.every((tenant): tenant is string => typeof tenant === 'string')) {
35
+ return [...new Set(tenants)];
36
+ }
37
+ throw new EntityError({
38
+ code: 'X_INVARIANT_VIOLATED',
39
+ cause: `${entity.$name}.search(<term>) ran inside crossTenant('${reason}') through an external search index, which is asked one tenant at a time — and the chain names no ${column} to ask for`,
40
+ fix: `${entity.$name}.andWhere('${column}', 'in', [<orgId>, …]).search('<term>') # or installSearchIndex(postgresSearchIndex()), which matches every tenant inside the statement`,
41
+ });
26
42
  };
27
43
 
28
44
  /** The single key a hit's id is read back by; a composite key has no `in` an index id can name. */
@@ -58,21 +74,25 @@ const resolved = async (entity: EntityCore<unknown>, args: FindManyArgs): Promis
58
74
  const where = args.where ?? [];
59
75
  const index = searchIndex();
60
76
  if (answersInStatement(index)) return args;
61
- const tenant = tenantOf(entity, where);
77
+ const tenants = tenantsOf(entity, where);
62
78
  const swapped: Predicate[] = [];
63
79
  for (const predicate of where) {
64
80
  if (!isMatch(predicate)) {
65
81
  swapped.push(predicate);
66
82
  continue;
67
83
  }
68
- const hits = await index.query({
69
- entity: entity.$name,
70
- tenant,
71
- term: String(predicate.value ?? ''),
72
- limit: MAX_PAGE_SIZE,
73
- });
74
- if (hits.length >= MAX_PAGE_SIZE) throw tooManyHits(entity, index.name);
75
- swapped.push({ column: keyOf(entity), op: 'in', value: hits.map((hit) => hit.id) });
84
+ const ids: string[] = [];
85
+ for (const tenant of tenants) {
86
+ const hits = await index.query({
87
+ entity: entity.$name,
88
+ tenant,
89
+ term: String(predicate.value ?? ''),
90
+ limit: MAX_PAGE_SIZE,
91
+ });
92
+ if (hits.length >= MAX_PAGE_SIZE) throw tooManyHits(entity, index.name);
93
+ ids.push(...hits.map((hit) => hit.id));
94
+ }
95
+ swapped.push({ column: keyOf(entity), op: 'in', value: ids });
76
96
  }
77
97
  return { ...args, where: swapped };
78
98
  };
package/src/seed.ts CHANGED
@@ -188,16 +188,29 @@ export const isSeed = (value: unknown): value is Seed =>
188
188
  const cellOf = (row: unknown, property: string): unknown =>
189
189
  (row as Readonly<Record<string, unknown>>)[property];
190
190
 
191
+ /** A plain object's keys in one order: jsonb hands an object back in ITS order, not the seed's. */
192
+ const sortedKeys = (_key: string, value: unknown): unknown => {
193
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;
194
+ const prototype = Object.getPrototypeOf(value);
195
+ if (prototype !== Object.prototype && prototype !== null) return value;
196
+ return Object.fromEntries(
197
+ Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>
198
+ a < b ? -1 : a > b ? 1 : 0,
199
+ ),
200
+ );
201
+ };
202
+
191
203
  /**
192
204
  * Two cells, as a replay has to compare them: a `Date` is not `===` a `Date` and money is an
193
- * object, so both are compared by value and everything else by identity.
205
+ * object, so both are compared by value — an object's keys in any order, an array's in its own —
206
+ * and everything else by identity.
194
207
  */
195
208
  const sameCell = (left: unknown, right: unknown): boolean => {
196
209
  if (left instanceof Date || right instanceof Date) {
197
210
  return left instanceof Date && right instanceof Date && left.getTime() === right.getTime();
198
211
  }
199
212
  if (typeof left === 'object' && left !== null && typeof right === 'object' && right !== null) {
200
- return JSON.stringify(left) === JSON.stringify(right);
213
+ return JSON.stringify(left, sortedKeys) === JSON.stringify(right, sortedKeys);
201
214
  }
202
215
  return left === right;
203
216
  };
@@ -0,0 +1,22 @@
1
+ // Single responsibility: the text Postgres parses as a `uuid`, and the one spelling it prints —
2
+ // so an operand no `uuid` column can hold is known before a statement carries it, and a spelling
3
+ // the server would have matched is the same value to both drivers.
4
+
5
+ /**
6
+ * `uuid_in`'s grammar: thirty-two hex digits, a hyphen allowed after any group of four but the
7
+ * last, the whole optionally in braces. No blanks — the server refuses a padded value.
8
+ */
9
+ const UUID_TEXT = /^(?:[0-9a-f]{4}-?){7}[0-9a-f]{4}$/i;
10
+
11
+ /**
12
+ * The lower-cased `8-4-4-4-12` spelling of `value`, or `undefined` when it is not a `uuid`'s text.
13
+ * Bound as a parameter the latter is `22P02`, a 500 for an id straight out of a URL.
14
+ */
15
+ export const canonicalUuid = (value: unknown): string | undefined => {
16
+ if (typeof value !== 'string') return undefined;
17
+ const braced = value.startsWith('{') && value.endsWith('}');
18
+ const text = braced ? value.slice(1, -1) : value;
19
+ if (!UUID_TEXT.test(text)) return undefined;
20
+ const hex = text.replaceAll('-', '').toLowerCase();
21
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
22
+ };