|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Advisory-hit aggregation for machine load paths (#13889). |
| 5 | + * |
| 6 | + * ## The defect this closes |
| 7 | + * |
| 8 | + * A `severity: 'warning'` (or `'info'`) validation rule is ADVISORY: it never |
| 9 | + * blocks a write, and its message is written for a HUMAN IN A FORM ("At least |
| 10 | + * one related record should be selected"). The evaluator's only report channel |
| 11 | + * for one is `logger.warn`, one line per (row × violated rule). |
| 12 | + * |
| 13 | + * On an interactive write that is exactly right. On the seed / bootstrap load |
| 14 | + * path it is not: a clean-database first boot writes every seeded row through |
| 15 | + * the same evaluator, so an app whose seed legitimately contains N rows that |
| 16 | + * trip one advisory rule gets N `WARN` lines in the STARTUP LOG — a form hint |
| 17 | + * re-cast as a boot diagnostic, which reads like the boot failed. Measured |
| 18 | + * downstream (hotcrm#1203): the only ways an app could reach "zero warnings" |
| 19 | + * were to bend its data (attach a parent record it does not have) or delete the |
| 20 | + * rule (weaken a real guard). Both are worse than the noise. |
| 21 | + * |
| 22 | + * Maintainer ruling (2026-09-01, verbatim 「同意」 on option B): |
| 23 | + * 「⛔ 不改规则语义,只改日志形状」 — do not change rule semantics, change |
| 24 | + * only the shape of the log. So this module changes NOTHING about what a rule |
| 25 | + * evaluates to, who it applies to, or whether it blocks. It changes where the |
| 26 | + * REPORT goes while a machine load path is running, and nothing else. |
| 27 | + * |
| 28 | + * ## Why an ambient scope rather than a parameter |
| 29 | + * |
| 30 | + * The producer (`evaluateValidationRules`, `@objectstack/objectql`) and the |
| 31 | + * scope owner (`SeedLoaderService.load`, `@objectstack/metadata-protocol`) are |
| 32 | + * separated by the whole engine write path: the loader calls |
| 33 | + * `IDataEngine.insert/update`, and the evaluator is reached several layers |
| 34 | + * below through a contract that carries no reporting channel. Threading a sink |
| 35 | + * through would mean widening `IDataEngine`'s options — a published contract — |
| 36 | + * for a diagnostic concern. An ambient scope keeps the change inside the two |
| 37 | + * ends that care. |
| 38 | + * |
| 39 | + * `AsyncLocalStorage` rather than a module-level flag, deliberately: seed loads |
| 40 | + * are NOT boot-only. A per-org replay (`sys_organization` insert) runs a full |
| 41 | + * seed load on a LIVE server, concurrently with ordinary interactive traffic. A |
| 42 | + * plain global would capture those interactive writes' advisories into the |
| 43 | + * replay's summary — silently swallowing a report meant for someone else. ALS |
| 44 | + * scopes the capture to the load's own async context, which is the difference |
| 45 | + * between aggregating and losing. |
| 46 | + * |
| 47 | + * ## Folded on arrival, never accumulated per row |
| 48 | + * |
| 49 | + * A hit is folded into its `(object, rule)` group as it arrives, so a load of |
| 50 | + * 100 000 rows that all trip one rule holds ONE group, not 100 000 records. |
| 51 | + * The group keeps what a reader needs to act — the rule, the object, the |
| 52 | + * severity, the message, the row count, and up to {@link ADVISORY_SAMPLE_ROWS} |
| 53 | + * example rows — which is the 「详见…」 half of the ruling's summary shape. |
| 54 | + */ |
| 55 | + |
| 56 | +import { AsyncLocalStorage } from 'node:async_hooks'; |
| 57 | + |
| 58 | +/** Example row references a group carries, so the summary can point at real rows. */ |
| 59 | +export const ADVISORY_SAMPLE_ROWS = 5; |
| 60 | + |
| 61 | +/** One advisory rule hit, as the evaluator reports it. */ |
| 62 | +export interface AdvisoryHit { |
| 63 | + /** Object the row belongs to. */ |
| 64 | + object: string; |
| 65 | + /** The declared rule's `name`. */ |
| 66 | + rule: string; |
| 67 | + /** The rule's declared severity — `'warning'` or `'info'`; never `'error'`. */ |
| 68 | + severity: string; |
| 69 | + /** The rule's author-written message, in the caller's locale. */ |
| 70 | + message: string; |
| 71 | + /** |
| 72 | + * A reference to the row, when the write carries one. |
| 73 | + * |
| 74 | + * NOT necessarily an id: on the path this exists for — a seed INSERT — the |
| 75 | + * driver has not issued an id yet at validation time, so an id-only reference |
| 76 | + * would be empty for exactly the case the aggregation was built for. The |
| 77 | + * producer sends the best stable handle it has (`id`, else `name=<value>`, |
| 78 | + * the same way the seed loader names a row in its own errors). |
| 79 | + */ |
| 80 | + recordRef?: string; |
| 81 | +} |
| 82 | + |
| 83 | +/** Every hit for one `(object, rule)` pair, folded. */ |
| 84 | +export interface AdvisoryGroup { |
| 85 | + object: string; |
| 86 | + rule: string; |
| 87 | + severity: string; |
| 88 | + /** The first message seen for this group (they differ only by interpolation). */ |
| 89 | + message: string; |
| 90 | + /** How many ROWS tripped this rule during the scope. */ |
| 91 | + rows: number; |
| 92 | + /** Up to {@link ADVISORY_SAMPLE_ROWS} example row references. */ |
| 93 | + sampleRows: string[]; |
| 94 | +} |
| 95 | + |
| 96 | +interface AdvisoryCollector { |
| 97 | + groups: Map<string, AdvisoryGroup>; |
| 98 | +} |
| 99 | + |
| 100 | +const storage = new AsyncLocalStorage<AdvisoryCollector>(); |
| 101 | + |
| 102 | +/** |
| 103 | + * Group key. |
| 104 | + * |
| 105 | + * `JSON.stringify` of the pair rather than a delimiter-joined string: any |
| 106 | + * single-character delimiter is a claim about what an object or rule name |
| 107 | + * cannot contain, and a wrong claim collides two groups into one silently. |
| 108 | + * Encoding the pair makes the key injective with nothing to be wrong about. |
| 109 | + */ |
| 110 | +function keyOf(object: string, rule: string): string { |
| 111 | + return JSON.stringify([object, rule]); |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Offer one advisory hit to the active aggregation scope. |
| 116 | + * |
| 117 | + * @returns `true` when a scope captured it — the caller must then NOT log its |
| 118 | + * own per-row line, because the scope owner reports the whole group. `false` |
| 119 | + * when no scope is active, which is the ordinary interactive case: the caller |
| 120 | + * logs exactly as it always did. A caller that ignores the return value |
| 121 | + * degrades to today's behaviour rather than losing the report. |
| 122 | + */ |
| 123 | +export function recordAdvisoryHit(hit: AdvisoryHit): boolean { |
| 124 | + const collector = storage.getStore(); |
| 125 | + if (!collector) return false; |
| 126 | + const key = keyOf(hit.object, hit.rule); |
| 127 | + const existing = collector.groups.get(key); |
| 128 | + if (existing) { |
| 129 | + existing.rows += 1; |
| 130 | + if (hit.recordRef != null && existing.sampleRows.length < ADVISORY_SAMPLE_ROWS) { |
| 131 | + existing.sampleRows.push(hit.recordRef); |
| 132 | + } |
| 133 | + return true; |
| 134 | + } |
| 135 | + collector.groups.set(key, { |
| 136 | + object: hit.object, |
| 137 | + rule: hit.rule, |
| 138 | + severity: hit.severity, |
| 139 | + message: hit.message, |
| 140 | + rows: 1, |
| 141 | + sampleRows: hit.recordRef != null ? [hit.recordRef] : [], |
| 142 | + }); |
| 143 | + return true; |
| 144 | +} |
| 145 | + |
| 146 | +/** |
| 147 | + * Whether an advisory aggregation scope is active on this async context. |
| 148 | + * |
| 149 | + * Exported for tests and for a caller that wants to skip building a message it |
| 150 | + * is about to discard; {@link recordAdvisoryHit}'s return value is the one that |
| 151 | + * decides. |
| 152 | + */ |
| 153 | +export function isAggregatingAdvisories(): boolean { |
| 154 | + return storage.getStore() !== undefined; |
| 155 | +} |
| 156 | + |
| 157 | +/** |
| 158 | + * Run `fn` with advisory hits aggregated, then hand the folded groups to |
| 159 | + * `report`. |
| 160 | + * |
| 161 | + * `report` runs in a `finally`, so a load that throws still reports what it |
| 162 | + * tripped before failing — the diagnostics of a half-finished seed are the ones |
| 163 | + * most worth having. It is called only when there is something to report, and |
| 164 | + * its own failure is never allowed to replace the caller's outcome: a reporting |
| 165 | + * bug must not turn a successful seed load into a failed one. |
| 166 | + */ |
| 167 | +export async function runWithAdvisoryAggregation<T>( |
| 168 | + fn: () => Promise<T>, |
| 169 | + report: (groups: AdvisoryGroup[]) => void, |
| 170 | +): Promise<T> { |
| 171 | + const collector: AdvisoryCollector = { groups: new Map() }; |
| 172 | + try { |
| 173 | + return await storage.run(collector, fn); |
| 174 | + } finally { |
| 175 | + if (collector.groups.size > 0) { |
| 176 | + try { |
| 177 | + report([...collector.groups.values()]); |
| 178 | + } catch { |
| 179 | + // Reporting is a diagnostic, never an outcome. |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments