Admin: scripting safely
Admin keys and scopes, dry runs, undo, idempotent writes and the audit log.
Beta
The admin routes are beta: they’re what Admin itself uses, and may still change. They answer only admins (the moderation queues also moderators); anyone else gets 404 not_found, as if the route didn’t exist.
Admin keys and scopes
Scripts use an admin key, made in Admin → API keys. It acts as you while you’re on staff, must expire within 90 days, and can be limited to your servers’ addresses. Give each script its own key with the fewest scopes it needs:
admin:catalog:readandadmin:catalog:write: catalog records, merges and issue moves.admin:moderation:readandadmin:moderation:write: the moderation queues (corrections, variant suggestions, codes, cover photos and the variants collectors added, the editions queue).admin:imports:readandadmin:imports:write: catalog imports and syncs, and their identity conflicts.admin:users:readand…:write,admin:support:write,admin:ops:readand…:write: people, plans and stores, support, and operations.
People’s data: email addresses and sign-in times reach a key only with admin:users:pii. Without it they answer null (a support message’s sender name and browser too), and finding people by email is refused (403 insufficient_scope); the people search then matches usernames, names and ids only. With it, every answer that carries them is in the audit log as api_key.pii_read, with whose records. No preset includes it, and moderators’ keys never use it.
Moderators’ keys hold catalog:read and the two moderation scopes, nothing else. That’s checked on every request, not only when the key is made: a key whose owner is a moderator can’t edit the catalog, whatever scopes it was made with (403 insufficient_scope).
Dry run, then apply
The changes that merge or move records take ?dryRun=true. The database runs the change and rolls it back, so the answer is exactly what applying it would do to the data as it is now, with dryRun: true and no journal id; nothing changes, and a change that can’t run is refused with the same error:
- Merge two records: the plan (children that merge or move, what follows, fills, warnings, fields left to decide) and the database’s count of its changes. Preview a merge answers the plan alone.
- Move issues to another series: how many move and which slugs change.
- Undo a merge and Undo an issue move: how many changes would be put back, and how many skipped because the data changed since.
- Put an imprint on series: which series would carry it, and the imprint each had. Resolve an import conflict: how it would be resolved.
- Review a provisional edition and Undo an edition’s review: a rejection’s merge, counted by kind of change, and what an undo would put back.
- Decide a report: the reports it would close, what it would hide, the store it would suspend and the account it would disable. Disabling bans an account outside the database: the dry run makes the same checks and disables nobody.
import { createCollectorClient } from '@collector/sdk';
// An admin key (Admin → API keys) with admin:catalog:write.
const collector = createCollectorClient({ token: process.env.COLLECTOR_ADMIN_TOKEN });
const merge = {
entity: 'issue',
winnerId: '00000000-0000-4000-8000-000000000001',
loserId: '00000000-0000-4000-8000-000000000002',
note: 'Duplicate created by an import',
} as const;
// 1. Dry run: the database runs the merge and rolls it back, so this is exactly what applying it
// does, and nothing changes. A merge that can't run answers 409 merge_blocked instead.
const plan = await collector.executeAdminMerge({ query: { dryRun: 'true' }, body: merge });
if (plan.preview.undecided > 0) {
console.error(`${plan.preview.undecided} field(s) to decide first: send them as overrides`);
process.exit(1);
}
for (const warning of plan.preview.warnings) console.warn(warning);
console.log('would change:', plan.summary);
// 2. Apply it. The client sends an Idempotency-Key (admin keys must), so a retry can't merge twice.
const merged = await collector.executeAdminMerge({ body: merge });
if (merged.dryRun) throw new Error('Expected the merge to be applied');
console.log('merged:', merged.id, merged.summary);
// 3. A merge can be undone for 7 days. Undo dry-runs too.
const undo = await collector.undoAdminMerge({ path: { id: merged.id }, query: { dryRun: 'true' } });
console.log(`undoing would put back ${undo.applied} change(s)`);Undo
Merges and moves are journaled, so they can be taken back for 7 days:
- Undo a merge and Undo an issue move.
- Undo a revert of an overridden field.
- Undo a change request’s review, Undo a code’s review, Undo a cover photo’s review and Undo a review in the Variants queue, within 7 days: the item is pending again, and an approval’s change is put back while the record still has what it wrote (
409 undo_blockedonce someone has changed it since). An import suggestion’s match can be undone at any time. - Undo an edition’s review, within 7 days: an approved edition is provisional again, a rejected one’s merge is undone.
Scripting the catalog
A script plans, dry-runs, then applies, with an admin key that has only the scopes it needs. Setting up an imprint: create it (or adopt the provisional publisher a collector already typed), merge the duplicates, and put it on its series, all or nothing:
import { CollectorApiError, createCollectorClient } from '@collector/sdk';
// Setting up an imprint (what scripts/catalog/setup-imprint.ts does), on the Admin API. An admin
// key with admin:catalog:write. The client sends an Idempotency-Key with every write, so running
// the script again after a failure can't apply anything twice.
const collector = createCollectorClient({ token: process.env.COLLECTOR_ADMIN_TOKEN });
const plan = {
publisherId: '00000000-0000-4000-8000-000000000010',
imprint: { name: 'Vertigo', foundedYear: 1993 },
// A duplicate series (the loser) to merge into the catalog's (the winner) first.
merges: [
{ winnerId: '00000000-0000-4000-8000-000000000021', loserId: '00000000-0000-4000-8000-000000000022' },
],
// The series that carry the imprint.
series: ['00000000-0000-4000-8000-000000000021', '00000000-0000-4000-8000-000000000023'],
note: 'The indicia name the imprint.',
};
// 1. The imprint: create it, or adopt the provisional publisher a collector already typed it as.
async function imprintId(): Promise<string> {
const path = { entity: 'publisher', id: plan.publisherId } as const;
try {
return (await collector.createAdminImprint({ path, body: plan.imprint })).record.id;
} catch (error) {
if (!(error instanceof CollectorApiError) || error.code !== 'provisional_exists') throw error;
// The provisional publisher's id rides in the problem's (pre-v1) error details.
const legacy = error.problem?.error as { details?: { provisional?: { id: string } } } | undefined;
const details = legacy?.details;
if (!details?.provisional) throw error;
const adopted = await collector.createAdminImprint({
path,
body: { ...plan.imprint, adopt: details.provisional.id },
});
return adopted.record.id;
}
}
const imprint = await imprintId();
// 2. Duplicates: a dry run first (the database runs the merge and rolls it back), then the merge.
for (const pair of plan.merges) {
const body = { entity: 'series', ...pair, note: plan.note } as const;
const dry = await collector.executeAdminMerge({ query: { dryRun: 'true' }, body });
if (dry.preview.undecided > 0) {
console.warn(`${pair.loserId}: ${dry.preview.undecided} field(s) to decide; merge it in Admin`);
continue;
}
const merged = await collector.executeAdminMerge({ body });
if (!merged.dryRun) console.log(`merged ${pair.loserId} (undo with ${merged.id})`, merged.summary);
}
// 3. The imprint on its series: all or nothing, each one locked against imports and audited.
const body = { seriesIds: plan.series, note: plan.note };
const check = await collector.setAdminImprintSeries({
path: { id: imprint },
query: { dryRun: 'true' },
body,
});
console.log(`${check.set} series to set, ${check.already} already carry it`);
if (check.set > 0) await collector.setAdminImprintSeries({ path: { id: imprint }, body });Settling import conflicts by a rule of your own, from each conflict’s side-by-side detail (One import conflict in full):
import { createCollectorClient } from '@collector/sdk';
// Settling import identity conflicts (what scripts/catalog/gcd-resolve-conflicts.ts does from a
// local GCD dump), on the Admin API. An admin key with admin:imports:read and admin:imports:write.
const collector = createCollectorClient({ token: process.env.COLLECTOR_ADMIN_TOKEN });
const { conflicts } = await collector.listAdminImportConflicts({ query: { status: 'open' } });
for (const conflict of conflicts) {
// Both series side by side, and what each resolution would do.
const detail = await collector.getAdminImportConflict({ path: { id: conflict.id } });
const merge = detail.impact.merge;
// A rule of your own: merge only when every issue lines up and none looks like another book.
if (!merge.known || merge.leftOut > 0 || merge.probablyDifferent.length > 0) {
console.log(`${conflict.record.title}: left for a person`);
continue;
}
const body = { action: 'merge', note: 'Every issue lines up.' } as const;
// The dry run is the resolution, rolled back: it refuses what the resolution would refuse.
const plan = await collector.resolveAdminImportConflict({
path: { id: conflict.id },
query: { dryRun: 'true' },
body,
});
const done = await collector.resolveAdminImportConflict({ path: { id: conflict.id }, body });
console.log(`${conflict.record.title}: ${plan.status} → ${done.status} (${done.seriesId})`);
}A moderator’s key working the codes queue:
import { createCollectorClient } from '@collector/sdk';
// Working the codes queue with a moderator's key (catalog:read, admin:moderation:read and
// admin:moderation:write: the only scopes a moderator's key can use).
const collector = createCollectorClient({ token: process.env.COLLECTOR_MODERATOR_TOKEN });
const { proposals } = await collector.listAdminCodeProposals({ query: { status: 'pending' } });
for (const proposal of proposals) {
// Approve a barcode onto the edition the collector's copy names, when no other edition has it;
// leave the rest for a person.
if (proposal.kind !== 'upc' || !proposal.editionId || proposal.conflicts.length > 0) continue;
const { proposal: reviewed } = await collector.reviewAdminCodeProposal({
path: { id: proposal.id },
body: { decision: 'approve', editionId: proposal.editionId },
});
console.log(`${proposal.code}: ${reviewed.status}`);
}
// Approved one by mistake? Within 7 days it can be taken back: the code is pending again and the
// edition has what it had before (409 undo_blocked if someone has changed it since).
// await collector.undoAdminCodeProposal({ path: { id }, body: { note: 'Wrong edition' } });And the editions queue (The editions queue, Added variants in the console): the variants collectors added (provisional editions) next to the ones they may duplicate. Approve one that’s a variant of its own; reject one that duplicates a match, and it’s merged into it:
import { createCollectorClient } from '@collector/sdk';
// Working the editions queue with a moderator's key (catalog:read, admin:moderation:read and
// admin:moderation:write): collectors' provisional editions next to an edition they may duplicate.
const collector = createCollectorClient({ token: process.env.COLLECTOR_MODERATOR_TOKEN });
const { data } = await collector.listAdminEditionQueue({ query: { status: 'pending', duplicates: 'true' } });
for (const item of data) {
// A rule of your own: one match, with a barcode, and the collector's edition has none of its own.
const [match, ...others] = item.matches;
if (!match || others.length > 0 || !match.upc || item.edition.upc) {
console.log(`${item.issue.label}, ${item.edition.label}: left for a person`);
continue;
}
const body = {
decision: 'reject',
intoEditionId: match.id,
note: 'The same edition, added again.',
} as const;
// The dry run is the merge, rolled back: the same changes, or the same refusal.
const plan = await collector.reviewAdminEdition({ path: { id: item.id }, query: { dryRun: 'true' }, body });
const done = await collector.reviewAdminEdition({ path: { id: item.id }, body });
console.log(`${item.issue.label}: ${JSON.stringify(plan.summary)} → merged (${done.mergeId})`);
}
// Rejected one by mistake? Within 7 days the merge is undone and the edition waits again.
// await collector.undoAdminEditionReview({ path: { id }, body: { note: 'A different printing' } });Imports and jobs
Start a Metron sync now answers the job it runs under. Follow it with Follow an import job: queued, running (progress of total), then succeeded, failed or cancelled, with its result. Import jobs lists the newest.
Cancel an import job ends a queued job at once. A running Metron sync stops at its next progress write, within a few seconds, and keeps what it imported; its job reads cancelled with what it got through. Jobs that can’t stop part-way (dump imports, enrichment, covers) answer 409 not_cancellable; cancellable on each job says which can.
import { createCollectorClient } from '@collector/sdk';
// Running a Metron sync and following it to the end, with an admin key holding admin:imports:read
// and admin:imports:write. The sync runs on the server after the answer; this only watches it.
const collector = createCollectorClient({ token: process.env.COLLECTOR_ADMIN_TOKEN });
const { job } = await collector.startAdminSync({ body: { job: 'new_releases' } });
const deadline = Date.now() + 4 * 60_000;
for (;;) {
const now = await collector.getAdminImport({ path: { id: job.id } });
if (now.status === 'succeeded' || now.status === 'failed' || now.status === 'cancelled') {
console.log(`${now.status}: ${JSON.stringify(now.result)}`);
break;
}
console.log(`${now.status}: ${now.progress} of ${now.total ?? '?'}`);
// Taking too long for this script's purpose: ask it to stop. A Metron sync stops at its next
// progress write and keeps what it imported; jobs that can't stop say so (409 not_cancellable).
if (Date.now() > deadline && now.cancellable) await collector.cancelAdminImport({ path: { id: job.id } });
await new Promise((resolve) => setTimeout(resolve, 5_000));
}Writing safely
- Idempotency-Key: every admin write takes one, and an admin key must send it (
400 idempotency_key_requiredotherwise), so a retried script can’t do a write twice. The SDK sends a fresh one on every write. Dry runs need none. - Roles need a person: Change someone’s role or access grants or removes a role only with a signed-in session. A key can disable or enable an account, never make an admin (
403 key_not_allowed). - Bulk work runs as a job: Put an imprint on many series, as a job (up to 10,000) and Decide many moderation items, as a job (up to 500) answer
202at once with where to follow the job (Follow a catalog job, Follow a moderation job): its progress, what it did and why items failed. Each item is made as its own operation would make it, audited; a cancel stops the job before its next step. Catalog jobs and Moderation jobs list them newest first, as Admin → Jobs does. - Field locks: Lock or unlock a field keeps imports from changing a value you corrected.
- The audit log: every admin change is recorded by the function that made it, and a key’s writes also by key, with the Idempotency-Key and the ids it named. Read them with Audit log, which pages back with
before.