Files
clean-architecture-frontend…/src/presentation/adapters/query/application-query.ts
T
DongHyeonka d4aa365bd9
frontend-quality-gates / merge / static checks (pull_request) Successful in 2m26s
frontend-quality-gates / merge / tests (pull_request) Failing after 15m50s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 11m10s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / checker self-tests (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
fix(query): stale 실패를 렌더 중에 계산하고 실패 진단이 원인을 남긴다
useApplicationQuery가 "데이터가 있고 마지막 조회가 실패했다"는 파생 값을
effect로 state에 복사한다. 다시 시도가 그 값을 지운 뒤 refetch해도, 조회
중에 effect가 다시 돌아 true로 되돌린다. 그래서 낡은 데이터의 다시 시도가
진행 중에도 지난 실패(stale-degraded)를 보인다(1112/01-05).

query·mutation 실패 진단은 원인을 버린다. cache의 onError가 모든 실패를
cache.operation.failed로 남기는데, ApplicationQueryError에 kind가 없어
safeErrorKind가 이름(APPLICATION_QUERY_ERROR)을 쓴다. 404, 필드 거절,
abort가 한 가지로 남는다. 예상 밖 throw는 정의 이름 대신 고정 문자열
(APPLICATION_QUERY, APPLICATION_MUTATION)을 쓴다(1112/01-04).

고른 방법: staleFailure를 query.isError && hasData && !isFetching으로 렌더
중에 계산하고 state와 effect를 지운다. 다시 시도 중은 refreshing이다.
ApplicationQueryError가 failure.kind를 kind로 싣는다. 예상 밖 throw는 query
정의 ID와 mutation 정의 ID를 쓰고, 정의가 없는 legacy mutation만 옛 이름을
둔다. 버린 대안: cache onError가 ApplicationQueryError를 아예 세지 않기
(서버 실패를 cache 진단에서 잃는다).

위험·한계: 낡은 데이터의 배경 재조회 중에도 stale 대신 refreshing을
보인다. 진단 error_kind 값이 바뀌어 그 값을 읽는 대시보드가 있으면
바꿔야 한다(템플릿 안에는 없다).

검증: tests/component/application-query-bridge.test.tsx의 새 시험 셋이
고치기 전 코드에서 실패하고 고친 뒤 통과한다(desktop, PR 본문).

Refs: 1112/01-04, 1112/01-05
2026-11-13 01:50:35 +09:00

1082 lines
37 KiB
TypeScript

import {
useCallback,
useEffect,
useMemo,
useState,
useSyncExternalStore,
} from "react";
import {
hashKey,
type QueryClient,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
deriveAsyncState,
type AsyncState,
} from "../../../application/view-models/async-state.ts";
import type { Result } from "../../../contracts/result.ts";
import {
createFailure,
isRefusedOnEveryAttempt,
normalizeUnknownFailure,
withFailureEffect,
type AppFailure,
} from "../../../contracts/errors.ts";
import type {
QueryInvalidationCoordinator,
QueryInvalidationTopic,
} from "../../../contracts/query-invalidation.ts";
import type { MutationIntent } from "../../../contracts/mutation-intent.ts";
import type { CacheScopeSnapshot } from "../../../contracts/server-state-scope.ts";
import {
admitQueryResult,
type BoundMutation,
type BoundQuery,
MUTATION_COORDINATOR_BOUNDS,
type MutationDuplicatePolicy,
} from "../../../contracts/server-state.ts";
import {
QUERY_WITHOUT_INVALIDATION_META,
runtimeIdentityToken,
} from "../../../contracts/query-keys.ts";
import { useQueryInvalidationCoordinator } from "./query-invalidation-provider.tsx";
import { useMutationIntentFactory } from "./mutation-intent-provider.tsx";
import {
createOptimisticLayerRuntime,
type OptimisticLayerLease,
} from "./optimistic-layer-runtime.ts";
export type ApplicationResult<Value> = Result<Value>;
class ApplicationQueryError extends Error {
readonly failure: AppFailure;
/**
* 1112/01-04. What the cache diagnostics record (`safeErrorKind` reads
* `kind` first): the failure's kind, not one name for every failure.
*/
readonly kind: AppFailure["kind"];
constructor(failure: AppFailure) {
super(failure.kind);
this.name = "ApplicationQueryError";
this.failure = failure;
this.kind = failure.kind;
}
}
/**
* Prefer a `BoundQuery` (`bindQuery`).
*
* The raw `{ queryKey, execute }` form is a read path that runs without a
* scope and without a measurement profile: no generation check around
* `execute`, no result-size limit, default stale and gc times, and a key that
* carries no scope fingerprint. It does not show the previous session's answer
* only because `ServerStateGenerationProvider` unmounts it on FENCED and mounts
* it again on the next generation's empty QueryClient
* (`server-state-generation-provider.test.tsx`). Outside that provider nothing
* in this hook fences it. Kept for reads only (1101/08-03): a read can be sent
* again without side effects; a raw write cannot.
*/
export function useApplicationQuery<Value>(
options:
| BoundQuery<Value>
| Readonly<{
queryKey: readonly unknown[];
execute(context: Readonly<{ signal: AbortSignal }>): Promise<
ApplicationResult<Value>
>;
enabled?: boolean;
}>,
): Readonly<{
data: Value | undefined;
state: AsyncState;
retry(): Promise<void>;
}> {
const { queryKey, execute } = options;
const enabled = "enabled" in options ? options.enabled ?? true : true;
const profile = "profile" in options ? options.profile : undefined;
const scope = "scope" in options ? options.scope : undefined;
const identity = "identity" in options ? options.identity : undefined;
const measureResult =
"measureResult" in options ? options.measureResult : undefined;
const queryDefinitionId =
"definitionId" in options ? options.definitionId : "APPLICATION_QUERY";
const invalidation =
"invalidation" in options ? options.invalidation : undefined;
useEffect(() => {
identity?.acquire();
return () => identity?.release();
}, [identity]);
const query = useQuery<Value, ApplicationQueryError>({
queryKey,
enabled,
...(invalidation === "NONE"
? { meta: QUERY_WITHOUT_INVALIDATION_META }
: {}),
retry: false,
staleTime: profile?.staleTimeMs,
gcTime: profile?.gcTimeMs,
refetchOnMount: profile?.refetchOnMount,
refetchOnWindowFocus: profile?.refetchOnFocus,
refetchOnReconnect: profile?.refetchOnReconnect,
queryFn: async ({ signal }) => {
identity?.acquire();
try {
if (scope && !scope.isCurrent()) {
throw new ApplicationQueryError(
createFailure(
"SCOPE_GENERATION_CHANGED",
queryDefinitionId,
0,
{ code: "QUERY_SCOPE_STALE" },
),
);
}
const result = await execute({ signal });
if (scope && !scope.isCurrent()) {
throw new ApplicationQueryError(
createFailure(
"SCOPE_GENERATION_CHANGED",
queryDefinitionId,
0,
{ code: "QUERY_SCOPE_CHANGED" },
),
);
}
if (result.ok) {
if (profile && measureResult) {
const admission = admitQueryResult(
measureResult,
result.value,
profile,
);
if (!admission.ok) {
throw new ApplicationQueryError(
createFailure(
"RESULT_LIMIT_EXCEEDED",
queryDefinitionId,
0,
{ code: admission.code },
),
);
}
}
return result.value;
}
if (signal.aborted) {
throw new DOMException("Query cancelled", "AbortError");
}
throw new ApplicationQueryError(result.error);
} catch (error) {
if (signal.aborted) {
throw new DOMException("Query cancelled", "AbortError");
}
if (error instanceof ApplicationQueryError) throw error;
// 1112/01-04. The definition it came from, as the other failures here.
throw new ApplicationQueryError(
normalizeUnknownFailure(error, {
operationId: queryDefinitionId,
}),
);
} finally {
identity?.release();
}
},
});
const hasData = query.data !== undefined && query.data !== null;
// 1112/01-05. Read while rendering: the data is stale because the last
// fetch failed, and no fetch runs now. A retry that is running shows as
// refreshing; copied into state by an effect, the old failure came back
// over the retry's reset.
const staleFailure = query.isError && hasData && !query.isFetching;
const retry = useCallback(async () => {
await query.refetch({ cancelRefetch: false });
}, [query]);
return Object.freeze({
data: query.data,
state: deriveAsyncState({
data: query.data,
// A disabled query is pending but idle; a paused offline first load is
// pending and still waiting, which `isLoading` would miss.
isInitialLoading: query.isPending && query.fetchStatus !== "idle",
failure:
!hasData && query.error instanceof ApplicationQueryError
? query.error.failure
: undefined,
isFetching: query.isFetching && !query.isPending,
isStale: staleFailure,
isDegraded: staleFailure,
}),
retry,
});
}
type LegacyMutationBase<Input, Value> = Readonly<{
execute(input: Input): Promise<ApplicationResult<Value>>;
duplicatePolicy?: MutationDuplicatePolicy;
invalidate?: readonly QueryInvalidationTopic[];
currentData?: unknown;
}>;
/**
* 1101/08-03. Raw mutation input: no scope, no intent, no `Idempotency-Key`,
* and `resendUnknownEffect()` resolves to `null`. `useApplicationMutation`
* rejects it; only the test harness passes it, by cast.
*/
export type LegacyMutationOptions<Input, Value> = LegacyMutationBase<Input, Value> &
(
| Readonly<{
/** Stable logical identity required to retain an unknown effect across remounts. */
definitionId: string;
optimistic?: never;
}>
| Readonly<{
definitionId?: string;
optimistic: Readonly<{
queryKey: readonly unknown[];
update(previous: unknown, input: Input): unknown;
}>;
}>
);
type ApplicationMutationController<Input, Value> = Readonly<{
state: AsyncState;
/**
* D-1. The same canonical input as an unknown-effect request is the same
* logical request: a keyed command sends it again with that request's
* key. 0929/03-03. Without a key it is not sent: the result is a
* `NOT_STARTED` `DUPLICATE_IN_FLIGHT` failure with code
* `UNKNOWN_EFFECT_PENDING` until the unknown request is reconciled.
* 1106/03-03. A `resendSafe` (IDEMPOTENT) policy sends it without a key.
*/
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
* Settles the oldest unknown effect. `NOT_APPLIED` needs evidence (an
* inspect operation or a server read); without it, resend instead.
*/
reconcileUnknownEffect(
resolution: "APPLIED" | "NOT_APPLIED",
): Promise<void>;
/**
* D-1. Sends the oldest unknown-effect request again with its original
* intent, so a keyed command carries the same `Idempotency-Key`. Resolves
* to `null` when nothing is waiting to be resent, and (0929/03-03) when
* that request has no key: the server could not tell a second one from a
* new request, so it could apply twice. An IDEMPOTENT command
* (`resendSafe`) is sent without one (1106/03-03). 1106/03-01. A resend
* that ends `NOT_APPLIED` or `NOT_STARTED` resolves to that failure and
* leaves the request unknown with its key. Success, `APPLIED_CONFIRMED`
* and a refusal every attempt gets (`isRefusedOnEveryAttempt`) settle it.
*/
resendUnknownEffect(): Promise<ApplicationResult<Value> | null>;
/**
* 0929/03-03. `resendUnknownEffect` would send: the oldest request is
* unknown, carries an idempotency key or comes from a `resendSafe`
* policy (1106/03-03), and is not being reconciled.
* `state.unknownEffectResendable` carries the same answer to `AsyncSurface`.
*/
canResendUnknownEffect: boolean;
}>;
type MutationExecution<Input> =
| Readonly<{ kind: "BOUND"; input: Input; intent: MutationIntent }>
| Readonly<{ kind: "LEGACY"; input: Input }>;
type MutationAdmission = {
sequence: number;
state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED";
readonly input: unknown;
intent: MutationIntent | null;
/**
* 1106/03-03. Sending this request again cannot apply it twice: its intent
* carries a key (KEYED) or the policy is `resendSafe` (IDEMPOTENT).
*/
resendable: boolean;
/** Held while UNKNOWN so the same input keeps the same identity token. */
identityLease: Readonly<{ release(): void }> | null;
/** `performance.now()` before which a resend waits (see RESEND_WAIT_CEILING_MS). */
resendNotBefore: number;
scope: CacheScopeSnapshot | null;
optimisticLayer: OptimisticLayerLease | null;
optimisticQueryKey: readonly unknown[] | null;
readonly invalidate: readonly QueryInvalidationTopic[];
invalidationCoordinator: QueryInvalidationCoordinator | null;
};
type UnknownEffectChannel = {
readonly key: string;
readonly registry: UnknownEffectRegistry;
readonly owner: QueryClient;
readonly scope: CacheScopeSnapshot | null;
nextSequence: number;
admissions: MutationAdmission[];
version: number;
reconciliationInFlight: boolean;
readonly listeners: Set<() => void>;
disposeScopeListener: (() => void) | null;
};
type UnknownEffectRegistry = {
readonly channels: Map<string, UnknownEffectChannel>;
activeAdmissions: number;
};
/**
* 백엔드 1101/02-01. An unknown answer may say when to ask again: the paired
* backend answers a same-key request while the first still runs with
* `409 IDEMPOTENT_IN_FLIGHT` and `Retry-After: 2`. A resend (the resend
* button, or saving the same input) before then only meets the same 409, so
* it waits, shown as pending. The wait is capped: an early resend carries the
* same key, so the server answers it again and never applies it twice.
* Same ceiling as the V3 executor's own Retry-After retries.
*/
const RESEND_WAIT_CEILING_MS = 5_000;
const LEGACY_OPTIMISTIC_SCOPE = Object.freeze({
isCurrent: () => true,
});
/**
* Takes a bound definition only (1101/08-03): the binding supplies the scope
* check, the intent and its `Idempotency-Key`, so a resend after an unknown
* result sends the same key.
*/
export function useApplicationMutation<Input, Value>(
options: BoundMutation<Input, Value>,
): ApplicationMutationController<Input, Value>;
// 1101/08-03. The raw (LEGACY) shape below is no longer a public overload. The
// runtime branch stays so `tests/helpers/legacy-application-query-harness.ts`
// keeps its assertions; reaching it takes an explicit cast. Removing the
// branch changes those tests and is a separate step.
export function useApplicationMutation<Input, Value>(
options: BoundMutation<Input, Value> | LegacyMutationOptions<Input, Value>,
): ApplicationMutationController<Input, Value> {
const queryClient = useQueryClient();
const invalidationCoordinator = useQueryInvalidationCoordinator();
const mutationIntentFactory = useMutationIntentFactory();
const invalidate = useMemo(
() => options.invalidate ?? [],
[options.invalidate],
);
const optimistic = "optimistic" in options ? options.optimistic : undefined;
const currentData = "currentData" in options ? options.currentData : undefined;
const definitionId =
"definitionId" in options
? options.definitionId ?? "LEGACY_MUTATION"
: "LEGACY_MUTATION";
// 1112/01-04. An unexpected throw names the mutation definition it came
// from; a legacy mutation without one keeps the generic name.
const failureOperationId =
"definitionId" in options && options.definitionId
? options.definitionId
: "APPLICATION_MUTATION";
const definitionVersion =
"definitionVersion" in options ? options.definitionVersion : 0;
const duplicatePolicy =
"duplicatePolicy" in options ? options.duplicatePolicy : "REJECT_WHILE_ACTIVE";
const [conflict, setConflict] = useState<AppFailure | null>(null);
const scope = "scope" in options ? options.scope : undefined;
const mutationOperationId =
"operationId" in options ? options.operationId : definitionId;
const requiresIdempotencyKey =
"requiresIdempotencyKey" in options
? options.requiresIdempotencyKey
: false;
const resendSafe = "resendSafe" in options && options.resendSafe === true;
const unknownEffectChannelKey = scope
? `bound:${scope.generation}:${scope.fingerprint}:${definitionId}:${definitionVersion}`
: `legacy:${definitionId}:${
optimistic
? hashKey(optimistic.queryKey)
: "non-optimistic"
}`;
const [acquiredUnknownEffectChannel, setAcquiredUnknownEffectChannel] =
useState<UnknownEffectChannel | null>(null);
const unknownEffectChannel =
acquiredUnknownEffectChannel?.owner === queryClient &&
acquiredUnknownEffectChannel.key === unknownEffectChannelKey &&
acquiredUnknownEffectChannel.scope === (scope ?? null)
? acquiredUnknownEffectChannel
: null;
useEffect(() => {
const acquired = acquireUnknownEffectChannel(
queryClient,
unknownEffectChannelKey,
scope,
);
setAcquiredUnknownEffectChannel(acquired);
return () => {
if (acquired) {
releaseUnknownEffectChannelIfUnused(queryClient, acquired);
}
};
}, [queryClient, scope, unknownEffectChannelKey]);
const subscribeToUnknownEffects = useCallback(
(listener: () => void) => {
if (!unknownEffectChannel) return () => {};
unknownEffectChannel.listeners.add(listener);
return () => {
unknownEffectChannel.listeners.delete(listener);
releaseUnknownEffectChannelIfUnused(
queryClient,
unknownEffectChannel,
);
};
},
[queryClient, unknownEffectChannel],
);
useSyncExternalStore(
subscribeToUnknownEffects,
() => unknownEffectChannel?.version ?? 0,
() => unknownEffectChannel?.version ?? 0,
);
const mutation = useMutation<
Value,
ApplicationQueryError,
MutationExecution<Input>
>({
retry: false,
mutationFn: async (execution) => {
const input = execution.input;
if (scope && !scope.isCurrent()) {
throw new ApplicationQueryError(
createFailure(
"SCOPE_GENERATION_CHANGED",
definitionId,
0,
{ code: "MUTATION_SCOPE_STALE", effect: "NOT_STARTED" },
),
);
}
const result =
"scope" in options
? await options.execute(input, {
signal: options.scope.signal,
intent:
execution.kind === "BOUND"
? execution.intent
: (() => {
throw new TypeError(
"Bound mutation execution requires an intent.",
);
})(),
})
: await options.execute(input);
if (scope && !scope.isCurrent()) {
const effect =
!result.ok && result.error.effect !== undefined
? result.error.effect
: "MAYBE_APPLIED";
throw new ApplicationQueryError(
createFailure(
"SCOPE_GENERATION_CHANGED",
definitionId,
0,
{ code: "MUTATION_SCOPE_CHANGED", effect },
),
);
}
if (result.ok) return result.value;
throw new ApplicationQueryError(result.error);
},
});
const submit = useCallback(
(input: Input): Promise<ApplicationResult<Value>> => {
let identity: string;
let identityLease: ReturnType<
NonNullable<typeof scope>["identities"]["intern"]
> | null = null;
try {
if (scope) {
if (!scope.isCurrent()) {
return Promise.resolve({
ok: false,
error: createFailure(
"SCOPE_GENERATION_CHANGED",
definitionId,
0,
{ code: "MUTATION_SCOPE_STALE", effect: "NOT_STARTED" },
),
});
}
identityLease = scope.identities.intern(input);
identityLease.acquire();
identity = `${scope.fingerprint}:${definitionId}:${identityLease.token}`;
} else {
identity = `${definitionId}:${runtimeIdentityToken(input)}`;
}
} catch (error) {
return Promise.resolve({
ok: false,
error: withFailureEffect(
normalizeUnknownFailure(error, {
operationId: definitionId,
}),
"NOT_STARTED",
),
});
}
const active = mutationExecutions(queryClient).get(identity) as
| RuntimeMutationExecution<Value>
| undefined;
if (active && duplicatePolicy === "JOIN_IDENTICAL") {
if (
active.joinedWaiters >=
MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent
) {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure(
"DUPLICATE_IN_FLIGHT",
definitionId,
0,
{
code: "JOIN_WAITER_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
),
});
}
active.joinedWaiters += 1;
identityLease?.release();
return active.promise;
}
if (active && duplicatePolicy === "REJECT_WHILE_ACTIVE") {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure(
"DUPLICATE_IN_FLIGHT",
definitionId,
0,
{ code: "DUPLICATE_IN_FLIGHT", effect: "NOT_STARTED" },
),
});
}
if (
!unknownEffectChannel ||
unknownEffectChannel.registry.activeAdmissions >=
MUTATION_COORDINATOR_BOUNDS.activeIntentsTotal
) {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure(
"IDENTITY_INTERN_LIMIT_EXCEEDED",
definitionId,
0,
{
code: "UNKNOWN_EFFECT_CHANNEL_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
),
});
}
// D-1. Saving the same canonical input again is the same logical
// request: it reuses the unknown admission's intent (and key).
const replayed = unknownEffectChannel.admissions.find(
(candidate) =>
candidate.state === "UNKNOWN" &&
candidate.intent?.canonicalInputIdentity === identity,
);
// 0929/03-03. Without an idempotency key the server cannot tell that
// request from this one, so saving the same input again could apply it
// twice. The unknown request is settled first (reconcileUnknownEffect),
// never repeated; a page that calls submit outside the form meets this
// too. 1106/03-03. An IDEMPOTENT command has no key but applying it
// twice gives the same result, so it is sent (`resendable`).
if (replayed && !replayed.resendable) {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure("DUPLICATE_IN_FLIGHT", definitionId, 0, {
code: "UNKNOWN_EFFECT_PENDING",
effect: "NOT_STARTED",
}),
});
}
const admission: MutationAdmission = {
sequence: unknownEffectChannel.nextSequence++,
state: "ACTIVE",
input,
intent: null,
resendable: false,
identityLease: null,
resendNotBefore: 0,
scope: scope ?? null,
optimisticLayer: null,
optimisticQueryKey: optimistic?.queryKey ?? null,
invalidate,
invalidationCoordinator: invalidationCoordinator ?? null,
};
unknownEffectChannel.admissions.push(admission);
unknownEffectChannel.registry.activeAdmissions += 1;
if (replayed) {
// The new attempt re-applies its own optimistic layer and owns the
// outcome from here.
replayed.optimisticLayer?.reconcile("NOT_APPLIED");
settleMutationAdmission(unknownEffectChannel, replayed);
}
notifyUnknownEffectChannel(unknownEffectChannel);
setConflict(null);
mutation.reset();
const holdUnknown = (retryAfterMs: number | undefined): void => {
admission.state = "UNKNOWN";
admission.resendNotBefore =
performance.now() +
Math.min(retryAfterMs ?? 0, RESEND_WAIT_CEILING_MS);
if (identityLease) {
identityLease.acquire();
admission.identityLease = identityLease;
}
notifyUnknownEffectChannel(unknownEffectChannel);
};
// 1106/03-01. A resend of an unknown request that is refused before
// the write (429, the edge's 503 RATE_LIMIT_*) or never sent shows only
// that this attempt did not apply; the first may have. The request
// stays unknown with its intent, so the next save or resend carries
// the same key, never a new one (backend http-contract.md §2). A
// refusal every attempt of the request gets (the paired backend's 400
// VALIDATION_FAILED and IDEMPOTENCY_KEY_INVALID) shows the first was
// refused too, so the request is settled and the form can take a
// corrected save (isRefusedOnEveryAttempt, D10 supplement).
const resendLeavesUnknown = (failure: AppFailure): boolean =>
replayed !== undefined &&
(!scope || scope.isCurrent()) &&
!isRefusedOnEveryAttempt(failure);
let runtimeExecution: RuntimeMutationExecution<Value> | undefined;
const pending = (async (): Promise<ApplicationResult<Value>> => {
let execution: MutationExecution<Input>;
if (scope) {
const intent =
replayed?.intent ??
mutationIntentFactory.create({
operationId: mutationOperationId,
canonicalInputIdentity: identity,
requiresIdempotencyKey,
});
admission.intent = intent;
admission.resendable =
intent.idempotencyKey !== undefined || resendSafe;
execution = Object.freeze({ kind: "BOUND", input, intent });
} else {
execution = Object.freeze({ kind: "LEGACY", input });
}
const mutationLease =
invalidate.length === 0
? null
: invalidationCoordinator?.beginMutation(invalidate);
if (invalidate.length > 0 && !mutationLease) {
throw new Error("Query invalidation coordinator is not installed.");
}
try {
let optimisticLayer: OptimisticLayerLease | null = null;
if (optimistic) {
await queryClient.cancelQueries({
queryKey: optimistic.queryKey,
exact: true,
});
optimisticLayer = optimisticLayers(queryClient).begin(
optimistic.queryKey,
input,
optimistic.update,
scope ?? LEGACY_OPTIMISTIC_SCOPE,
);
admission.optimisticLayer = optimisticLayer;
}
const resendWaitMs =
(replayed?.resendNotBefore ?? 0) - performance.now();
if (resendWaitMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, resendWaitMs);
});
}
let value: Value;
try {
value = await mutation.mutateAsync(execution);
} catch (error: unknown) {
const reportedFailure =
error instanceof ApplicationQueryError
? error.failure
: normalizeUnknownFailure(error, {
operationId: failureOperationId,
});
const failure = mutationFailureWithEffect(reportedFailure);
switch (failure.effect) {
case "NOT_STARTED":
case "NOT_APPLIED":
if (resendLeavesUnknown(failure)) {
optimisticLayer?.markUncertain();
holdUnknown(failure.retryAfterMs);
break;
}
optimisticLayer?.rollback();
if (failure.kind === "CONFLICT") setConflict(failure);
settleMutationAdmission(unknownEffectChannel, admission);
break;
case "APPLIED_CONFIRMED":
optimisticLayer?.commit();
if (!scope || scope.isCurrent()) {
try {
await invalidationCoordinator?.invalidate(invalidate);
} catch {
// A confirmed command remains committed if refresh fails.
}
}
settleMutationAdmission(unknownEffectChannel, admission);
break;
case "MAYBE_APPLIED":
optimisticLayer?.markUncertain();
if (!scope || scope.isCurrent()) {
holdUnknown(failure.retryAfterMs);
} else {
settleMutationAdmission(unknownEffectChannel, admission);
}
break;
}
return { ok: false, error: failure };
}
optimisticLayer?.commit();
try {
await invalidationCoordinator?.invalidate(invalidate);
} catch {
// Cache refresh remains best effort after the server has committed.
}
settleMutationAdmission(unknownEffectChannel, admission);
return { ok: true, value };
} finally {
try {
await mutationLease?.release();
} catch {
// A cache coordination defect cannot change the committed command.
}
}
})()
.catch((error: unknown) => {
const failure = withFailureEffect(
normalizeUnknownFailure(error, {
operationId: failureOperationId,
}),
"NOT_STARTED",
);
if (resendLeavesUnknown(failure)) {
admission.optimisticLayer?.markUncertain();
holdUnknown(undefined);
return { ok: false as const, error: failure };
}
settleMutationAdmission(unknownEffectChannel, admission);
if (failure.kind === "CONFLICT") setConflict(failure);
return { ok: false as const, error: failure };
})
.finally(() => {
identityLease?.release();
if (
runtimeExecution &&
mutationExecutions(queryClient).get(identity) === runtimeExecution
) {
mutationExecutions(queryClient).delete(identity);
}
});
if (duplicatePolicy !== "ALLOW_PARALLEL") {
runtimeExecution = { promise: pending, joinedWaiters: 0 };
mutationExecutions(queryClient).set(identity, runtimeExecution);
}
return pending;
},
[
invalidate,
invalidationCoordinator,
mutation,
optimistic,
queryClient,
definitionId,
duplicatePolicy,
failureOperationId,
mutationIntentFactory,
mutationOperationId,
requiresIdempotencyKey,
resendSafe,
scope,
unknownEffectChannel,
],
);
const resolveConflict = useCallback(async () => {
setConflict(null);
mutation.reset();
if (invalidate.length > 0 && !invalidationCoordinator) {
throw new Error("Query invalidation coordinator is not installed.");
}
await invalidationCoordinator?.invalidate(invalidate);
}, [invalidate, invalidationCoordinator, mutation]);
const reconcileUnknownEffect = useCallback(
async (resolution: "APPLIED" | "NOT_APPLIED") => {
if (
!unknownEffectChannel ||
unknownEffectChannel.reconciliationInFlight
) {
return;
}
const pending = unknownEffectChannel.admissions[0];
if (!pending || pending.state !== "UNKNOWN") return;
if (pending.scope && !pending.intent) return;
unknownEffectChannel.reconciliationInFlight = true;
pending.state = "RECONCILING";
notifyUnknownEffectChannel(unknownEffectChannel);
try {
pending.optimisticLayer?.reconcile(resolution);
if (
resolution === "APPLIED" &&
(!pending.scope || pending.scope.isCurrent())
) {
try {
await pending.invalidationCoordinator?.invalidate(
pending.invalidate,
);
} catch {
// Explicit reconciliation remains settled if refresh fails.
}
}
} finally {
if (pending.scope && !pending.scope.isCurrent()) {
removeAdmissionOptimisticQuery(queryClient, pending);
}
settleMutationAdmission(unknownEffectChannel, pending);
if (
!unknownEffectChannel.admissions.some(
(admission) => admission.state === "ACTIVE",
)
) {
mutation.reset();
}
// Keep the head intent locked through the current event turn so two
// clicks cannot consume two FIFO records when reconciliation itself
// has no asynchronous invalidation work.
await Promise.resolve();
unknownEffectChannel.reconciliationInFlight = false;
notifyUnknownEffectChannel(unknownEffectChannel);
}
},
[mutation, queryClient, unknownEffectChannel],
);
const resendUnknownEffect = useCallback(async () => {
const head = unknownEffectChannel?.admissions[0];
if (!head || !canResend(unknownEffectChannel, head)) return null;
return submit(head.input as Input);
}, [submit, unknownEffectChannel]);
const unknownEffectHead = unknownEffectChannel?.admissions[0];
const canResendUnknownEffect =
unknownEffectChannel !== null &&
unknownEffectHead !== undefined &&
canResend(unknownEffectChannel, unknownEffectHead);
return Object.freeze({
state: deriveAsyncState({
data: currentData ?? true,
isMutationPending:
mutation.isPending ||
unknownEffectHead?.state === "ACTIVE" ||
unknownEffectHead?.state === "RECONCILING",
hasMutationEffectUnknown: unknownEffectHead?.state === "UNKNOWN",
isUnknownEffectResendable: canResendUnknownEffect,
hasMutationConflict: conflict !== null,
}),
submit,
resolveConflict,
reconcileUnknownEffect,
resendUnknownEffect,
canResendUnknownEffect,
});
}
/**
* D-1 / 0929/03-03. A resend repeats the unknown request with its original
* intent. Without an idempotency key (a `NEVER` command) nothing lets the
* server recognise the repeat, so it is not offered. 1106/03-03. An
* IDEMPOTENT command (`resendSafe`) is: applying it twice gives the same
* result.
*/
function canResend(
channel: UnknownEffectChannel,
head: MutationAdmission,
): boolean {
return (
head.state === "UNKNOWN" &&
head.resendable &&
!channel.reconciliationInFlight
);
}
function mutationFailureWithEffect(failure: AppFailure): AppFailure {
switch (failure.effect) {
case "NOT_STARTED":
case "NOT_APPLIED":
case "APPLIED_CONFIRMED":
case "MAYBE_APPLIED":
return withFailureEffect(failure, failure.effect);
case "NOT_APPLICABLE":
case undefined:
return withFailureEffect(failure, "MAYBE_APPLIED");
}
}
const UNKNOWN_EFFECT_CHANNELS = new WeakMap<
object,
UnknownEffectRegistry
>();
function acquireUnknownEffectChannel(
queryClient: QueryClient,
key: string,
scope: CacheScopeSnapshot | undefined,
): UnknownEffectChannel | null {
let registry = UNKNOWN_EFFECT_CHANNELS.get(queryClient);
if (!registry) {
registry = { channels: new Map(), activeAdmissions: 0 };
UNKNOWN_EFFECT_CHANNELS.set(queryClient, registry);
}
const { channels } = registry;
const existing = channels.get(key);
if (existing) return existing.scope === (scope ?? null) ? existing : null;
if (
channels.size >= MUTATION_COORDINATOR_BOUNDS.activeDefinitionsPerRuntime
) {
return null;
}
const created: UnknownEffectChannel = {
key,
registry,
owner: queryClient,
scope: scope ?? null,
nextSequence: 1,
admissions: [],
version: 0,
reconciliationInFlight: false,
listeners: new Set(),
disposeScopeListener: null,
};
channels.set(key, created);
if (scope) {
const discardScope = () => {
for (const admission of created.admissions) {
removeAdmissionOptimisticQuery(queryClient, admission);
markMutationAdmissionSettled(created, admission);
}
created.admissions = [];
notifyUnknownEffectChannel(created);
releaseUnknownEffectChannelIfUnused(queryClient, created);
};
scope.signal.addEventListener("abort", discardScope, { once: true });
created.disposeScopeListener = () =>
scope.signal.removeEventListener("abort", discardScope);
if (scope.signal.aborted || !scope.isCurrent()) discardScope();
}
return created;
}
function releaseUnknownEffectChannelIfUnused(
queryClient: QueryClient,
channel: UnknownEffectChannel,
): void {
if (channel.admissions.length > 0 || channel.listeners.size > 0) return;
const registry = UNKNOWN_EFFECT_CHANNELS.get(queryClient);
const channels = registry?.channels;
if (channels?.get(channel.key) !== channel) return;
channel.disposeScopeListener?.();
channels.delete(channel.key);
if (channels.size === 0 && registry?.activeAdmissions === 0) {
UNKNOWN_EFFECT_CHANNELS.delete(queryClient);
}
}
function notifyUnknownEffectChannel(channel: UnknownEffectChannel): void {
channel.version += 1;
for (const listener of [...channel.listeners]) listener();
}
function settleMutationAdmission(
channel: UnknownEffectChannel,
admission: MutationAdmission,
): void {
markMutationAdmissionSettled(channel, admission);
while (channel.admissions[0]?.state === "SETTLED") {
channel.admissions.shift();
}
notifyUnknownEffectChannel(channel);
releaseUnknownEffectChannelIfUnused(channel.owner, channel);
}
function markMutationAdmissionSettled(
channel: UnknownEffectChannel,
admission: MutationAdmission,
): void {
if (admission.state === "SETTLED") return;
admission.state = "SETTLED";
admission.identityLease?.release();
admission.identityLease = null;
channel.registry.activeAdmissions = Math.max(
0,
channel.registry.activeAdmissions - 1,
);
}
function removeAdmissionOptimisticQuery(
queryClient: QueryClient,
admission: MutationAdmission,
): void {
if (!admission.optimisticQueryKey) return;
queryClient.removeQueries({
queryKey: admission.optimisticQueryKey,
exact: true,
});
}
type RuntimeMutationExecution<Value = unknown> = {
promise: Promise<ApplicationResult<Value>>;
joinedWaiters: number;
};
const RUNTIME_MUTATION_EXECUTIONS = new WeakMap<
object,
Map<string, RuntimeMutationExecution>
>();
function mutationExecutions(
owner: object,
): Map<string, RuntimeMutationExecution> {
const existing = RUNTIME_MUTATION_EXECUTIONS.get(owner);
if (existing) return existing;
const created = new Map<string, RuntimeMutationExecution>();
RUNTIME_MUTATION_EXECUTIONS.set(owner, created);
return created;
}
const OPTIMISTIC_LAYER_RUNTIMES = new WeakMap<
object,
ReturnType<typeof createOptimisticLayerRuntime>
>();
function optimisticLayers(
queryClient: Parameters<typeof createOptimisticLayerRuntime>[0],
): ReturnType<typeof createOptimisticLayerRuntime> {
const existing = OPTIMISTIC_LAYER_RUNTIMES.get(queryClient);
if (existing) return existing;
const created = createOptimisticLayerRuntime(queryClient);
OPTIMISTIC_LAYER_RUNTIMES.set(queryClient, created);
return created;
}