Skip to content

Commit 5430b4a

Browse files
fix(service-storage)!: an upload link is refused at issue for a file field whose readonlyWhen holds now (#32768) (#33079)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DDqqDa5SijBGNapewRUK6xS)_ Fixes #32768 Clause-②: yes (narrowing) Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches `create_upload_link` or upload links; the tool's own description and `content/docs/ai/connect-mcp.mdx` carry the refusal, updated here ## 维护者速读 - 改了什么:AI 通过 MCP 的 `create_upload_link` 给用户要上传链接时,如果目标文件字段此刻被 `readonlyWhen` 锁住(例如报销单已审批后,发票字段只读),现在直接拒绝、不发链接,拒绝理由用的是更新接口对同一把锁的原话。引擎新增一个只读不写的判断 `judgeFieldWriteLock`,复用更新路径自己的 `readonlyWhen` 判定,存储层只调用它,不另写一套表达式求值。 - 为什么改:#32734 之后,这种情况下用户要先选文件、上传,才在页面上被告知「没有附上」。白跑一趟。现在在发链接那一步就告诉 AI 原因,AI 可以直接跟用户解释。 - 风险与回滚:收紧(BREAKING 标注):原来能拿到链接的调用现在被拒,403 `FIELD_NOT_ACCESSIBLE`,与静态只读字段同一个错误码。附件列表(不指定字段)不受影响;没有 `readonlyWhen` 的字段不多读一次库。回滚 = revert 本 PR,用户回到「上传后被拒」的旧体验,数据不受影响。 - 先看:`packages/objectql/src/engine-field-write-lock.ts`(判断本体,看它是否与更新路径同源);`packages/services/service-storage/src/record-file-access.ts` 的 `createUploadLinkAs` 新增的那段拒绝;`packages/objectql/src/engine.ts` 新方法 `judgeFieldWriteLock`。 - 两分钟验证:`pnpm --filter @objectstack/service-storage exec vitest run src/record-file-access.integration.test.ts`,预期 36/36 通过,其中「minting refuses a field whose readonlyWhen holds now」一条绿。 - 需要你做的:本 PR 是收紧(narrowing),按车队规则需要你一句话同意后席位才排队落地。 **BREAKING** for a caller that minted an upload link onto a file field while the field's `readonlyWhen` held. - FROM: `create_upload_link` answered a link; the upload through it was refused when it arrived (`403 FIELD_NOT_ACCESSIBLE`, "Nothing was attached: …", since #32734), after the person had picked and sent the file. - TO: the call itself is refused, `403 FIELD_NOT_ACCESSIBLE`, ``You cannot attach a file to OBJECT.FIELD: the field is read-only in the target record's current state (a TRUE `readonlyWhen` predicate).``, and no link row is written. The fix for a caller: mint the link once the record's state unlocks the field, or use the record's attachments, which carry no field lock and are unchanged. ## What changes - **`@objectstack/objectql`** — `ObjectQL#judgeFieldWriteLock(object, id, field, { context })`, the one write-free judgement of "is this field writable on this record now" for its `readonlyWhen` lock. Its body (`engine-field-write-lock.ts`) runs the update's own conditional strip, `stripReadonlyWhenFields`, over the update's own inputs: the stored row from `readUpdatePriorRow` as `previous`, the master-detail header from `resolveMasterDetailParent` under the same gate (`hasParentScopedReadonlyWhenInPayload`), and a payload carrying the value the field holds now. It answers `null`, or `{ reason: 'readonly_when', phrase }`: the `DroppedFieldsEvent['reason']` the update reports the field under, and the phrase `ReadonlyFieldRejectedError` uses for that reason (`readonlyDropReasonPhrase`, newly exported from `readonly-strict-errors.ts`, not from the package entry). A faulting predicate refuses as the write refuses; an unbound root holds the lock; a row the caller cannot read is `RECORD_NOT_FOUND`; a field with no `readonlyWhen` reads nothing. The facade method in `engine.ts` is a delegation in the shape `validate` uses. `FieldWriteLock` is exported as a type. - **`@objectstack/service-storage`** — `createUploadLinkAs`, for a file-field target, asks `engine.judgeFieldWriteLock` after the static `readonly` refusal and before the approval lock, and refuses `403 FIELD_NOT_ACCESSIBLE` with the engine's phrase. No CEL is evaluated here. The member is optional on `RecordFileEngine`: an engine without it is not asked, and the upload's own strict write still refuses on arrival. **An attachments target (no field) is unchanged** — it carries no field lock and is not judged. - **`@objectstack/mcp`** — the `create_upload_link` description names the new refusal. `packages/mcp/src/file-content.ts` is not touched: it only declares the bridge types; the issue-time refusals live in `service-storage` (measured, and declared on the re-posted claim 6847846915). - **Docs** — `content/docs/ai/connect-mcp.mdx`: which fields get no link, and with what answer. - **Update preview (`engine.validate`, `ValidateDataResponse`)** — not changed. Its published limit (`readonlyWhen` is not run) stays as written, so no published preview surface widens. The new judgement is a separate method; its only widening is the method itself. ## Tests - `packages/objectql/src/engine-field-write-lock.test.ts` (new, 7): locked with the update's reason and phrase; unlocked while the condition is false; a `parent`-scoped lock reads the header; each verdict cross-checked against what `engine.update` reports for the same field (`onFieldsDropped`, `readonly_when`); no `readonlyWhen` costs no read; a faulting predicate refuses as `ValidationError`; a missing row is `RECORD_NOT_FOUND` 404; no driver write and no strip warning in any case. - `packages/services/service-storage/src/record-file-access.integration.test.ts` (+2): minting on an approved claim's `invoices` is refused 403 with the exact sentence and writes no link row; the same field on a draft gets a link, a static `readonly` field keeps its refusal word for word, and the attachments list of an approved claim still gets a link. - `packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts` (+1, the one dogfood pin, over the real MCP HTTP face): after approval `create_upload_link` is refused 403 with the engine's phrase and mints nothing, and `update_record` on the same field answers `droppedFields` with reason `readonly_when` naming it. ## Acceptance notes - Out of scope, report only (as the order names): the consume-side refusal and page text (#32734, done), several files per link (#32747), upload before the record exists (#32686). - Named limits of the judgement, documented on the method: `beforeUpdate` hooks are not run (a hook that rewrites a field a predicate reads moves the write's verdict and not this one); a lock whose predicate reads the incoming value of its own field is judged against the value already stored. - PR #32932 (same `area:files` door) touches none of these files. ## Verification All readings at head `c3e09f34` unless named; the full dogfood battery ran at `d9c65672`, and the one commit after it (`c3e09f34`) changes only the objectql unit test's driver double (it applies the caller's `limit`, for `check:objectql-double-limit`), re-run below. <details><summary>Package tests and typecheck (objectql, service-storage, mcp)</summary> - `pnpm --filter @objectstack/objectql test` — Test Files 594 passed (594), Tests 12784 passed (12784) - `pnpm --filter @objectstack/service-storage test` — Test Files 79 passed (79), Tests 1486 passed (1486) - `pnpm --filter @objectstack/mcp test` — Test Files 63 passed (63), Tests 1096 passed (1096) - `pnpm --filter @objectstack/objectql typecheck`, `@objectstack/service-storage typecheck`, `@objectstack/mcp typecheck` — exit 0 each (after the dependency closure build) - `engine-field-write-lock.test.ts` re-run at `c3e09f34` — Tests 7 passed (7) - `record-file-access.integration.test.ts` at `d9c65672` — Tests 36 passed (36) </details> <details><summary>Ablation of the issue-time refusal</summary> Through `scripts/ablation-replace.mjs` on `packages/services/service-storage/src/record-file-access.ts` (committed head as the restore point): anchor `refuse('FIELD_NOT_ACCESSIBLE', 403, ... the field is ${lock.phrase}.)` x1 -> x0, replacement `void lock;` x0 -> x1, blob `a771bfae` -> `d5ac8211`. `record-file-access.integration.test.ts` under the mutation: **1 failed | 35 passed**, the failing one `minting refuses a field whose readonlyWhen holds now 403 FIELD_NOT_ACCESSIBLE, in the update's words, and writes no link`. Restored: blob == HEAD (`a771bfae`), `git diff HEAD` empty. The test runs the package's source, so no `dist/` leg. </details> <details><summary>Full dogfood battery (Clause-② narrowing arm)</summary> `pnpm --filter @objectstack/dogfood test` under the verify lock at `d9c65672`: Test Files 458 passed | 3 skipped (461), Tests 3845 passed | 42 skipped (3887), `VERDICT command-exit 0`. The new pin in `showcase-mcp-record-files.dogfood.test.ts` is among them (that file alone: 15/15). </details> <details><summary>Derived gates and lint</summary> `node scripts/pm/dispatch-gates.mjs --commands` (from the merge base, after `origin/main` was merged once at `05853f3a`): 104 families. Run record with exit codes: `--ran` reconciles **104 accounted, 101 run, 3 NOT MEASURED**: - `node scripts/check-plugin-teardown-shape.mjs --self-test` — exit 3, PREREQUISITE NOT MET: its positive control is a pinned commit a shallow clone cannot reach. NOT MEASURED, reason: shallow checkout; CI runs it. - `pnpm --filter @objectstack/spec run check:skill-examples` — exit 3, PREREQUISITE NOT MET: `packages/client-react/dist` not built (outside this diff's closure). NOT MEASURED; CI runs it. - `pnpm check:dual-build-cjs-loads` — exit 3, PREREQUISITE NOT MET: unbuilt packages outside this diff's closure (studio, client-react, scenarios, …). NOT MEASURED; CI runs it. Two reds found and fixed on this branch: `check:tenant-audit-census` (the `RecordFileEngine` type, widened as a type literal, stopped being an engine-shaped type the census reads; now an interface extending `IDataEngine`, census back to 310) and `check:objectql-double-limit` (the new test's driver double ignored `limit`). Both exit 0 at `c3e09f34`, as do `check:engine-double-contract` and `check:nul-bytes`. `node scripts/check-platform-checklist.mjs --changed-from origin/main` — OK, 21 anchors judged, 0 lost. `pnpm lint` — exit 0. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4czfTdXkf83P5ogS9TT)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a752057 commit 5430b4a

11 files changed

Lines changed: 458 additions & 3 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/service-storage': patch
4+
'@objectstack/mcp': patch
5+
---
6+
7+
fix(service-storage)!: an upload link is refused at issue for a file field whose `readonlyWhen` holds now (#32768)
8+
9+
Clause-②: yes (narrowing) — `create_upload_link` (`createUploadLinkAs`) issues no link for a file field whose `readonlyWhen` holds on the record as it stands, where it issued one and the upload was refused when it arrived. The engine gains one write-free judgement, `ObjectQL#judgeFieldWriteLock` (widening).
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no stored shape changes. The refusal is the existing FIELD_NOT_ACCESSIBLE 403 the link door already answers for a static readonly field, so there is nothing for a migration to rewrite and no tombstone. -->
13+
14+
**BREAKING** for a caller that minted an upload link onto a file field while its `readonlyWhen` held.
15+
16+
FROM: `create_upload_link` answered a link, and the upload through it was refused when it arrived (`403 FIELD_NOT_ACCESSIBLE`, "Nothing was attached: …", since #32734), after the person had picked and sent the file.
17+
TO: the call itself is refused, `403 FIELD_NOT_ACCESSIBLE`, `You cannot attach a file to OBJECT.FIELD: the field is read-only in the target record's current state (a TRUE \`readonlyWhen\` predicate).`, and no link is written. The fix for a caller: mint the link once the record's state unlocks the field, or use the record's attachments, which carry no field lock and are unchanged.
18+
19+
The verdict is the engine's own: `ObjectQL#judgeFieldWriteLock(object, id, field, { context })` runs the update's `readonlyWhen` strip over the update's stored-row read and master-detail header, without writing, and answers the reason the update reports the field under (`readonly_when`) with the words its strict refusal uses. A field with no `readonlyWhen` costs no read. A static `readonly` field and a record a pending approval locks are refused at issue as before.

‎content/docs/ai/connect-mcp.mdx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,15 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`.
306306
`401`, and a second use, an expired link, an unknown link and another user's
307307
link all get the same `404`. The upload is stored as that user, with their
308308
access checked again when the file arrives, and it meets the storage
309-
service's maximum upload size before the link is spent. Sending a file's
309+
service's maximum upload size before the link is spent. A field that cannot
310+
take the upload now gets no link: a `readonly` field, or one whose
311+
`readonlyWhen` holds on this record as it stands (refused `403`
312+
`FIELD_NOT_ACCESSIBLE`, naming the lock in the words the engine update's
313+
strict refusal (`strictReadonlyWrites`) uses for it; `update_record` reports
314+
the same lock under `droppedFields` with reason `readonly_when`), and a
315+
record a pending approval locks (`409`
316+
`RECORD_LOCKED`). A field that becomes read-only after the link was made
317+
refuses the upload when it arrives, attaching nothing. Sending a file's
310318
bytes through the MCP protocol itself is not supported yet.
311319

312320
Reading a PDF or Word document's text runs on a pool of worker threads, so the

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3371,7 +3371,8 @@ export function registerFileTools(
33713371
'as an attachment (attachments: true). Give the link to the user to open in a browser where they are ' +
33723372
'signed in to this deployment as themselves; it works only for them, once, for this record and field ' +
33733373
'only, and expires (see expiresAt). The upload is stored as the user, so they must be able to edit the ' +
3374-
'record (and the field): a record a pending approval locks, or a read-only field, gets no link, and an ' +
3374+
'record (and the field): a record a pending approval locks, a read-only field, or a field read-only on ' +
3375+
'this record in its current state (readonlyWhen), gets no link, and an ' +
33753376
'upload the field cannot take when it arrives is refused with the reason, attaching nothing.',
33763377
inputSchema: strictToolInput(
33773378
{
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// #32768 — `ObjectQL#judgeFieldWriteLock`: the update's own `readonlyWhen`
4+
// verdict on one field of one record, asked without writing. A door that hands
5+
// out a promise to write a field later (the upload link) asks it first.
6+
//
7+
// Pinned against the write itself: for every row below, the judgement says
8+
// LOCKED exactly when an update of the field reports it dropped under
9+
// `readonly_when`, and nothing the judgement does reaches the driver's write
10+
// verbs.
11+
12+
import { describe, it, expect, beforeEach } from 'vitest';
13+
import type { DroppedFieldsEvent } from '@objectstack/spec/data';
14+
import { ObjectQL } from './engine.js';
15+
16+
function makeDriver() {
17+
const stores = new Map<string, Map<string, any>>();
18+
const writes: string[] = [];
19+
const storeFor = (o: string) => {
20+
let s = stores.get(o);
21+
if (!s) { s = new Map(); stores.set(o, s); }
22+
return s;
23+
};
24+
const matches = (row: any, where: any): boolean => {
25+
if (!where || typeof where !== 'object') return true;
26+
return Object.entries(where).every(([k, v]: [string, any]) => {
27+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
28+
return row?.[k] === v;
29+
});
30+
};
31+
const driver: any = {
32+
name: 'memory', version: '0.0.0', supports: {},
33+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
34+
async find(object: string, ast: any) {
35+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
36+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
37+
},
38+
async findOne(object: string, ast: any) {
39+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return r;
40+
return null;
41+
},
42+
async create(object: string, data: Record<string, unknown>) {
43+
writes.push(`create ${object}`);
44+
const row = { ...data, id: data.id as string };
45+
storeFor(object).set(row.id, row);
46+
return row;
47+
},
48+
async update(object: string, id: string, data: Record<string, unknown>) {
49+
writes.push(`update ${object}`);
50+
const s = storeFor(object);
51+
const row = { ...s.get(id), ...data, id };
52+
s.set(id, row);
53+
return row;
54+
},
55+
async updateMany() { writes.push('updateMany'); return 0; },
56+
async delete() { writes.push('delete'); return true; },
57+
async count() { return 0; },
58+
async bulkCreate() { writes.push('bulkCreate'); return []; },
59+
async bulkUpdate() { writes.push('bulkUpdate'); return []; }, async bulkDelete() { writes.push('bulkDelete'); },
60+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
61+
async commit() {}, async rollback() {},
62+
};
63+
return { driver, storeFor, writes };
64+
}
65+
66+
const PHRASE = "read-only in the target record's current state (a TRUE `readonlyWhen` predicate)";
67+
68+
describe('judgeFieldWriteLock: the update\'s readonlyWhen verdict, without the write (#32768)', () => {
69+
let engine: ObjectQL;
70+
let d: ReturnType<typeof makeDriver>;
71+
let warns: string[];
72+
73+
beforeEach(async () => {
74+
warns = [];
75+
const logger: any = {
76+
warn: (m: string) => warns.push(String(m)),
77+
debug() {}, info() {}, error() {}, trace() {}, fatal() {},
78+
child() { return logger; },
79+
};
80+
engine = new ObjectQL({ logger });
81+
d = makeDriver();
82+
engine.registerDriver(d.driver, true);
83+
await engine.init();
84+
85+
engine.registry.registerObject({
86+
name: 'expense_claim',
87+
fields: {
88+
name: { type: 'text' },
89+
status: { type: 'text' },
90+
invoices: { type: 'file', multiple: true, readonlyWhen: "record.status == 'approved'" },
91+
note: { type: 'text' },
92+
broken: { type: 'text', readonlyWhen: 'record.no_such_field == 1' },
93+
},
94+
} as any, 'test');
95+
engine.registry.registerObject({
96+
name: 'expense_report',
97+
fields: { name: { type: 'text' }, status: { type: 'text' } },
98+
} as any, 'test');
99+
engine.registry.registerObject({
100+
name: 'expense_line',
101+
fields: {
102+
report: { type: 'master_detail', reference: 'expense_report', required: true },
103+
receipt: { type: 'file', readonlyWhen: "parent.status == 'paid'" },
104+
},
105+
} as any, 'test');
106+
107+
d.storeFor('expense_claim').set('c_draft', { id: 'c_draft', name: 'Lyon', status: 'draft', invoices: null, note: null, broken: null });
108+
d.storeFor('expense_claim').set('c_approved', { id: 'c_approved', name: 'Rome', status: 'approved', invoices: null, note: null, broken: null });
109+
d.storeFor('expense_report').set('r_paid', { id: 'r_paid', name: 'Q3', status: 'paid' });
110+
d.storeFor('expense_report').set('r_open', { id: 'r_open', name: 'Q4', status: 'open' });
111+
d.storeFor('expense_line').set('l_paid', { id: 'l_paid', report: 'r_paid', receipt: null });
112+
d.storeFor('expense_line').set('l_open', { id: 'l_open', report: 'r_open', receipt: null });
113+
});
114+
115+
/** What the update itself reports for `field` on `id`: dropped under `readonly_when`, or kept. */
116+
async function updateDrops(object: string, id: string, field: string, value: unknown = 'f_new'): Promise<boolean> {
117+
const events: DroppedFieldsEvent[] = [];
118+
await engine.update(object, { [field]: value }, {
119+
where: { id },
120+
context: { isSystem: true },
121+
onFieldsDropped: (e: DroppedFieldsEvent) => { events.push(e); },
122+
} as any);
123+
return events.some((e) => e.reason === 'readonly_when' && e.fields.includes(field));
124+
}
125+
126+
it('a field whose readonlyWhen holds now is locked, with the update\'s reason and its strict refusal\'s words', async () => {
127+
const lock = await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'invoices', { context: { isSystem: true } as any });
128+
expect(lock).toEqual({ reason: 'readonly_when', phrase: PHRASE });
129+
expect(d.writes).toEqual([]);
130+
expect(await updateDrops('expense_claim', 'c_approved', 'invoices', ['f_new'])).toBe(true);
131+
});
132+
133+
it('the same field while the condition is false is writable', async () => {
134+
expect(await engine.judgeFieldWriteLock('expense_claim', 'c_draft', 'invoices', { context: { isSystem: true } as any })).toBeNull();
135+
expect(d.writes).toEqual([]);
136+
expect(await updateDrops('expense_claim', 'c_draft', 'invoices', ['f_new'])).toBe(false);
137+
});
138+
139+
it('a parent-scoped lock reads the master-detail header, as the update does', async () => {
140+
expect(await engine.judgeFieldWriteLock('expense_line', 'l_paid', 'receipt', { context: { isSystem: true } as any }))
141+
.toEqual({ reason: 'readonly_when', phrase: PHRASE });
142+
expect(await engine.judgeFieldWriteLock('expense_line', 'l_open', 'receipt', { context: { isSystem: true } as any })).toBeNull();
143+
expect(d.writes).toEqual([]);
144+
expect(await updateDrops('expense_line', 'l_paid', 'receipt')).toBe(true);
145+
expect(await updateDrops('expense_line', 'l_open', 'receipt')).toBe(false);
146+
});
147+
148+
it('a field that declares no readonlyWhen is writable and costs no read', async () => {
149+
const findOne = d.driver.findOne;
150+
let reads = 0;
151+
d.driver.findOne = async (...a: any[]) => { reads += 1; return findOne(...a); };
152+
expect(await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'note', { context: { isSystem: true } as any })).toBeNull();
153+
expect(reads).toBe(0);
154+
});
155+
156+
it('a predicate that faults refuses as the write refuses it, and writes nothing', async () => {
157+
const err = await engine.judgeFieldWriteLock('expense_claim', 'c_draft', 'broken', { context: { isSystem: true } as any })
158+
.then(() => null, (e: unknown) => e as { code?: string; name?: string });
159+
expect(err).not.toBeNull();
160+
expect(err?.name).toBe('ValidationError');
161+
expect(d.writes).toEqual([]);
162+
});
163+
164+
it('a record that is not there answers as the by-id update answers it', async () => {
165+
const err = await engine.judgeFieldWriteLock('expense_claim', 'c_missing', 'invoices', { context: { isSystem: true } as any })
166+
.then(() => null, (e: unknown) => e as { code?: string; status?: number });
167+
expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 });
168+
});
169+
170+
it('logs no strip line: nothing was written, so "ignoring incoming change" is not true', async () => {
171+
await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'invoices', { context: { isSystem: true } as any });
172+
expect(warns.filter((w) => w.includes('ignoring incoming change'))).toEqual([]);
173+
});
174+
});
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#32768] The body of `ObjectQL#judgeFieldWriteLock`: is `field` writable on
5+
* the record `id` names, NOW, as far as its `readonlyWhen` lock goes — asked
6+
* without writing anything.
7+
*
8+
* ## Why it exists
9+
*
10+
* A door that hands out a promise to write a field later (the upload link
11+
* `create_upload_link` mints) needs the update's verdict on that field before
12+
* the write happens. The update preview (`validate`) names `readonlyWhen` as a
13+
* limit it does not run (`ValidateDataResponse`), and the field-access read
14+
* (`getRecordFieldAccess`) leaves conditional read-only out. So the door could
15+
* only learn the lock by attempting the write. This answers it without one.
16+
*
17+
* ## The same evaluation, not a second one
18+
*
19+
* The verdict is the update's own conditional strip
20+
* ({@link stripReadonlyWhenFields}), run over the inputs the by-id update
21+
* hands it: the stored row as `previous`, read by the update's own prior-row
22+
* read ({@link ObjectQL.readUpdatePriorRow}); the master-detail header as
23+
* `parent`, resolved by the update's own resolver and under the same gate
24+
* ({@link hasParentScopedReadonlyWhenInPayload}); and a payload carrying the
25+
* field. The field is LOCKED when that strip would take it back out. A
26+
* predicate that faults refuses here as it refuses the write (the
27+
* `ValidationError` the strip throws), and an unbound root holds the lock, as
28+
* on the write. No logger is handed to the strip: nothing is written, so no
29+
* "ignoring incoming change" line is true.
30+
*
31+
* ## What it judges the field with
32+
*
33+
* The payload carries the value the field holds NOW (the stored row's), so a
34+
* predicate reads the record exactly as it stands: `record` is the stored row,
35+
* `previous` is the stored row. A lock whose predicate reads the INCOMING
36+
* value of its own field cannot be judged before that value exists; it is
37+
* judged here against the value already there.
38+
*
39+
* ## Named limits
40+
*
41+
* - The update's `beforeUpdate` hooks are not run. A hook that rewrites a
42+
* field a predicate reads moves the write's verdict and not this one.
43+
* - Static `readonly` is not judged here: it is a property of the field's
44+
* definition, readable off the schema without the record.
45+
* - Neither are the update's other refusals (permissions, an approval's
46+
* record lock, validation rules): they belong to their own doors.
47+
*
48+
* ## Reads
49+
*
50+
* None for a field that declares no `readonlyWhen`. Otherwise: the READ DOOR
51+
* first, under the caller's own context — a row the caller cannot read is a
52+
* row that does not exist, answered `recordNotFoundError` as the by-id update
53+
* answers it — then the stored row, then the header when a predicate on the
54+
* field reads `parent`.
55+
*/
56+
57+
import { recordNotFoundError } from '@objectstack/core';
58+
import type { EngineQueryOptions } from '@objectstack/spec/data';
59+
import type { ExecutionContext } from '@objectstack/spec/kernel';
60+
import type { ObjectQL } from './engine.js';
61+
import { readonlyDropReasonPhrase } from './readonly-strict-errors.js';
62+
import { hasParentScopedReadonlyWhenInPayload, stripReadonlyWhenFields } from './validation/rule-validator.js';
63+
64+
/**
65+
* A lock that keeps a field from taking a caller's write now. `reason` is the
66+
* `DroppedFieldsEvent['reason']` the update reports the field under
67+
* (`onFieldsDropped`, `droppedFields`); `phrase` is how the update's strict
68+
* refusal (`ReadonlyFieldRejectedError`) names that reason.
69+
*/
70+
export interface FieldWriteLock {
71+
readonly reason: 'readonly_when';
72+
readonly phrase: string;
73+
}
74+
75+
/** The members of `ObjectQL` the judgement reads. */
76+
export interface FieldWriteLockHost {
77+
resolveObjectName: ObjectQL['resolveObjectName'];
78+
readonly _registry: ObjectQL['_registry'];
79+
findOne: ObjectQL['findOne'];
80+
readUpdatePriorRow: ObjectQL['readUpdatePriorRow'];
81+
resolveMasterDetailParent: ObjectQL['resolveMasterDetailParent'];
82+
}
83+
84+
/** The body of `ObjectQL#judgeFieldWriteLock`; the method's docblock there is its contract. */
85+
export async function judgeFieldWriteLock(
86+
this: FieldWriteLockHost,
87+
objectName: string,
88+
id: unknown,
89+
field: string,
90+
options?: { context?: ExecutionContext },
91+
): Promise<FieldWriteLock | null> {
92+
const object = this.resolveObjectName(objectName);
93+
const schema = this._registry.getObject(object) as { fields?: Record<string, { readonlyWhen?: unknown }> } | undefined;
94+
const def = schema?.fields?.[field];
95+
if (!def || !def.readonlyWhen) return null;
96+
97+
const context = options?.context;
98+
const visible = await this.findOne(object, { where: { id }, context } as EngineQueryOptions);
99+
const prior = visible && typeof visible === 'object' ? await this.readUpdatePriorRow(object, id, context) : null;
100+
if (!prior) throw recordNotFoundError(object, id as string);
101+
102+
const payload: Record<string, unknown> = { [field]: Object.prototype.hasOwnProperty.call(prior, field) ? prior[field] : null };
103+
const parent = hasParentScopedReadonlyWhenInPayload(schema as never, payload)
104+
? await this.resolveMasterDetailParent(schema, payload, prior, context)
105+
: undefined;
106+
const kept = stripReadonlyWhenFields(schema as never, payload, prior, undefined, parent);
107+
if (kept && Object.prototype.hasOwnProperty.call(kept, field)) return null;
108+
return { reason: 'readonly_when', phrase: readonlyDropReasonPhrase('readonly_when') };
109+
}

0 commit comments

Comments
 (0)