A scheduled mirror of another system's records
Keep a copy of a shop's orders, a CRM's contacts or a calendar's events in your app: a scheduled job reads what changed since its watermark, writes one record per outside id, and leaves the fields your people edit alone.
The problem: the records live somewhere else. A shop's orders sit in Squarespace, contacts in a CRM, events in a calendar, and your app wants them on its own screens, next to the notes, checkboxes and assignments your people add. Reading the other system on every page load is slow and burns its rate limit; copying everything every time rewrites records nobody changed.
The pattern: a scheduled handler keeps a mirror. Each run reads only
what changed since a stored watermark, writes one document per outside
record at an id built from the record's own id, and moves the watermark
forward only after the page it read is written. Everything a person types
lives in a second document beside the mirrored one, so the next sync never
touches it.
The example below mirrors a shop's Squarespace orders into a packing list.
Squarespace's order reads are on the platform's list of admitted services,
called with the owner's own API key from ctx.secrets. The same shape fits
any API that can list records modified after a time.
The parts
| Part | What it does |
|---|---|
| The watermark doc | One document, mirror:state, holding the time the last complete read reached, the page cursor of a read in progress, and when to try again after a refusal |
| One record per outside id | Each order lands at order:<store id>, so reading it again rewrites the same document |
| Write only what changed | A record whose mirrored fields already match is skipped, so a quiet store means a quiet database |
| Paging | A read covers a fixed time window and pages through it on the store's cursor, a few pages a run, picking up where it stopped |
| Backing off | A 429 stores a backoffUntil time on the watermark doc, and runs before it return at once |
| Two writers, two documents | The mirror owns order:<id>; people own pack:<id>, keyed by the same store id |
The mirror job
Save the store's key as a secret first, in Code mode under App settings ›
Secrets or from a terminal:
npx vibes-diy secrets set SQUARESPACE_API_KEY --vibe you/your-app. Until it
is set, the job returns and the rest of the app works.
js// backend.js
export const config = { scheduled: { interval: "1m" } };
const ORDERS = "https://api.squarespace.com/1.0/commerce/orders";
const STATE = "mirror:state";
const POLL_EVERY_MS = 15 * 60 * 1000; // read the store every 15 minutes
const OVERLAP_MS = 2 * 60 * 1000; // re-read the edge of the last window; the upsert makes it free
const PAGES_PER_RUN = 5;
// The fields the mirror owns. Every one comes from the store and is rewritten from it.
function mirrorOf(order) {
return {
type: "order",
storeId: order.id,
orderNumber: String(order.orderNumber),
createdOn: order.createdOn,
modifiedOn: order.modifiedOn,
fulfillmentStatus: order.fulfillmentStatus,
shipTo: [order.shippingAddress?.firstName, order.shippingAddress?.lastName].filter(Boolean).join(" "),
items: (order.lineItems ?? []).map((li) => ({ name: li.productName, sku: li.sku ?? null, quantity: li.quantity })),
};
}
// One document per store id, written only when a mirrored field changed.
async function upsert(ctx, order) {
const id = "order:" + order.id;
const next = mirrorOf(order);
const stored = await ctx.db.get(id, { db: "orders" });
if (stored && Object.keys(next).every((k) => JSON.stringify(stored[k]) === JSON.stringify(next[k]))) return false;
await ctx.db.put(next, { db: "orders", id });
return true;
}
export async function scheduled(event, ctx) {
const key = ctx.secrets.SQUARESPACE_API_KEY;
if (!key) return; // the mirror starts the minute the key is saved
const now = Date.parse(event.scheduledTime);
const state = (await ctx.db.get(STATE, { db: "orders" })) ?? {
type: "mirrorState",
since: new Date(now - 30 * 86400000).toISOString(), // the first run copies the last 30 days
};
if (state.backoffUntil && Date.parse(state.backoffUntil) > now) return;
const due = state.cursor || !state.lastPolledAt || now - Date.parse(state.lastPolledAt) >= POLL_EVERY_MS;
if (!due) return;
const until = state.until ?? event.scheduledTime; // the window stays fixed until its last page is in
let cursor = state.cursor ?? null;
let written = 0;
for (let page = 0; page < PAGES_PER_RUN; page++) {
const url = cursor
? `${ORDERS}?cursor=${encodeURIComponent(cursor)}`
: `${ORDERS}?modifiedAfter=${encodeURIComponent(state.since)}&modifiedBefore=${encodeURIComponent(until)}`;
const res = await ctx.fetch(url, { headers: { authorization: `Bearer ${key}`, "user-agent": "packing-station" } });
if (!res.ok) {
// Back off and keep the cursor: the next try resumes on the same page.
// The first wait is a minute (Squarespace's cool-down after a 429), doubling up to 30.
const wait = Math.min((state.backoffMs ?? 30000) * 2, 30 * 60000);
await ctx.db.put(
{ ...state, until, cursor, backoffMs: wait, backoffUntil: new Date(now + wait).toISOString(), lastError: `store answered ${res.status}` },
{ db: "orders", id: STATE }
);
ctx.log("warn", "mirror backing off", { status: res.status, waitMs: wait });
return;
}
const body = await res.json();
for (const order of body.result ?? []) if (await upsert(ctx, order)) written += 1;
if (body.pagination?.hasNextPage) {
// This page is written, so the cursor may move past it.
cursor = body.pagination.nextPageCursor;
await ctx.db.put({ ...state, until, cursor, backoffMs: null, backoffUntil: null, lastError: null }, { db: "orders", id: STATE });
continue;
}
// The whole window is in: move the watermark, keeping a small overlap.
await ctx.db.put(
{
...state,
since: new Date(Date.parse(until) - OVERLAP_MS).toISOString(),
until: null,
cursor: null,
lastPolledAt: event.scheduledTime,
backoffMs: null,
backoffUntil: null,
lastError: null,
},
{ db: "orders", id: STATE }
);
break;
}
ctx.log("info", "mirror run", { written });
}
The query parameters are Squarespace's own: modifiedAfter and
modifiedBefore together bound a window, and cursor, sent alone, carries
the value of pagination.nextPageCursor from the page before. Another store
names these differently, so take them from its API reference.
A run that stops after five pages saves its cursor, and the next run, a minute later, picks the read up on that page. The watermark itself moves only when a window's last page is written, so a crash halfway through re-reads a page and lands every order on the document it already had.
The rules that keep it safe
- Key every record by the outside id.
order:<store id>is the whole idempotency story: a second read, an overlapping window and a retried page all write the same document. Order numbers are for people; the store's own id is the one that never changes. - Write only what changed. Comparing the mirrored fields first means a
run over 200 unchanged orders writes nothing, so nothing syncs to anyone's
device and any
onChangehandler stays quiet. - Move the watermark after the write. Save the cursor once a page is
stored, and the new
sinceonce the window's last page is stored. A small overlap at the edge of each window picks up a record modified in the same second the last read ended. - Pause on a refusal and resume on the same page. Squarespace allows 300
requests a minute and answers the next one with a
429and a one-minute cool-down, which arrives as an ordinary response fromctx.fetch. Wait at least that minute, double the wait on each refusal in a row, and cap it so the mirror is back within half an hour. Another store states its own limit and cool-down in its API reference. The platform's own per-app limits (30 calls in 10 seconds, 300 a minute) leave plenty of room for five pages a minute. - Keep what the store stopped sending. A record missing from one read is a record outside that window. A cancelled order comes back with its new status, and the mirror writes that.
- Show the watermark.
mirror:stateis a document like any other, so the packing screen can say "Orders synced 3 minutes ago" fromlastPolledAt, or showlastErrorwhile the mirror waits out a refusal.
Mirror fields and people's fields
A packer ticks "packed", adds a note, or claims an order. Those fields go in
a pack:<store id> document beside the order, never on the order itself.
Each document has one writer: the mirror rewrites order:<id> whenever the
store changes, and a packer's tick lands on pack:<id>, which the mirror
never reads or writes. Records merge whole, the last write wins, so two
writers on one document would take turns erasing each other.
The packing screen reads both types and joins them by store id:
useLiveQuery("type", { key: "order" }) for the orders and
useLiveQuery("type", { key: "packing" }) for the packers' notes.
Access rules for the mirror's writes
scheduled runs as the app's owner in admin mode, so it reads every record
and passes ctx.requireBackend("scheduled"), while the access function still
routes what it writes. Gate the mirrored types on that origin, and a packer's
browser can never overwrite what the store said:
js// access.js
export function orders(doc, oldDoc, user, ctx) {
if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
if (doc.type === "order" || doc.type === "mirrorState") {
ctx.requireBackend("scheduled"); // only the mirror writes the store's copy
return { channels: ["orders"], grant: { roles: { owner: ["orders"] } } };
}
if (doc.type === "packing") {
ctx.requireAccess("orders"); // anyone who sees the orders can pack them
if (typeof doc.orderId !== "string" || doc._id !== "pack:" + doc.orderId) {
throw { forbidden: "a packing note sits at pack:<order id>" };
}
return { channels: ["orders"] };
}
if (doc.type === "member") {
ctx.requireRole("owner"); // the owner adds the packers
if (typeof doc.userHandle !== "string" || doc.userHandle === "") throw { forbidden: "a member names a handle" };
return { channels: ["orders"], grant: { users: { [doc.userHandle]: ["orders"] }, roles: { owner: ["orders"] } } };
}
throw { forbidden: "unknown type" };
}
The owner reads the orders from the first run through the reserved owner
role. A member record the owner writes lets a packer in, and from then on
the packer sees every order and writes packing records, while the order
records stay the store's.
Ring the doorbell for faster updates
A fifteen-minute read is gentle on the store, and a new order can show up in the app within a minute when something tells the mirror to look now. Many shops already get an email for every order, and a Zap on that email can post just the order number to the app. The Zap setup is on Works with Zapier. The backend half is a route that stores the number and two lines in the mirror job.
The route checks the shared secret the same way as every Zapier route, then
writes a doorbell record holding nothing but the order number:
js// backend.js — add beside the mirror job
const enc = new TextEncoder();
function json(data, status) {
return new Response(JSON.stringify(data), { status: status ?? 200, headers: { "content-type": "application/json" } });
}
// Constant time: both sides become fixed-length digests, compared byte by byte.
async function sameText(a, b) {
const [x, y] = await Promise.all([a, b].map(async (s) => new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s)))));
let diff = 0;
for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
return diff === 0;
}
export async function fetch(request, ctx) {
const url = new URL(request.url);
if (url.pathname !== "/zapier/order" || request.method !== "POST") return json({ ok: false, reason: "not found" }, 404);
const secret = ctx.secrets.ZAPIER_INBOUND_SECRET;
if (!secret) return json({ ok: false, reason: "this app is still being set up" }, 503);
if (!(await sameText(request.headers.get("x-zapier-secret") ?? "", secret))) {
return json({ ok: false, reason: "unrecognized sender" }, 401);
}
const body = await request.json().catch(() => null);
const number = String(body?.order ?? "").replace(/^#/, "").trim();
if (!/^[A-Za-z0-9-]{1,40}$/.test(number)) return json({ ok: false, reason: "send the order number as order" }, 400);
// Ringing twice for one order lands on the same doorbell.
await ctx.db.put({ type: "doorbell", orderNumber: number, rangAt: new Date().toISOString() }, { db: "doorbells", id: number });
return json({ ok: true });
}
In the mirror job, a ringing doorbell makes the read due, and a finished read clears every doorbell that rang before the window it just covered ended. The store sends its order email after the order exists, so a read whose window ends after the ring has already brought that order in:
js// in scheduled(), replacing the `due` line
const ringing = await ctx.db.query({ db: "doorbells", limit: 100 });
const due = state.cursor || ringing.length > 0 || !state.lastPolledAt || now - Date.parse(state.lastPolledAt) >= POLL_EVERY_MS;
// in scheduled(), right after the watermark moves and before `break`
for (const bell of ringing) {
if (Date.parse(bell.rangAt) < Date.parse(until)) await ctx.db.delete(bell._id, { db: "doorbells" });
}
Doorbells get a database of their own, so the run reads them with one small query. Only the route rings one, nobody is granted the channel it sits on, and only the mirror clears it:
js// access.js — beside orders()
export function doorbells(doc, oldDoc, user, ctx) {
if (doc._deleted) ctx.requireBackend("scheduled"); // the mirror clears answered doorbells
else ctx.requireBackend("fetch"); // only the route rings
return { channels: ["doorbells"], allowAnonymous: true }; // the Zap carries no sign-in
}
The doorbell carries an order number and nothing else, and the mirror reads every detail from the store with the owner's key. So the app never parses an email, a new email template from the store changes nothing, and the most a stray ring can do is start the next read a little early. Anything Zapier misses, the fifteen-minute read brings in anyway.
Composes with
Scheduled self-maintenance (the
same tick discipline: idempotent, bounded, visible when it stops),
doc-status state machines (a pack:
record walking new → packed → shipped), the
operator console (the watermark doc is its
"last synced" line), and Works with Zapier for
the doorbell's Zap.