Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/37768-closed-state-refusal-sentences.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/spec': patch
'@objectstack/objectql': patch
'@objectstack/service-storage': patch
---

feat(spec,objectql): the closed-state refusal's own sentences, in every locale (ADR-0162 D8)

Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed)
Metadata-protocol: none

A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog.

- **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.<key>` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines".
- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when a registered security service cannot be resolved. With no security service registered there is no field-level security, and the title is named. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value.
- **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`.
- **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change.
365 changes: 344 additions & 21 deletions packages/objectql/src/closed-state-lock.ts

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions packages/objectql/src/engine-cascade-planning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ export interface CascadePlanningHost {
/** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */
buildDriverOptions: ObjectQLClass['buildDriverOptions'];
resolveEnginePosture: ObjectQLClass['resolveEnginePosture'];
/** [ADR-0162 D8] The engine, whose security-service slot answers whether the caller is served the root's title. */
readonly facade: ObjectQLClass;
/** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */
validationMessageContext: ObjectQLClass['validationMessageContext'];
getDriver: ObjectQLClass['getDriver'];
isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull'];
readonly logger: ObjectQLClass['logger'];
Expand Down Expand Up @@ -536,7 +540,7 @@ export class CascadePlanningFacet {
* (formula values, file references, hooks), so they are not the values a
* restore must write back.
*/
static async cascadeDeleteRelations(this: Pick<CascadePlanningHost, '_registry' | 'buildDriverOptions' | 'cascadeDeleteSets' | 'collectCascadeDeleteSet' | 'getDriver' | 'refuseRestrictsInsideOwnCascade' | 'resolveEnginePosture' | 'resolveObjectName' | 'walkReferencingRelations'>, object: string, ids: ReadonlyArray<string | number>, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise<void>): Promise<void> {
static async cascadeDeleteRelations(this: Pick<CascadePlanningHost, '_registry' | 'buildDriverOptions' | 'cascadeDeleteSets' | 'collectCascadeDeleteSet' | 'facade' | 'getDriver' | 'logger' | 'refuseRestrictsInsideOwnCascade' | 'resolveEnginePosture' | 'resolveObjectName' | 'validationMessageContext' | 'walkReferencingRelations'>, object: string, ids: ReadonlyArray<string | number>, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise<void>, named: ReadonlyArray<string | number> = []): Promise<void> {
const roots: Array<string | number> = [];
const seen = new Set<string>();
for (const id of ids) {
Expand Down Expand Up @@ -583,7 +587,9 @@ export class CascadePlanningFacet {
// point: after the caller's gates on the record it asked to delete and
// before the first row is removed, never leg by leg. A member that is
// closed, or is a line of a closed record, refuses the delete whole.
await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context);
// [D8] The refusal's title form reads the ids the delete NAMED (`named`),
// never the set planned so far.
await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, named);
if (onCollected) await onCollected(cascadeSet);
await this.cascadeDeleteSets.run(cascadeSet, () =>
this.walkReferencingRelations(object, fresh, context, objects, cascadeSet),
Expand Down
6 changes: 4 additions & 2 deletions packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ export interface DeleteAndAggregateHost {
expandSearchOnOptions: ObjectQLClass['expandSearchOnOptions'];
/** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */
readonly facade: ObjectQLClass;
/** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */
validationMessageContext: ObjectQLClass['validationMessageContext'];
getDriver: ObjectQLClass['getDriver'];
getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors'];
hasHooksFor: ObjectQLClass['hasHooksFor'];
Expand Down Expand Up @@ -164,7 +166,7 @@ export interface DeleteAndAggregateHost {
/** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
export class DeleteAndAggregateFacet {
/** The body of `ObjectQL#delete`; the method's docblock there is its contract. */
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'cascadeIssuedDeletes' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'masterDetailHeadersCallerReads' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveEnginePosture' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'cascadeIssuedDeletes' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'masterDetailHeadersCallerReads' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveEnginePosture' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'validationMessageContext' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
object = this.resolveObjectName(object);
// [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
Expand Down Expand Up @@ -713,7 +715,7 @@ export class DeleteAndAggregateFacet {
let cascadeChildVanished = false;
const runByIdDelete = async (writeContext?: ExecutionContext) => {
const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent);
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected)
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected, [hookContext.input.id as string | number])
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
// [ADR-0131 D9] The entry's organization, when neither the record
// nor the context names one, is the engine's own system-insert
Expand Down
8 changes: 4 additions & 4 deletions packages/objectql/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4927,10 +4927,10 @@ export class ObjectQL implements IObjectQLEngine {
ids: ReadonlyArray<string | number>,
context?: ExecutionContext,
depth = 0,
onCollected?: (set: CascadeDeleteSet) => Promise<void>,
onCollected?: (set: CascadeDeleteSet) => Promise<void>, named?: ReadonlyArray<string | number>, // [ADR-0162 D8] the ids the delete named
): Promise<void> {
// [#29986 codemod] The body moved to `engine-cascade-planning.ts`, its docblock with it (see `CascadePlanningHost`).
return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected);
return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected, named);
}

/**
Expand Down Expand Up @@ -5826,7 +5826,7 @@ export class ObjectQL implements IObjectQLEngine {
refuseRestrictsInsideOwnCascade: (...a) => engine.refuseRestrictsInsideOwnCascade(...a),
resolveObjectName: (...a) => engine.resolveObjectName(...a),
update: (...a) => engine.update(...a),
walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D6]
walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), facade: engine, validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D6, D8]
}));
compatibilitySectionHost.install((engine) => ({
get _registry() { return engine._registry; },
Expand Down Expand Up @@ -5899,7 +5899,7 @@ export class ObjectQL implements IObjectQLEngine {
transaction: (...a) => engine.transaction(...a),
triggerHooks: (...a) => engine.triggerHooks(...a),
warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a),
withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10]
withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D8, D10]
}));
findHost.install((engine) => ({
get _registry() { return engine._registry; },
Expand Down
43 changes: 42 additions & 1 deletion packages/objectql/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts';
import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol';
import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core';
import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol';
import { Plugin, PluginContext } from '@objectstack/core';
import { Plugin, PluginContext, isServiceNotRegisteredError } from '@objectstack/core';
import { SECURITY_SERVICE_REGISTERED_SLOT } from './closed-state-lock.js';
import { resolveArtifactPackageEntries, artifactPackageId, declaredDependencyIds, readDeploymentOrgScopingEntitlement } from '@objectstack/core';
// [ADR-0130 D4] The residual rule's decision half — which top-level items of a
// multi-package stack no body declares, and the id they take. See
Expand Down Expand Up @@ -561,6 +562,40 @@ export const OBJECTQL_DRIVERS_READY_HOOK = 'objectql:drivers-ready';
*/
export const OBJECTQL_SCHEMA_SYNCED_HOOK = 'objectql:schema-synced';

/**
* [ADR-0162 D8] Whether a `security` service is registered on the plugin's
* kernel, read without building one: `false` only when nothing is registered
* under the name, `true` for every other answer (the answer that names no
* title in a closed-state refusal).
* - The sync accessor returns it, or the context's service map holds the
* name: registered.
* - The sync accessor refuses a service registered as a factory and not yet
* built with "is async" (the message the kernel keeps verbatim for callers
* that match on it): registered, and the probe does not build it.
* - Otherwise the kernel's async accessor draws the line with the branded
* "never registered" rejection (`isServiceNotRegisteredError`), given
* before anything is built; any other answer is registered.
* - A host with no async accessor (`LiteKernel`) has no factories, so "not
* registered" is the only fault its sync accessor reports.
*/
async function securityServiceRegistered(ctx: PluginContext): Promise<boolean> {
try {
ctx.getService<unknown>('security');
return true;
} catch (err) {
if (err instanceof Error && err.message.includes('is async')) return true;
}
if (ctx.getServices().has('security')) return true;
const kernel = ctx.getKernel?.() as { getServiceAsync?: <S>(name: string) => Promise<S> } | undefined;
if (typeof kernel?.getServiceAsync !== 'function') return false;
try {
await kernel.getServiceAsync<unknown>('security');
return true;
} catch (err) {
return !isServiceNotRegisteredError(err);
}
}

export class ObjectQLPlugin implements Plugin {
name = 'com.objectstack.engine.objectql';
type = 'objectql' as const;
Expand Down Expand Up @@ -923,6 +958,12 @@ export class ObjectQLPlugin implements Plugin {
// `$in: []` (fail closed); a throw — the in-repo kernels' answer for a
// name nothing registered — is one of them.
(this.ql as unknown as Record<symbol, unknown>)[SECURITY_SERVICE_SOURCE_SLOT] = () => ctx.getService('security');
// [ADR-0162 D8] Beside the source, a probe that answers whether a
// `security` service is registered at all (SECURITY_SERVICE_REGISTERED_SLOT).
// Only the closed-state refusal's title rule reads it, and only when the
// source above throws; it builds no service, so every other reader of the
// source answers as before.
(this.ql as unknown as Record<symbol, unknown>)[SECURITY_SERVICE_REGISTERED_SLOT] = () => securityServiceRegistered(ctx);
// [ADR-0142 D5] The assignment seam reads the ownership-queue service the
// same way: a source, resolved at use. ⛔ `ownership-queue`, never the job
// queue's `queue`.
Expand Down
Loading
Loading