Standardize Camino query references and retire live field sidecars

This commit is contained in:
Timothy J. Aveni
2026-09-22 15:41:27 -07:00
parent 152f58a3c6
commit eba85ba158
28 changed files with 88 additions and 217 deletions
+1 -4
View File
@@ -76,13 +76,10 @@ export function generatePortableClientBindings(
const operations = query.operations.map(
(key) => plan.definition.operations.find((operation) => operation.key === key)!,
);
const live = (selections: readonly QuerySelection[]): boolean =>
selections.some((selection) => !!selection.liveSelectionId || live(selection.selection));
if (
operations.some(
(operation) => operation.execution.kind !== "snapshot" || !operation.execution.targets.includes("server"),
) ||
live(query.query.checked.selection)
)
) {
unavailable.push({ key: query.id, reason: "QUERY_NOT_SNAPSHOT_PROJECTION" });
continue;
+1 -19
View File
@@ -1,6 +1,5 @@
import type { BindingSchema } from "./index.js";
import type { ValueType } from "../capability-model/types.js";
import { queryPresentation } from "../query/presentation.js";
/** Browser projection of the SAME checked RPC types, not a second props schema. */
export function generateReactBindings(
@@ -131,25 +130,9 @@ export function generateReactBindings(
return type(value);
};
const queries = pkg.checkedQueries ?? [];
const presentedType = (
value: ValueType,
fields: ReturnType<typeof queryPresentation>,
path: string[] = [],
): string => {
const field = fields.find((field) => JSON.stringify(field.path) === JSON.stringify(path));
if (field)
return `${field.conditions.length ? "(" : ""}${field.setOperationId ? "WritableQueryField" : "QueryField"}<${type(field.valueType)}>${field.conditions.length ? " | null)" : ""}`;
if (value.kind === "optional") return `(${presentedType(value.value, fields, path)} | null)`;
if (value.kind === "list") return `Array<${presentedType(value.value, fields, [...path, "*"])}>`;
if (value.kind === "record")
return `{${Object.entries(value.fields)
.map(([key, child]) => `${q(key)}: ${presentedType(child, fields, [...path, key])}`)
.join(";")}}`;
return queryType(value);
};
const queryCode =
`export type QueryVariables = {${queries.map((query) => `${q(query.declaration.displayName)}: ${queryType(query.variables)}`).join(";")}};\n` +
`export type QueryResults = {${queries.map((query) => `${q(query.declaration.displayName)}: ${presentedType(query.output, queryPresentation(query, schema.interfaces))}`).join(";")}};\n` +
`export type QueryResults = {${queries.map((query) => `${q(query.declaration.displayName)}: ${queryType(query.output)}`).join(";")}};\n` +
`export const queries: {${queries.map((query) => `${q(query.declaration.displayName)}: QueryDescriptor<QueryVariables[${q(query.declaration.displayName)}], QueryResults[${q(query.declaration.displayName)}], ${q(query.declaration.root.kind)}>`).join(";")}} = ${JSON.stringify(
Object.fromEntries(
queries.map((query) => [
@@ -160,7 +143,6 @@ export function generateReactBindings(
root: query.declaration.root,
variables: query.variables,
output: query.output,
liveFields: queryPresentation(query, schema.interfaces),
watch: query.declaration.watch,
},
]),
+2 -2
View File
@@ -24,7 +24,7 @@ export function validateControllers(
objects = selected(root?.selection, "objects"),
entries = selected(objects?.selection, "entries"),
node = selected(entries?.selection, "node"),
qx = selected(node?.selection, "_qx"),
qx = selected(node?.selection, "_camino"),
ref = selected(qx?.selection, "ref");
const all = objects?.arguments.all;
if (
@@ -44,7 +44,7 @@ export function validateControllers(
)
fail(
`${path}.registry`,
"Controller registry requires a native/portable workspace query over its subject, no variables, and root.objects(all: 1..64).entries.node._qx.ref without aliases or conditional selections",
"Controller registry requires a native/portable workspace query over its subject, no variables, and root.objects(all: 1..64).entries.node._camino.ref without aliases or conditional selections",
);
}
const iface = interfaces.find((i) => i.revisionId === controller.subject && !i.template);
+11 -29
View File
@@ -87,6 +87,16 @@ export async function compileQuery(
definitions.push(...document.definitions);
}
const document: DocumentNode = { kind: "Document" as DocumentNode["kind"], definitions };
visit(document, {
Directive(node) {
if (node.name.value === "live")
fail(
"QUERY_RETIRED_DIRECTIVE",
"@live is retired. Observations watch ordinary query values; use checked operations for mutations.",
node,
);
},
});
const generated = querySchema(declaration, interfaces, document);
const operations = definitions.filter((entry) => entry.kind === "OperationDefinition");
if (
@@ -201,16 +211,7 @@ export async function compileQuery(
Field(node) {
const parent = info.getParentType();
const contract = parent && generated.byName.get(parent.name);
if (node.directives?.some((directive) => directive.name.value === "live")) {
const member = contract?.members.find((entry) => entry.displayName === node.name.value);
if (!member || member.kind !== "value" || member.queryRead?.execution !== "native")
fail(
"QUERY_LIVE_UNSUPPORTED",
"@live requires a direct native-queryable value field, not RPC enrichment or a synthetic result",
node,
);
}
if (!contract || node.name.value === "_qx") return;
if (!contract || node.name.value === "_camino") return;
mark(contract.revisionId, node.name.value, "select", node);
const member = contract.members.find((entry) => entry.displayName === node.name.value)!;
if (member.kind !== "relationship" || (member.cardinality !== "many" && member.cardinality !== "many-unique"))
@@ -425,13 +426,6 @@ export async function compileQuery(
{
name: node.name.value,
key: node.alias?.value ?? node.name.value,
...(node.directives?.some((directive) => directive.name.value === "live")
? {
liveSelectionId: createHash("sha256")
.update(JSON.stringify([node.loc?.source.name, node.loc?.start, contract?.revisionId, member?.id]))
.digest("hex"),
}
: {}),
...(member && contract ? { interfaceRevisionId: contract.revisionId, memberId: member.id } : {}),
...(member?.kind === "relationship" ? { targetInterfaceRevisionId: generated.target(member) } : {}),
conditions: [...inherited, ...conditions(node.directives)],
@@ -447,18 +441,6 @@ export async function compileQuery(
const normalized = print(document),
schema = printSchema(generated.schema);
const selections = selection(operations[0]!.selectionSet, generated.schema.getQueryType()!);
const checkPresentation = (entries: QuerySelection[]) => {
for (const key of new Set(entries.map((entry) => entry.key))) {
const siblings = entries.filter((entry) => entry.key === key);
if (siblings.some((entry) => entry.liveSelectionId) && siblings.some((entry) => !entry.liveSelectionId))
throw new QueryCompileError(
"QUERY_LIVE_CONFLICT",
`${key} mixes live and plain selections; use separate aliases`,
);
checkPresentation(siblings.flatMap((entry) => entry.selection));
}
};
checkPresentation(selections);
const definitionDigest = createHash("sha256")
.update(
canonicalJson({
-58
View File
@@ -1,58 +0,0 @@
import type { InterfaceRevision, ValueType } from "../capability-model/types.js";
import type { CheckedQuery, QuerySelection } from "./types.js";
/** Browser presentation is separate from the portable query value contract. */
export function queryPresentation(query: CheckedQuery, interfaces: readonly InterfaceRevision[]) {
const result: {
path: string[];
selectionId: string;
interfaceRevisionId: string;
getOperationId: string;
setOperationId?: string;
watchOperationId?: string;
inputKind: "value" | "fields";
valueType: ValueType;
conditions: (QuerySelection["conditions"][number] & { defaultValue?: boolean })[];
}[] = [];
const visit = (type: ValueType, selections: QuerySelection[], path: string[]) => {
if (type.kind === "optional") return visit(type.value, selections, path);
if (type.kind === "list") return visit(type.value, selections, [...path, "*"]);
if (type.kind !== "record") return;
for (const [name, field] of Object.entries(type.fields)) {
const matches = selections.filter((entry) => entry.key === name);
if (matches.some((entry) => entry.liveSelectionId) && matches.some((entry) => !entry.liveSelectionId))
throw new Error(`QUERY_LIVE_CONFLICT: ${[...path, name].join(".")} mixes live and plain selections`);
for (const entry of matches) {
if (entry.liveSelectionId) {
const iface = interfaces.find((iface) => iface.revisionId === entry.interfaceRevisionId)!;
const member = iface.members.find((member) => member.id === entry.memberId)!;
if (member.kind !== "value") throw new Error("QUERY_LIVE_UNSUPPORTED");
const get = member.operations.find((op) => op.displayName === "get")!;
const set = member.operations.find((op) => op.displayName === "set");
result.push({
path: [...path, name],
selectionId: entry.liveSelectionId,
interfaceRevisionId: iface.revisionId,
getOperationId: get.id,
setOperationId: set?.id,
watchOperationId: member.operations.find((op) => op.displayName === "watch-start")?.id,
inputKind: set?.inputType.kind === "record" ? "fields" : "value",
valueType: get.outputType,
conditions: entry.conditions.map((condition) => {
const fallback =
condition.value.kind === "variable" ? query.variableDefaults[condition.value.name] : undefined;
return {
...condition,
...(fallback?.kind === "literal" && typeof fallback.value === "boolean"
? { defaultValue: fallback.value }
: {}),
};
}),
});
} else visit(field, entry.selection, [...path, name]);
}
}
};
visit(query.output, query.selection, []);
return result;
}
+6 -5
View File
@@ -94,7 +94,8 @@ export function relationalCompiler(
if (!prefix(base, path)) return false;
// Object identity does not determine which incoming membership carried it.
return (
last === "entry" || !(path[base.length] === "_qx" && ["entry", "mapKey"].includes(path[base.length + 1] ?? ""))
last === "entry" ||
!(path[base.length] === "_camino" && ["entry", "mapKey"].includes(path[base.length + 1] ?? ""))
);
});
if (!ok)
@@ -153,7 +154,7 @@ export function relationalCompiler(
available?: Availability,
): QueryExpression => {
requireAvailable(names, available, node);
const meta = names.at(-2) === "_qx";
const meta = names.at(-2) === "_camino";
let fieldIndex = names.length - 1;
if (!meta) {
let cursor = root;
@@ -334,10 +335,10 @@ export function relationalCompiler(
children.push({ kind: "not", child: { kind: "and", children: children.splice(before) } });
} else if (current.kind === "pair" && (name === "source" || name === "target"))
visit(current[name], field.value, [...base, name]);
else if (name === "_qx") {
else if (name === "_camino") {
for (const meta of pairs(field.value)) {
if (meta.name.value !== "relations") {
const expr = expression(row, [...base, "_qx", meta.name.value], ["predicate"], meta, available);
const expr = expression(row, [...base, "_camino", meta.name.value], ["predicate"], meta, available);
children.push(
...(comparisons(meta.value, (operator, value) => ({
kind: "compare",
@@ -531,7 +532,7 @@ export function relationalCompiler(
expression: { ...k.expression, path: [{ kind: "source" as const }, ...k.expression.path] },
})),
{
path: ["target", "_qx", "entry"],
path: ["target", "_camino", "entry"],
expression: {
path: [{ kind: "target" as const }],
leaf: { kind: "entry" as const },
+7 -5
View File
@@ -205,7 +205,9 @@ export function relationalSchema(env: RelationalSchemaEnvironment, document?: Do
metadata[name] = { type: !operator && nullable ? t : new GraphQLNonNull(t) };
}
if (Object.keys(metadata).length)
result._qx = { type: new GraphQLNonNull(out("ColumnsMeta", row, () => metadata, `${operator}:${nullable}`)) };
result._camino = {
type: new GraphQLNonNull(out("ColumnsMeta", row, () => metadata, `${operator}:${nullable}`)),
};
// A type may have no matching scalar at this node; a private schema sentinel
// keeps it valid while compiler validation forbids selecting that sentinel.
if (!Object.keys(result).length) result._unavailable = { type: GraphQLBoolean };
@@ -233,7 +235,7 @@ export function relationalSchema(env: RelationalSchemaEnvironment, document?: Do
else if (queryKeyType(field.type)) result[name] = { type: GraphQLBoolean };
}
const meta = Object.fromEntries([...leafFields(row)].map(([name]) => [name, { type: GraphQLBoolean }]));
if (Object.keys(meta).length) result._qx = { type: inp("KeyMeta", row, () => meta) };
if (Object.keys(meta).length) result._camino = { type: inp("KeyMeta", row, () => meta) };
return result;
});
const comparisons = (
@@ -266,7 +268,7 @@ export function relationalSchema(env: RelationalSchemaEnvironment, document?: Do
if (!operator || operator === "countPresent")
meta[name] = { type: ordering ? env.direction : compare(operator ? aggregateType(operator, type) : type) };
if (Object.keys(meta).length)
result._qx = { type: inp("ExpressionMeta", row, () => meta, `${operator}:${ordering}`) };
result._camino = { type: inp("ExpressionMeta", row, () => meta, `${operator}:${ordering}`) };
if (!Object.keys(result).length) result._unavailable = { type: GraphQLBoolean };
return result;
},
@@ -306,7 +308,7 @@ export function relationalSchema(env: RelationalSchemaEnvironment, document?: Do
if (field.kind === "leaf" && !comparableValue(field.type)) continue;
result[name] = { type: field.kind === "row" ? where(field.row) : compare(field.type) };
}
result._qx = {
result._camino = {
type: inp("WhereMeta", row, () => {
const meta: GraphQLInputFieldConfigMap = {};
for (const [name, type] of leafFields(row)) meta[name] = { type: compare(type) };
@@ -397,7 +399,7 @@ export function relationalSchema(env: RelationalSchemaEnvironment, document?: Do
const discoverObject = (row: QueryRow, set: SelectionSetNode) => {
for (const node of selections(set))
if (node.selectionSet) {
if (node.name.value === "_qx") {
if (node.name.value === "_camino") {
for (const meta of selections(node.selectionSet))
if (meta.name.value === "relations" && meta.selectionSet)
for (const edge of selections(meta.selectionSet)) {
+2 -4
View File
@@ -11,8 +11,6 @@ import {
GraphQLList,
GraphQLNonNull,
GraphQLSchema,
GraphQLDirective,
DirectiveLocation,
specifiedDirectives,
type GraphQLOutputType,
type GraphQLInputType,
@@ -198,7 +196,7 @@ export function querySchema(
...(helpers ? { relations: { type: new GraphQLNonNull(helpers) } } : {}),
},
});
const fields: GraphQLFieldConfigMap<unknown, unknown> = { _qx: { type: new GraphQLNonNull(metadata) } };
const fields: GraphQLFieldConfigMap<unknown, unknown> = { _camino: { type: new GraphQLNonNull(metadata) } };
for (const member of contract(id).members) {
if (member.kind === "operation" || member.kind === "module" || !member.queryRead) continue;
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(member.displayName) || member.displayName.startsWith("_"))
@@ -258,7 +256,7 @@ export function querySchema(
return result;
};
const schema = new GraphQLSchema({
directives: [...specifiedDirectives, new GraphQLDirective({ name: "live", locations: [DirectiveLocation.FIELD] })],
directives: specifiedDirectives,
query: new GraphQLObjectType({
name: "QxQuery",
fields: { root: { type: new GraphQLNonNull(object(root.interface)) } },
-1
View File
@@ -102,7 +102,6 @@ export type QueryArgument =
| { kind: "list"; values: QueryArgument[] }
| { kind: "object"; fields: Record<string, QueryArgument> };
export interface QuerySelection {
liveSelectionId?: string;
name: string;
key: string;
interfaceRevisionId?: InterfaceRevisionId;