Virtual objects — rows from your server, shown in any view
Serve an object's rows from your own server through a plugin driver, so grids, gantts, forms, permissions, formulas and hooks work over data ObjectStack never stores.
A virtual object is an ordinary object whose rows your own code answers on every
read. ObjectStack stores none of them: a plugin driver — a class implementing the
driver contract, published by a plugin — receives each query and asks the system that
really holds the data. Every view, form, permission set, formula and hook works on it the
way it works on a stored object, and it takes no new metadata at all: a datasource with
schemaMode: 'external' and an object bound to it, the same two declarations
federation uses. The difference is who
answers: there, a built-in SQL driver reads a remote database; here, your driver reads
whatever you put behind it — a REST API, a planning engine, a device gateway.
Everything on this page is what the platform's reference test boots and asserts
(packages/runtime/src/plugin-driver-external-object.spike.test.ts, with the gantt half
in ui/packages/plugin-gantt/src/ObjectGantt.pluginDriverTree.test.tsx). Read them when
this page and the runtime seem to disagree.
Which way in: OData, a plugin driver, or a real object
Three rules, checked in order:
- Slow-changing reference data: a real object, fed by a sync. Codes, catalogues and registries that change monthly are better copied. Declare a real object and fill it with a scheduled pull.
- The remote exposes OData v4: an OData datasource. SAP S/4HANA, Dynamics 365, Dataverse and other CSDL 4.0 services are served by the shipped OData driver. You declare a datasource and one object per entity set, and write no driver code (OData datasources).
- No OData, rows computed on request, or a private API: a plugin driver of your own, which is what the rest of this page builds.
The first rule is the question of whether to copy at all. Make the object virtual when a copy would be wrong, and real when a copy is merely convenient:
| The data is… | Choose | Why |
|---|---|---|
| Computed by the remote when asked — a plan, a price, an availability | virtual | a stored copy is yesterday's answer to today's question |
| Must not land — a system of record you may not copy (residency, licence, audit, personal data) | virtual | no copy exists to leak, drift or fall out of retention |
| Real-time — state that changes faster than any sync could follow | virtual | the row is read at the moment the page is drawn |
| Slow-changing reference data — codes, catalogues, registries that change monthly | a real object fed by a scheduled pull | indexes, every query operator, search, reports, and pages that keep working while the remote is down |
If the remote is a SQL database you can reach, you need no driver of your own — use a built-in one through External datasources.
Salesforce takes a driver of its own. Salesforce can read other systems' OData services (Salesforce Connect), but it does not publish its own records as an OData service, so the OData datasource cannot read it. Serve Salesforce objects from a plugin driver over its REST API, built to the contract on this page.
A virtual object pays for its freshness on every request: each list read is a round trip to the remote, and a read can match at most 1000 rows by default, 10,000 at most (the row cap). That is the trade the table above decides.
The recipe
The worked example is a port's berth plan: the terminal's scheduling system owns the plan and its dependencies, planners reschedule slots on a gantt, a locked plan cannot be moved, and only a slot's own planner may move it. Five pieces, the first two code and the rest metadata.
1. The driver
The driver translates the engine's query into a request the remote understands, and refuses what it cannot translate. The transport — your HTTP client — is passed in, which is also what makes the driver testable (below).
import type { DriverQuery, IDataDriver } from '@objectstack/spec/contracts';
type Row = Record<string, unknown>;
/** One condition your remote API can run. Grow it only as far as the API does. */
export type RemoteCondition = { field: string; op: 'eq' | 'ne' | 'in'; value: unknown };
export interface RemoteListRequest {
filter: RemoteCondition[];
sort: Array<{ field: string; desc: boolean }>;
limit?: number;
offset?: number;
fields?: string[];
}
/** The remote system, as your driver sees it. Back it with your HTTP client. */
export interface PortScheduleTransport {
list(resource: string, request: RemoteListRequest): Promise<Row[]>;
count(resource: string, filter: RemoteCondition[]): Promise<number>;
patch(resource: string, id: string, changes: Row): Promise<Row | null>;
}
/**
* Per object: the remote resource, and the columns the remote really has.
* The driver is handed the OBJECT name, never `external.remoteName`.
*/
const RESOURCES: Record<string, { resource: string; columns: ReadonlySet<string>; writable: ReadonlySet<string> }> = {
berth_slot: {
resource: 'slots',
columns: new Set(['id', 'name', 'parent', 'start_date', 'end_date', 'depends_on', 'planner', 'plan_locked', 'archived', 'plan_note']),
writable: new Set(['start_date', 'end_date', 'plan_note']),
},
};
const OPERATORS: Record<string, RemoteCondition['op']> = { $eq: 'eq', $ne: 'ne', $in: 'in' };
/** A refusal of this request, by name. `status: 400` is what the engine reads to tell it from an outage. */
function refuse(what: string): never {
throw Object.assign(new Error(`port_schedule driver: the remote cannot run ${what}`), { status: 400 });
}
function resourceOf(object: string) {
return RESOURCES[object] ?? refuse(`object '${object}' (no remote resource is mapped)`);
}
/** Translate the whole `where`, or refuse. Never drop a condition. */
function toFilter(object: string, where: unknown, out: RemoteCondition[] = []): RemoteCondition[] {
if (where === undefined || where === null) return out;
if (typeof where !== 'object' || Array.isArray(where)) refuse(`a where of shape ${JSON.stringify(where)}`);
const { columns } = resourceOf(object);
for (const [key, cond] of Object.entries(where as Row)) {
if (key === '$and') {
for (const part of cond as unknown[]) toFilter(object, part, out);
continue;
}
if (key.startsWith('$')) refuse(`the combinator ${key}`);
if (!columns.has(key)) refuse(`a filter on '${key}', which ${object} does not carry`);
if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) {
for (const [op, value] of Object.entries(cond as Row)) {
out.push({ field: key, op: OPERATORS[op] ?? refuse(`the operator ${op} on '${key}'`), value });
}
continue;
}
out.push({ field: key, op: 'eq', value: cond });
}
return out;
}
function toListRequest(object: string, query: DriverQuery): RemoteListRequest {
const request: RemoteListRequest = {
filter: toFilter(object, query.where),
sort: (query.orderBy ?? []).map((s) => ({ field: s.field, desc: s.order === 'desc' })),
};
if (typeof query.limit === 'number') request.limit = query.limit;
if (typeof query.offset === 'number') request.offset = query.offset;
if (Array.isArray(query.fields)) request.fields = ['id', ...query.fields.filter((f): f is string => typeof f === 'string' && f !== 'id')];
return request;
}
const notSupported = (what: string) => async (): Promise<never> => refuse(what);
export function createPortScheduleDriver(transport: PortScheduleTransport): IDataDriver {
return {
name: 'port_schedule', // = the datasource name; the plugin registers `driver.port_schedule`
version: '1.0.0',
supports: { transactionsUnsupported: true },
async connect() { /* open a session, check the remote answers; throw to refuse the boot */ },
async disconnect() {},
async checkHealth() { return true; },
async find(object, query) {
return transport.list(resourceOf(object).resource, toListRequest(object, query));
},
async findOne(object, query) {
const rows = await transport.list(resourceOf(object).resource, { ...toListRequest(object, query), limit: 1 });
return rows[0] ?? null;
},
async count(object, query) {
return transport.count(resourceOf(object).resource, toFilter(object, query?.where));
},
async update(object, id, data) {
const { resource, writable } = resourceOf(object);
// The engine adds `id`, `updated_at` and `updated_by` to the patch; send
// only what the remote owns.
const changes = Object.fromEntries(Object.entries(data).filter(([k]) => writable.has(k)));
return transport.patch(resource, String(id), changes);
},
// Not offered by this remote: refuse by name, never pretend.
execute: notSupported('execute'),
create: notSupported('create'),
upsert: notSupported('upsert'),
delete: notSupported('delete'),
bulkCreate: notSupported('bulkCreate'),
bulkUpdate: notSupported('bulkUpdate'),
bulkDelete: notSupported('bulkDelete'),
beginTransaction: notSupported('beginTransaction'),
commit: notSupported('commit'),
rollback: notSupported('rollback'),
dropTable: notSupported('dropTable'),
async syncSchema() { /* external: the platform runs no DDL; nothing to do */ },
};
}A driver cannot opt out of correctness, only of performance. The engine does not trust a plugin driver to have applied the query: it re-applies it (below). The rules the driver keeps:
- Never return fewer rows than match. The engine filters, sorts and pages the rows
your driver returns, so extra rows cost only transfer, but a row your driver leaves out
is lost. When you cannot translate part of a
where, send the remote a WIDER filter, never a narrower one: drop an untranslatable member of a top-level$and(or the wholewhere), and drop a whole$oror$notthat contains one. ⛔ Dropping one branch of an$ornarrows the result. The skeleton above takes the stricter road and refuses instead, which is also safe. - Fail when the remote fails. Throw; ⛔ never return an empty array, which reads
exactly like "no rows match". What the caller sees depends on the
status(orstatusCode) on the error you throw:- A read refused for the request's own sake (400, 404 or 422), which is what
refuse()above throws, answers400. The code isINVALID_QUERY, or the code you set on the error when it is a registered one (INVALID_FILTER, say). A retry of the same read never clears it. The caller reads your error's message, so they know which operator or column to drop. Write it for them: ⛔ no remote URL, host or credential in it. The message is withheld, and goes to the server log, when the read carries a predicate the caller did not write, such as a sharing or row-level security scope, because it may name that predicate's column or value. A remote404on a list endpoint often means a wrong base path or resource mapping in your driver, not a bad query. - A write refused for the request's own sake (400, 404, 409, 412 or 422) answers
422 EXTERNAL_WRITE_REFUSEDcarrying your error's message. - Anything else answers
503 ERR_DATASOURCE_UNAVAILABLEwithreason: 'remote': a 5xx, an unreachable remote, a throw with nostatus, and also 401, 403, 407 and 429, because an expired credential or a rate limit is the operator's to fix and its text may name the credential. The message says the remote could not answer and to retry; your error's own text goes to the server log atwarnand never to the caller.
- A read refused for the request's own sake (400, 404 or 422), which is what
- Send the remote only the columns it owns.
updatereceives the patch plus any field a hook stamped, plusid,updated_atandupdated_by, which the engine adds on its own and no remote column declares. - Declare
supports.transactionsUnsupported: truefor a transport with no transactions (any REST API): the engine reads the bit before it reaches for one. - Throw from
connect()to refuse the boot when the remote is unusable — the operator then reads your message instead of a failure per request (Writing a driver).
2. The plugin
A plugin publishes the driver as the service driver.<name> during init. That is the
whole server half of the integration.
import type { Plugin, PluginContext } from '@objectstack/core';
import type { IDataDriver } from '@objectstack/spec/contracts';
export function portScheduleDriverPlugin(driver: IDataDriver): Plugin {
return {
name: 'com.example.driver-port-schedule',
version: '1.0.0',
init: async (ctx: PluginContext) => {
ctx.registerService(`driver.${driver.name}`, driver);
},
};
}Mount it in the stack's plugins like any other plugin
(Register with the kernel):
plugins: [portScheduleDriverPlugin(createPortScheduleDriver(myTransport))]. Register the
service in init, not start: the engine adopts driver.* services, and the datasource
connect step looks the driver up, once every plugin has initialised.
3. The datasource, the object, the hook, the views
import { defineStack, defineView } from '@objectstack/spec';
const BerthViews = defineView({
list: {
label: 'All slots',
type: 'grid',
data: { provider: 'object', object: 'berth_slot' },
columns: ['name', 'start_date', 'end_date'],
},
listViews: {
plan: {
label: 'Berth plan',
type: 'gantt',
data: { provider: 'object', object: 'berth_slot' },
columns: ['name'],
filter: [{ field: 'archived', operator: 'equals', value: false }],
sort: [{ field: 'start_date', order: 'asc' }],
gantt: {
startDateField: 'start_date',
endDateField: 'end_date',
titleField: 'name',
parentField: 'parent',
lockField: 'locked',
dependenciesField: 'depends_on',
},
},
},
});
export default defineStack({
manifest: { id: 'com.example.port', name: 'Port operations', version: '1.0.0', type: 'app' },
datasources: [
{
name: 'port_schedule',
label: 'Terminal schedule (plugin driver)',
driver: 'port_schedule', // the service suffix: the plugin published `driver.port_schedule`
schemaMode: 'external',
config: {}, // the driver was built by your code; nothing to configure here
external: {
allowWrites: true,
// A driver without `introspectSchema` cannot be validated at boot;
// `checkOnBoot: false` is what lets it come up.
validation: { onMismatch: 'fail', checkOnBoot: false },
},
},
],
objects: [
{
name: 'berth_slot',
label: 'Berth slot',
datasource: 'port_schedule',
external: { remoteName: 'slots', writable: true },
// Remote rows carry no `owner_id` / `created_by`: who may edit is the
// hook's decision. See "Choose the sharing model on purpose" below.
sharingModel: 'public_read_write',
fields: {
name: { type: 'text', label: 'Name' },
parent: { type: 'lookup', reference: 'berth_slot', label: 'Parent' },
start_date: { type: 'date', label: 'Start' },
end_date: { type: 'date', label: 'End' },
depends_on: { type: 'text', label: 'Depends on' },
planner: { type: 'text', label: 'Planner' },
plan_locked: { type: 'boolean', label: 'Plan locked' },
archived: { type: 'boolean', label: 'Archived' },
plan_note: { type: 'text', label: 'Plan note' },
// Per caller: locked once the plan is, and for anyone but the slot's planner.
locked: {
type: 'formula',
label: 'Locked',
returnType: 'boolean',
expression: 'record.plan_locked || record.planner != current_user.id',
},
},
},
],
views: [BerthViews],
hooks: [
{
name: 'berth_slot_plan_guard',
object: 'berth_slot',
events: ['beforeUpdate'],
refusals: {
PLAN_LOCKED: { message: 'This plan is locked; unlock it before rescheduling.', status: 409 },
NOT_PLANNER: { message: 'Only the planner of this slot may reschedule it.', status: 403 },
},
body: {
language: 'js',
source:
"if (ctx.previous && ctx.previous.plan_locked === true) throw Object.assign(new Error(), { code: 'PLAN_LOCKED' });\n"
+ "if (ctx.previous && ctx.previous.planner !== ctx.user?.id) throw Object.assign(new Error(), { code: 'NOT_PLANNER' });\n"
+ "ctx.input.plan_note = 'checked';\n",
capabilities: [],
timeoutMs: 5000,
},
},
],
permissions: [
{
name: 'berth_planner',
label: 'Berth planner',
objects: { berth_slot: { allowRead: true, allowEdit: true } },
},
],
});What each piece does on a plugin driver:
- The datasource names the driver by its service suffix. Keep four names equal:
the driver's
name, the service suffix, the datasourcenameand itsdriver. The connect step finds the driver already registered and leaves it alone — it builds nothing and connects it once. - Writes are a double opt-in, exactly as for federation:
external.allowWriteson the datasource andexternal.writableon the object (Writes). - The formula is the UI's lock; the hook is the rule.
lockedevaluates per caller on every read — the planner readsfalseon an open slot, an administratortrue— and the gantt offers no drag grips on a locked bar. A PATCH does not consult a formula, so thebeforeUpdatehook enforces the same rule: its refusal answers with the declared message and status, and the driver is never asked to write. It reads the pre-image (ctx.previous) through your driver, and may stamp fields (plan_note) that then reachupdate. See Before hook and Hook bodies. - Permission sets apply as on any object. A caller whose sets grant nothing on
berth_slotis refused403on a list read before your driver is asked anything. On a PATCH the write door loads the record first, so the remote sees one by-id read for a caller it then refuses. - The gantt is an ordinary list view (Gantt):
parentFieldbuilds the summary-and-children tree,dependenciesFielddraws the links, andlockFieldreads the per-caller formula. A drag on an unlocked bar issues thePATCH /data/berth_slot/:idabove.
Choose the sharing model on purpose
On the default sharing model, every member edit is refused, even for a member whose
permission set grants allowEdit. That model keys reads to the row's owner_id, a column
a remote row does not carry, so the member's read scope admits no row: lists come back
empty and an edit answers 404. On public_read the rows are readable, but before a write
the platform's ownership checks ask the remote for owner_id and for created_by equal to
the caller, find neither, and refuse the edit with 403
(#27332). Declare
sharingModel: 'public_read_write' and decide who may edit in beforeUpdate, as above.
Serving an owner column the checks can read is the other way out; the reference test
does not cover it, so pin it in your own test if you take it.
Missing owner columns fail closed: the edit is refused, never allowed by mistake. Setting
sharingModel is not enough by itself, because an explicit private is refused the
same way. There are two ways out:
sharingModel: 'public_read_write'with abeforeUpdatehook that decides, as above;- a declared owner field that your driver returns under that field name. A built-in SQL
driver maps it through
external.columnMap; on a plugin driver the mapping is your driver's own job, because the engine does not applycolumnMap.
On public_read_write, a member's delete is still refused: the ownership floor keeps
deletes by design. A delete passes only when your driver returns created_by, or when a
policy or a share grants it. The validation warning for an external object whose owner
is unmapped is tracked in
#27332.
Several organizations on one deployment: declare the object's scope
A deployment that walls its organizations apart (OS_TENANCY_POSTURE=isolated or group)
stores every platform row with an organization_id and reads it back through that wall. A
virtual object has no platform row: whether the rows your driver serves belong to one
organization or to every organization is something only you know, so under a walled
posture every external object states its organization scope, in one of three ways.
// Walled: the remote rows carry the organization column and the driver returns it.
// A member of organization A reads only rows whose organization_id is A.
{
name: 'berth_slot',
datasource: 'port_schedule',
external: { remoteName: 'slots' },
fields: { name: { type: 'text', label: 'Name' }, organization_id: { type: 'text', label: 'Organization' } },
}
// Shared: every organization reads the same rows (a reference catalogue, a tariff table).
{ name: 'tariff', datasource: 'port_schedule', external: { remoteName: 'tariffs' }, tenancy: { enabled: false }, fields: { /* … */ } }
// Shared, spelled on the system fields: the same declaration.
{ name: 'tariff', datasource: 'port_schedule', external: { remoteName: 'tariffs' }, systemFields: { tenant: false }, fields: { /* … */ } }What the reference test pins, under isolated with two organizations (block (h)):
- A member of A reads only A's rows of a walled object, and the driver is asked with
where: { organization_id: 'A' }— forward it to the remote as you forward any other condition. - A driver that ignores
wherestays walled. The engine re-applies the whole query to the rows the driver returns, so a remote that cannot filter by organization still answers only the caller's rows to the caller. - A row missing the organization column reads to no one.
- An external object that states none of the three fails the boot, by name, with the
three ways out in the error. The boot that runs the
singleposture owes no declaration: the first seven blocks of the reference test boot exactly such a stack.
A remote whose organization column has another name is mapped onto the wall's column with
external.columnMap: { org_ref: 'organization_id' } on a built-in SQL driver or the OData
driver, which apply the map; on a plugin driver, return the column as organization_id
yourself — the engine does not apply columnMap there. tenancy.tenantField does not do this: the wall keys on organization_id
alone, so on an external object a tenantField naming another column is refused at boot
with the same remedy. An object registered after the boot (a Studio import, a runtime
datasource) that states nothing is not refused — it is denied: every read answers zero
rows and every write is refused, and the boot log says why, until it declares one of the
three.
The engine re-applies every query
For a datasource whose schemaMode is not managed and whose driver is not a built-in
id (memory, sqlite, sqlite-wasm, postgres, mysql, mongodb, turso), the engine holds the
driver behind a correctness floor. It does not change a federated database on a built-in
driver.
- What the driver is sent.
findgetswhereandorderBy, which it may push down, and alimitof the row cap plus one (limit: 1001by default). It never getsoffsetorfields.findOneandcountreach your driver as that samefind.aggregateis never called; the engine aggregates in memory. - What the engine does with the rows. It applies the whole query itself:
where(the engine's own operator vocabulary,$likeand$ilikeincluded), the sort (no value sorts last),offsetandlimit(a paged read breaks ties byid), and the projection. - Writes go to your driver unchanged, one record at a time. The floored driver does
not offer
updateManyordeleteMany, so nowherethe engine cannot re-check reaches a write. A by-id write under a precondition goes throughupdateby id, and a multi-row predicate update or delete is refused.
So a driver grows in three steps, each correct:
- Return every row. Ignore the query and answer the resource's rows. The answer is
correct for any resource with at most the row cap's rows. Honour the
limityou are sent by paging the remote: a remote whose page is smaller than that limit, and that you do not page through, answers fewer rows than match, and the engine cannot detect it. Never hard-code1001: a datasource that raises its cap sends a larger limit. - Push
whereandorderBydown. The remote returns only the matching rows, so the row cap now counts matching rows, not the whole resource, and less travels. The engine still re-checks every row, so a translation slip shows up as a missing row (step 1's rule), never as an extra one. - Skip the floor with a conformance-tested driver. This is planned for a later phase (#27261): a driver that passes the platform's conformance kit would be trusted with paging and the cap. The kit ships (Run the conformance kit); the trust does not exist yet.
Because the engine needs every matching row to answer correctly, a read that matches more rows than the row cap is refused, never answered from a part.
Not covered by the floor.
- Predicate writes.
updateManyanddeleteManyare not offered on a floored datasource, so a write that selects its rows by a filter is refused rather than handed to your driver. Read the ids, then write each one. - A read whose scope composes a
ReadableIdsleaf, such as an objectcontrolled_by_parent, is refused (ADR-0139): the engine has no semi-join over a plugin driver's rows.
The row cap
A read that matches more rows than the datasource's row cap is refused with
422 EXTERNAL_ROW_CAP_EXCEEDED rather than answered from a partial set. The cap applies
to plugin drivers only, OData included, and it counts every read: a list page, its total,
a record, and the by-id reads before a write.
-
The default is 1000 rows. A datasource raises or lowers it with
external.rowCap, a whole number from 1 to the platform maximum of 10,000. The schema refuses a larger value, and refuses the key on a built-in driver or a managed datasource, where it would do nothing.external: { allowWrites: true, validation: { onMismatch: 'fail', checkOnBoot: false }, rowCap: 5000, // this remote's widest read matches about 5,000 rows }, -
What a higher cap costs. The engine's own share is small: decoding and re-applying the query over 5,000 rows takes about 15 ms and 1 MiB, and over 10,000 about 35 ms and 2 MiB. The remote pays more. Every list page reads every matching row up to the cap, twice (the rows, then the total), so a cap of 5,000 can mean 10,000 rows from the remote for one page of 50. Raise it only as far as the widest read needs, and push
wheredown so the cap counts matching rows, not the resource. -
A list cannot page past the cap. When more rows match than the cap allows, every page of that read is refused, the first page and the one that starts at the cap included.
-
Past the cap, narrow the filter so fewer rows match, raise
external.rowCapup to 10,000, or, for data that size, mirror it into a real object with a scheduled pull and read that. The refusal's message names the datasource and its cap.
Views that read the whole set
A grid reads one page at a time. A gantt, a tree, a calendar and a map do not: each needs the whole filtered set at once, because a gantt cannot draw its date range or roll up its groups from one page, and a map cannot fit its camera to markers it never received. So each of the four sends one read for every matching row, and two ceilings apply to it, in this order:
| Ceiling | Where | Number | Past it |
|---|---|---|---|
| The row cap | the server, on a plugin-driver datasource | 1000, or external.rowCap up to 10,000 | the whole view fails with 422 EXTERNAL_ROW_CAP_EXCEEDED |
| The view's row ceiling | the browser, on every datasource | 2,000 rows, not configurable | the view draws the first 2,000 rows in its sort order and says so: "Showing the first 2,000 of 5,000 records. Narrow the filter." |
Each of the four views asks for 2,001 rows, the ceiling plus one row to detect the cut. On a plugin-driver datasource at the default cap, any filtered set past 1000 rows fails the whole view, and raising the cap is what turns the failure into a drawn view:
- Up to 1000 matching rows: the view draws everything with the default cap.
- 1001 to 2,000: set
external.rowCapto at least the largest set the view's filter admits, and the view draws everything. - More than 2,000: a cap of at least that size lets the view draw its first 2,000 rows with the note instead of failing. It never draws all of them. A cut gantt or tree is missing whole branches, so a planner should not work from one. Give the view a filter that keeps the set under 2,000 rows: a date window, a project, a status. Or split the view, one per project or per line.
Two habits keep a whole-set view working as the data grows:
- Put the narrowing in the view's
filter, not only in a quick filter a planner can clear. Clearing a quick filter, or widening a date range, is how a view that worked in testing reaches the cap in production. - Size the cap from the widest filter the view allows, not from today's row count, and keep it at or below 10,000. A set that will outgrow 10,000 matching rows belongs in a real object fed by a scheduled pull.
Credentials
⛔ Never put a credential in the stack — not in config, not in a hook body, not in an
object. On a plugin driver, also know what external.credentialsRef
(Credentials) does not do:
it is resolved when the platform builds the driver from the datasource, and a driver your
plugin registered is already built, so the connect step skips it before credential
resolution. A credentialsRef on this datasource is not resolved, not handed to your
driver, and does not fail the boot when no secret store is configured. A plugin is
configured by the host that composes it, through the options it passes to the plugin;
keep the credential in the host's secret handling and out of metadata and the
repository.
When a connector instance
already authorizes the vendor your driver calls, the datasource can name it in
external.connector instead
(Borrowing a connector instance's credential):
one credential then serves the connector's flow actions and your driver's requests. The
connect step checks that the named instance can lend, and fails the datasource when it
cannot, but it hands your already-built driver nothing. Your driver borrows the
credential itself, from the connector-credential-source service that the automation
service registers:
import type { PluginContext } from '@objectstack/core';
import {
CONNECTOR_CREDENTIAL_SOURCE_SERVICE,
callWithBorrowedCredential,
withoutBorrowedCredential,
type BorrowedConnectorAuth,
type ConnectorCredentialHandle,
type IConnectorCredentialSource,
} from '@objectstack/types';
// At the first request: `connector` is the datasource's `external.connector`.
async function borrow(ctx: PluginContext, connector: string): Promise<ConnectorCredentialHandle> {
const source = ctx.getService<IConnectorCredentialSource>(CONNECTOR_CREDENTIAL_SOURCE_SERVICE);
return source.borrow(connector);
}
// Every request: the helper refreshes an expired credential, and on a 401 obtains it
// afresh once and retries; a second 401 throws a 503 naming the instance.
async function request(handle: ConnectorCredentialHandle, url: string): Promise<Response> {
let sent: BorrowedConnectorAuth | undefined;
const response = await callWithBorrowedCredential(handle, (auth) => {
sent = auth;
return fetch(url, {
headers: auth.type === 'bearer' ? { Authorization: `Bearer ${auth.token}` } : {},
});
});
if (!response.ok) {
// An upstream may echo the credential in its error text: remove it before throwing.
const text = await response.text();
throw Object.assign(new Error(sent ? withoutBorrowedCredential(text, sent) : text), {
status: response.status,
});
}
return response;
}The sketch sends only a bearer token. Present auth as its type says: bearer as
Authorization: Bearer, basic as Authorization: Basic, and api-key in its
headerName header or, with paramName, as a query parameter. Refuse the request,
sending nothing, when the service is absent or the datasource also names a
credentialsRef. The OData driver is the reference implementation
(packages/drivers/driver-odata/src/plugin.ts and transport.ts).
What your driver receives
Measured on the reference test, request by request, with the engine's floor (above) in place:
| The platform does | Your driver is called with |
|---|---|
| Boots | connect() once. No syncSchema, no introspectSchema (checkOnBoot: false). |
Serves a list (GET /data/berth_slot with the view's filter, sort and page size) | find(object, { where, orderBy, limit: 1001 }), then find(object, { where, limit: 1001 }) for the total. The page size is applied by the engine. 1001 is the default row cap plus one; a datasource's external.rowCap moves it. |
Serves a record (GET /data/berth_slot/:id) | find(object, { where: { id }, limit: 1001 }) |
Writes (PATCH /data/berth_slot/:id) | several by-id reads as find (the pre-image for hooks and checks), then update(object, id, patch) with the extra keys above |
| Refuses a caller with no grant on a list read | nothing |
Your driver should still implement findOne and count: the engine calls them on a
driver that is not behind the floor, and the shape test below exercises them.
Two details catch every first driver:
objectis the object name (berth_slot), neverexternal.remoteName(slots). The mapping from object to remote resource is the driver's.objectalso rides inside the query ({ where, …, object: 'berth_slot' }) althoughDriverQueryomits it from its type. Read the object name from argument one; do not forward the query object to the remote as-is.
The filter arrives in the engine's where shape: equality as a bare value
({ archived: false }), operators as { field: { $op: value } }, and combinators such
as $and. The console lowers the view's
[{ field: 'archived', operator: 'equals', value: false }] to
?filter=["archived","=",false], which arrives as { archived: false }.
Pin the shapes your driver receives
A driver is correct when, for every query shape the engine sends, the remote is asked for exactly the right thing — and asked for nothing when the driver cannot honour the shape. Pin that in a test of the driver alone, with a recording transport in place of the network. The shapes below are the ones the reference test measured; add one for every view filter your app ships.
import { describe, it, expect, vi } from 'vitest';
import { createPortScheduleDriver, type PortScheduleTransport } from './port-schedule-driver';
/** A transport that records what the remote is asked, and answers nothing in particular. */
function recordingTransport() {
return {
list: vi.fn(async () => [{ id: 's_1', name: 'Berth 4 — MSC Aurora' }]),
count: vi.fn(async () => 1),
patch: vi.fn(async (_resource: string, id: string, changes: Record<string, unknown>) => ({ id, ...changes })),
} satisfies PortScheduleTransport;
}
describe('port_schedule driver — the shapes the engine sends, and what the remote is asked', () => {
it('a list view read: every filter, the sort and the page size reach the remote', async () => {
const remote = recordingTransport();
const driver = createPortScheduleDriver(remote);
// The DriverQuery a list view with a filter, a sort and a page size produces.
// `object` rides inside it although the type omits it.
await driver.find('berth_slot', {
where: { archived: false },
orderBy: [{ field: 'start_date', order: 'asc' }],
limit: 50,
object: 'berth_slot',
} as never);
expect(remote.list).toHaveBeenCalledWith('slots', {
filter: [{ field: 'archived', op: 'eq', value: false }],
sort: [{ field: 'start_date', desc: false }],
limit: 50,
});
});
it('the total: count carries the same filter', async () => {
const remote = recordingTransport();
await createPortScheduleDriver(remote).count('berth_slot', { object: 'berth_slot', where: { archived: false } } as never);
expect(remote.count).toHaveBeenCalledWith('slots', [{ field: 'archived', op: 'eq', value: false }]);
});
it('a by-id read (record page, pre-image for a hook) asks for one row', async () => {
const remote = recordingTransport();
const row = await createPortScheduleDriver(remote).findOne('berth_slot', { where: { id: 's_1' }, object: 'berth_slot', limit: 1 } as never);
expect(remote.list).toHaveBeenCalledWith('slots', { filter: [{ field: 'id', op: 'eq', value: 's_1' }], sort: [], limit: 1 });
expect(row).toMatchObject({ id: 's_1' });
});
it('an update forwards only the columns the remote owns', async () => {
const remote = recordingTransport();
// The patch, the hook's stamp, and what the engine adds on its own.
await createPortScheduleDriver(remote).update('berth_slot', 's_1', {
start_date: '2026-11-03', end_date: '2026-11-07', plan_note: 'checked',
id: 's_1', updated_at: '2026-11-01T08:00:00.000Z', updated_by: 'usr_planner',
});
expect(remote.patch).toHaveBeenCalledWith('slots', 's_1', { start_date: '2026-11-03', end_date: '2026-11-07', plan_note: 'checked' });
});
it('a condition the remote cannot run is refused by name — never dropped, never an empty answer', async () => {
const remote = recordingTransport();
const driver = createPortScheduleDriver(remote);
await expect(driver.find('berth_slot', { where: { $or: [{ archived: false }, { planner: 'u1' }] } } as never)).rejects.toThrow(/\$or/);
// The status the engine reads: a refusal of this request answers 400, not "retry later".
await expect(driver.find('berth_slot', { where: { $or: [{ archived: false }] } } as never)).rejects.toMatchObject({ status: 400 });
await expect(driver.find('berth_slot', { where: { start_date: { $gte: '2026-11-01' } } } as never)).rejects.toThrow(/\$gte/);
// The default sharing model asks for ownership columns no remote row carries.
await expect(driver.findOne('berth_slot', { where: { $and: [{ id: 's_1' }, { created_by: 'u1' }] } } as never)).rejects.toThrow(/created_by/);
expect(remote.list).not.toHaveBeenCalled();
});
});When the remote gains an operator, the refusal case is the one that changes: move the
operator from "refused" to a shape case, then teach OPERATORS the mapping. To see the
same shapes arrive through a booted stack — HTTP door, permissions, formula, hook —
start from the reference test named at the top of this page.
Run the conformance kit
The shape test pins what your driver sends. The platform's plugin-driver conformance
kit pins what the engine relies on, from outside this repository: a driver in its own
repository runs it in its own CI, so a platform change to that contract fails there
before it reaches your users. It ships in @objectstack/objectql:
definePluginDriverConformanceSuite registers one test per case under your runner's
describe / it (vitest and jest alike), and runPluginDriverConformance returns a
report without a test framework.
import { afterAll, describe, it } from 'vitest';
import { definePluginDriverConformanceSuite } from '@objectstack/objectql';
import { createPortScheduleDriver } from './port-schedule-driver';
import { fakeRemoteHolding } from './fake-remote'; // your fake of the remote's API
definePluginDriverConformanceSuite(
{ describe, it, afterAll },
{
// A driver over a remote holding exactly the fixture's rows, served under its object.
setup: (fixture) => ({ driver: createPortScheduleDriver(fakeRemoteHolding(fixture)) }),
},
);The kit's oracle is the spec's driver conformance tables, the standard every built-in
driver is held to. Each read is checked against the floor: the driver may push all of a
filter down, part of it or none, and may refuse what it cannot translate, but must never
return fewer rows than match, invent a row, or answer a failure as rows. Add
setupUnavailable (a remote that is down) for the outage cases and writeProbes (one
write the remote accepts, one it refuses) for the write cases; without them those cases
report not-offered. tiers: ['floor', 'direct'] adds the stricter tier, where the
driver answers the whole query itself; the floor does not need it. The OData driver runs the
kit in packages/drivers/driver-odata/src/odata-driver.conformance-kit.test.ts.
Five business examples
Port berth scheduling — computed, real-time. The worked example above. The
terminal's planning system recomputes the plan as vessels slip; the platform is the
plan's view and its edit door. A gantt over the tree, a per-caller lock formula, a
beforeUpdate guard, writes through update only.
SAP sales orders — must not land. The ERP is the system of record, and orders may not
be copied out of it. When the ERP publishes the orders as an OData v4 service, bind them
through an OData datasource and write no driver.
Otherwise the driver reads orders through the ERP's own query API and writes
the few fields users may change through its update API; the ERP's own validation answers
a write it rejects, so let that error reach the caller rather than retrying around it.
Refuse create and delete until the integration deliberately offers them, and keep
the object's writable and the datasource's allowWrites as narrow as the API.
HR directory — must not land. People's records stay in the HR system, so a leaver
disappears from every page the moment HR removes them, with no copy left to purge. Read
only: leave allowWrites off, grant read by permission set, and choose public_read —
an owner-keyed sharing model judges records by ownership columns an HR row does not
carry (the callout above).
Equipment live status — real-time. Cranes, reefers, gates: the state a device
reports now, read from the gateway when the page is drawn; a copy would be stale before
it landed. Read only, small pages, and a find that throws when the gateway does not
answer, so a dead gateway reads as an error and never as "no alarms".
Counter-example: vessel and port codes — a real object. UN/LOCODE port codes, vessel
registries, cost centres change monthly and are read by every page, filtered, joined and
reported on. Make them a real object filled by a scheduled pull — a mapping whose
connectorSource names the API, and a job whose pull runs it
(Pulling a mapping) — and they get indexes,
every query operator and search, and stay readable when the source is down. There is no
separate data-sync metadata type: a sync is defined on its target, as that mapping.
See also
- OData datasources — the same binding over an OData v4 service, with the driver already written.
- External datasources — the datasource and
externalbinding this page builds on, federation over SQL, the write gates and credentials. - Database drivers — the built-in drivers and the driver-startup contract.
- Formulas —
current_userand the formula bindings. - Hooks and Hook bodies — the
beforeUpdateguard. - Views — the gantt and every other list view.
- ADR-0015 (federation spec) —
schemaMode, theexternalbinding and the write gates.