import { randomBytes } from 'node:crypto'; import { NotFoundError, type Adapter as DbAdapter, type WhereClause } from '@superfunctions/db'; import type { Connection } from '../../types/connection.js'; import type { PlugFnConnectionGrant, PlugFnProviderEvent, PlugFnProviderInstallation, PlugFnSecretRef, PlugFnSyncCheckpoint, PlugFnSyncJob, PlugFnWebhookDelivery, PlugFnWebhookReceipt, } from '../../types/runtime.js'; import type { Workflow, WorkflowExecution } from '../../types/workflow.js'; import type { WebhookRecord } from '../webhook-storage.js'; const WEBHOOK_DELIVERY_LEASE_MS = 5 * 60 * 1000; const SYNC_JOB_LEASE_MS = 5 * 60 * 1000; export interface PlugFnStorageModelMapping { connections: string; oauthStates: string; oauthTokens: string; workflows: string; workflowExecutions: string; webhooks: string; actionLogs: string; providerInstallations: string; connectionGrants: string; webhookReceipts: string; webhookDeliveries: string; syncJobs: string; syncCheckpoints: string; providerEvents: string; secretRefs: string; } export const DEFAULT_PLUGFN_STORAGE_MODELS: PlugFnStorageModelMapping = { connections: 'plugfn_connections', oauthStates: 'plugfn_oauth_states', oauthTokens: 'plugfn_oauth_tokens', workflows: 'plugfn_workflows', workflowExecutions: 'plugfn_workflow_executions', webhooks: 'plugfn_webhooks', actionLogs: 'plugfn_action_logs', providerInstallations: 'plugfn_provider_installations', connectionGrants: 'plugfn_connection_grants', webhookReceipts: 'plugfn_webhook_receipts', webhookDeliveries: 'plugfn_webhook_deliveries', syncJobs: 'plugfn_sync_jobs', syncCheckpoints: 'plugfn_sync_checkpoints', providerEvents: 'plugfn_provider_events', secretRefs: 'plugfn_secret_refs', }; export type PlugFnRequiredModelName = | 'plugfn_connections' | 'plugfn_oauth_states' | 'plugfn_oauth_tokens' | 'plugfn_workflows' | 'plugfn_workflow_executions' | 'plugfn_webhooks' | 'plugfn_action_logs' | 'plugfn_provider_installations' | 'plugfn_connection_grants' | 'plugfn_webhook_receipts' | 'plugfn_webhook_deliveries' | 'plugfn_sync_jobs' | 'plugfn_sync_checkpoints' | 'plugfn_provider_events' | 'plugfn_secret_refs'; export const PLUGFN_REQUIRED_MODEL_NAMES: PlugFnRequiredModelName[] = [ 'plugfn_connections', 'plugfn_oauth_states', 'plugfn_oauth_tokens', 'plugfn_workflows', 'plugfn_workflow_executions', 'plugfn_webhooks', 'plugfn_action_logs', 'plugfn_provider_installations', 'plugfn_connection_grants', 'plugfn_webhook_receipts', 'plugfn_webhook_deliveries', 'plugfn_sync_jobs', 'plugfn_sync_checkpoints', 'plugfn_provider_events', 'plugfn_secret_refs', ]; export interface PlugFnDatabaseStorageAdapter { readonly database: DbAdapter; readonly models: PlugFnStorageModelMapping; createConnection(connection: Connection): Promise; getConnection(id: string): Promise; listConnections(userId: string, provider?: string): Promise; updateConnection(id: string, updates: Partial): Promise; deleteConnection(id: string): Promise; createWebhook(webhook: WebhookRecord): Promise; getWebhook(id: string): Promise; listWebhooks(provider?: string): Promise; updateWebhook(id: string, updates: Partial): Promise; deleteWebhook(id: string): Promise; createWorkflow(workflow: Workflow): Promise; getWorkflow(id: string): Promise; listWorkflows(userId?: string, status?: string): Promise; updateWorkflow(id: string, updates: Partial): Promise; deleteWorkflow(id: string): Promise; createWorkflowExecution(execution: WorkflowExecution): Promise; updateWorkflowExecution(id: string, updates: Partial): Promise; listWorkflowExecutions(workflowId: string, limit?: number): Promise; createActionLog(log: Record): Promise>; listActionLogs(filters: Record, limit?: number): Promise[]>; createProviderInstallation(installation: PlugFnProviderInstallation): Promise; getProviderInstallation(id: string): Promise; listProviderInstallations(filters?: Record): Promise; updateProviderInstallation(id: string, updates: Partial): Promise; createConnectionGrant(grant: PlugFnConnectionGrant): Promise; listConnectionGrants(connectionId: string): Promise; deleteConnectionGrant(id: string): Promise; createWebhookReceipt(receipt: PlugFnWebhookReceipt): Promise; getWebhookReceipt(id: string): Promise; findWebhookReceiptByIdempotencyKey(provider: string, idempotencyKey: string): Promise; updateWebhookReceipt(id: string, updates: Partial): Promise; createWebhookDelivery(delivery: PlugFnWebhookDelivery): Promise; updateWebhookDelivery(id: string, updates: Partial): Promise; updateClaimedWebhookDelivery(id: string, claimToken: string, updates: Partial): Promise; listWebhookDeliveries(receiptId: string): Promise; listWebhookDeliveriesForRetry(now: Date, limit?: number, leaseMs?: number): Promise; claimWebhookDeliveriesForRetry(now: Date, limit: number, workerId: string, leaseMs?: number): Promise; createSyncJob(job: PlugFnSyncJob): Promise; getSyncJob(id: string): Promise; listSyncJobs(filters?: Record, limit?: number, offset?: number): Promise; claimQueuedSyncJobs( limit: number, workerId: string, leaseMs?: number ): Promise; updateSyncJob(id: string, updates: Partial): Promise; updateClaimedSyncJob(id: string, claimToken: string, updates: Partial): Promise; upsertSyncCheckpoint(checkpoint: PlugFnSyncCheckpoint): Promise; getSyncCheckpoint(connectionId: string, resource: string): Promise; createProviderEvent(event: PlugFnProviderEvent): Promise; listProviderEvents(filters?: Record, limit?: number): Promise; upsertSecretRef(secretRef: PlugFnSecretRef): Promise; listSecretRefs(filters?: Record): Promise; } export interface PlugFnDatabaseAdapterOptions { database: DbAdapter; models?: Partial; } export function createPlugFnDatabaseAdapter( options: PlugFnDatabaseAdapterOptions ): PlugFnDatabaseStorageAdapter { return new DbBackedPlugFnDatabaseAdapter(options.database, resolvePlugFnStorageModels(options.models)); } export function ensurePlugFnDatabaseAdapter( value: DbAdapter | PlugFnDatabaseStorageAdapter, models?: Partial ): PlugFnDatabaseStorageAdapter { if (isPlugFnDatabaseStorageAdapter(value)) { return value; } return createPlugFnDatabaseAdapter({ database: value, models, }); } function isPlugFnDatabaseStorageAdapter( value: DbAdapter | PlugFnDatabaseStorageAdapter ): value is PlugFnDatabaseStorageAdapter { return ( typeof value === 'object' && value !== null && 'database' in value && 'models' in value && typeof (value as PlugFnDatabaseStorageAdapter).getConnection === 'function' ); } export function resolvePlugFnStorageModels( models?: Partial ): PlugFnStorageModelMapping { return { connections: models?.connections ?? DEFAULT_PLUGFN_STORAGE_MODELS.connections, oauthStates: models?.oauthStates ?? DEFAULT_PLUGFN_STORAGE_MODELS.oauthStates, oauthTokens: models?.oauthTokens ?? DEFAULT_PLUGFN_STORAGE_MODELS.oauthTokens, workflows: models?.workflows ?? DEFAULT_PLUGFN_STORAGE_MODELS.workflows, workflowExecutions: models?.workflowExecutions ?? DEFAULT_PLUGFN_STORAGE_MODELS.workflowExecutions, webhooks: models?.webhooks ?? DEFAULT_PLUGFN_STORAGE_MODELS.webhooks, actionLogs: models?.actionLogs ?? DEFAULT_PLUGFN_STORAGE_MODELS.actionLogs, providerInstallations: models?.providerInstallations ?? DEFAULT_PLUGFN_STORAGE_MODELS.providerInstallations, connectionGrants: models?.connectionGrants ?? DEFAULT_PLUGFN_STORAGE_MODELS.connectionGrants, webhookReceipts: models?.webhookReceipts ?? DEFAULT_PLUGFN_STORAGE_MODELS.webhookReceipts, webhookDeliveries: models?.webhookDeliveries ?? DEFAULT_PLUGFN_STORAGE_MODELS.webhookDeliveries, syncJobs: models?.syncJobs ?? DEFAULT_PLUGFN_STORAGE_MODELS.syncJobs, syncCheckpoints: models?.syncCheckpoints ?? DEFAULT_PLUGFN_STORAGE_MODELS.syncCheckpoints, providerEvents: models?.providerEvents ?? DEFAULT_PLUGFN_STORAGE_MODELS.providerEvents, secretRefs: models?.secretRefs ?? DEFAULT_PLUGFN_STORAGE_MODELS.secretRefs, }; } class DbBackedPlugFnDatabaseAdapter implements PlugFnDatabaseStorageAdapter { readonly database: DbAdapter; readonly models: PlugFnStorageModelMapping; constructor(database: DbAdapter, models: PlugFnStorageModelMapping) { this.database = database; this.models = models; } async createConnection(connection: Connection): Promise { return this.database.create({ model: this.models.connections, data: cloneRecord(connection), }); } async getConnection(id: string): Promise { return this.database.findOne({ model: this.models.connections, where: [{ field: 'id', operator: 'eq', value: id }], }); } async listConnections(userId: string, provider?: string): Promise { const where: WhereClause[] = [{ field: 'userId', operator: 'eq', value: userId }]; if (provider) { where.push({ field: 'provider', operator: 'eq', value: provider }); } return this.database.findMany({ model: this.models.connections, where, orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async updateConnection(id: string, updates: Partial): Promise { return this.database.update({ model: this.models.connections, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async deleteConnection(id: string): Promise { await this.database.delete({ model: this.models.connections, where: [{ field: 'id', operator: 'eq', value: id }], }); } async createWebhook(webhook: WebhookRecord): Promise { return this.database.create({ model: this.models.webhooks, data: cloneRecord(webhook), }); } async getWebhook(id: string): Promise { return this.database.findOne({ model: this.models.webhooks, where: [{ field: 'id', operator: 'eq', value: id }], }); } async listWebhooks(provider?: string): Promise { const where: WhereClause[] = []; if (provider) { where.push({ field: 'provider', operator: 'eq', value: provider }); } return this.database.findMany({ model: this.models.webhooks, where, orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async updateWebhook(id: string, updates: Partial): Promise { return this.database.update({ model: this.models.webhooks, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async deleteWebhook(id: string): Promise { await this.database.delete({ model: this.models.webhooks, where: [{ field: 'id', operator: 'eq', value: id }], }); } async createWorkflow(workflow: Workflow): Promise { assertWorkflowRecordPersistable(this.database, workflow); return this.database.create({ model: this.models.workflows, data: cloneWorkflowRecord(workflow), }); } async getWorkflow(id: string): Promise { return this.database.findOne({ model: this.models.workflows, where: [{ field: 'id', operator: 'eq', value: id }], }); } async listWorkflows(userId?: string, status?: string): Promise { const where: WhereClause[] = []; if (userId) { where.push({ field: 'userId', operator: 'eq', value: userId }); } if (status) { where.push({ field: 'status', operator: 'eq', value: status }); } return this.database.findMany({ model: this.models.workflows, where, orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async updateWorkflow(id: string, updates: Partial): Promise { assertWorkflowRecordPersistable(this.database, updates); return this.database.update({ model: this.models.workflows, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneWorkflowRecord(updates), }); } async deleteWorkflow(id: string): Promise { await this.database.delete({ model: this.models.workflows, where: [{ field: 'id', operator: 'eq', value: id }], }); } async createWorkflowExecution(execution: WorkflowExecution): Promise { return this.database.create({ model: this.models.workflowExecutions, data: cloneRecord(execution), }); } async updateWorkflowExecution( id: string, updates: Partial ): Promise { return this.database.update({ model: this.models.workflowExecutions, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async listWorkflowExecutions(workflowId: string, limit = 50): Promise { return this.database.findMany({ model: this.models.workflowExecutions, where: [{ field: 'workflowId', operator: 'eq', value: workflowId }], orderBy: [{ field: 'startedAt', direction: 'desc' }], limit, }); } async createActionLog(log: Record): Promise> { return this.database.create>({ model: this.models.actionLogs, data: cloneRecord(log), }); } async listActionLogs( filters: Record, limit = 100 ): Promise[]> { const where: WhereClause[] = []; for (const [field, value] of Object.entries(filters)) { if (value === undefined) { continue; } where.push({ field, operator: 'eq', value }); } return this.database.findMany>({ model: this.models.actionLogs, where, orderBy: [{ field: 'executedAt', direction: 'desc' }], limit, }); } async createProviderInstallation( installation: PlugFnProviderInstallation ): Promise { return this.database.create({ model: this.models.providerInstallations, data: cloneRecord(installation), }); } async getProviderInstallation(id: string): Promise { return this.database.findOne({ model: this.models.providerInstallations, where: [{ field: 'id', operator: 'eq', value: id }], }); } async listProviderInstallations( filters: Record = {} ): Promise { return this.database.findMany({ model: this.models.providerInstallations, where: toWhereClauses(filters), orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async updateProviderInstallation( id: string, updates: Partial ): Promise { return this.database.update({ model: this.models.providerInstallations, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async createConnectionGrant(grant: PlugFnConnectionGrant): Promise { return this.database.create({ model: this.models.connectionGrants, data: cloneRecord(grant), }); } async listConnectionGrants(connectionId: string): Promise { return this.database.findMany({ model: this.models.connectionGrants, where: [{ field: 'connectionId', operator: 'eq', value: connectionId }], orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async deleteConnectionGrant(id: string): Promise { await this.database.delete({ model: this.models.connectionGrants, where: [{ field: 'id', operator: 'eq', value: id }], }); } async createWebhookReceipt(receipt: PlugFnWebhookReceipt): Promise { return this.database.create({ model: this.models.webhookReceipts, data: cloneRecord(receipt), }); } async getWebhookReceipt(id: string): Promise { return this.database.findOne({ model: this.models.webhookReceipts, where: [{ field: 'id', operator: 'eq', value: id }], }); } async findWebhookReceiptByIdempotencyKey( provider: string, idempotencyKey: string ): Promise { return this.database.findOne({ model: this.models.webhookReceipts, where: [ { field: 'provider', operator: 'eq', value: provider }, { field: 'idempotencyKey', operator: 'eq', value: idempotencyKey }, ], }); } async updateWebhookReceipt( id: string, updates: Partial ): Promise { return this.database.update({ model: this.models.webhookReceipts, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async createWebhookDelivery(delivery: PlugFnWebhookDelivery): Promise { return this.database.create({ model: this.models.webhookDeliveries, data: cloneRecord(delivery), }); } async updateWebhookDelivery( id: string, updates: Partial ): Promise { return this.database.update({ model: this.models.webhookDeliveries, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async updateClaimedWebhookDelivery( id: string, claimToken: string, updates: Partial ): Promise { try { return await this.database.update({ model: this.models.webhookDeliveries, where: [ { field: 'id', operator: 'eq', value: id }, { field: 'status', operator: 'eq', value: 'running' }, { field: 'claimToken', operator: 'eq', value: claimToken }, ], data: cloneRecord(updates), }); } catch (error) { if (error instanceof NotFoundError) { return null; } throw error; } } async listWebhookDeliveries(receiptId: string): Promise { return this.database.findMany({ model: this.models.webhookDeliveries, where: [{ field: 'receiptId', operator: 'eq', value: receiptId }], orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } async listWebhookDeliveriesForRetry( now: Date, limit = 100, leaseMs = WEBHOOK_DELIVERY_LEASE_MS ): Promise { const pending = await this.database.findMany({ model: this.models.webhookDeliveries, where: [{ field: 'status', operator: 'eq', value: 'pending' }], orderBy: [{ field: 'createdAt', direction: 'asc' }], limit, }); const failed = await this.database.findMany({ model: this.models.webhookDeliveries, where: [ { field: 'status', operator: 'eq', value: 'failed' }, { field: 'nextAttemptAt', operator: 'lte', value: now }, ], orderBy: [{ field: 'updatedAt', direction: 'asc' }], limit, }); const staleBefore = new Date(now.getTime() - leaseMs); const staleRunning = await this.database.findMany({ model: this.models.webhookDeliveries, where: [ { field: 'status', operator: 'eq', value: 'running' }, { field: 'updatedAt', operator: 'lte', value: staleBefore }, ], orderBy: [{ field: 'updatedAt', direction: 'asc' }], limit, }); return [...pending, ...failed, ...staleRunning] .filter((delivery) => !delivery.nextAttemptAt || toTime(delivery.nextAttemptAt) <= now.getTime()) .sort((left, right) => { const leftTime = toTime(left.nextAttemptAt ?? left.createdAt); const rightTime = toTime(right.nextAttemptAt ?? right.createdAt); return leftTime - rightTime; }) .slice(0, limit); } async claimWebhookDeliveriesForRetry( now: Date, limit: number, workerId: string, leaseMs = WEBHOOK_DELIVERY_LEASE_MS ): Promise { const candidates = await this.listWebhookDeliveriesForRetry(now, limit, leaseMs); const claimed: PlugFnWebhookDelivery[] = []; const claimedAt = new Date(); for (const delivery of candidates) { const where: WhereClause[] = [ { field: 'id', operator: 'eq', value: delivery.id }, { field: 'status', operator: 'eq', value: delivery.status }, ]; if (delivery.nextAttemptAt) { where.push({ field: 'nextAttemptAt', operator: 'lte', value: now }); } if (delivery.status === 'running') { where.push({ field: 'updatedAt', operator: 'lte', value: new Date(now.getTime() - leaseMs), }); } try { const claimToken = `${workerId}:${delivery.id}:${claimedAt.getTime()}`; const updated = await this.database.update({ model: this.models.webhookDeliveries, where, data: cloneRecord({ status: 'running', claimToken, attempts: delivery.attempts + 1, metadata: claimMetadata(delivery.metadata, workerId, claimedAt), updatedAt: claimedAt, }), }); if (updated?.status === 'running') { claimed.push(updated); } } catch { // Another worker claimed or updated the delivery first. } } return claimed; } async createSyncJob(job: PlugFnSyncJob): Promise { return this.database.create({ model: this.models.syncJobs, data: cloneRecord(job), }); } async getSyncJob(id: string): Promise { return this.database.findOne({ model: this.models.syncJobs, where: [{ field: 'id', operator: 'eq', value: id }], }); } async listSyncJobs( filters: Record = {}, limit = 100, offset = 0 ): Promise { return this.database.findMany({ model: this.models.syncJobs, where: toWhereClauses(filters), orderBy: [{ field: 'createdAt', direction: 'desc' }, { field: 'id', direction: 'desc' }], limit, offset, }); } async claimQueuedSyncJobs( limit: number, workerId: string, leaseMs = SYNC_JOB_LEASE_MS ): Promise { const claimedAt = new Date(); const staleBefore = new Date(claimedAt.getTime() - leaseMs); const [queued, abandoned] = await Promise.all([ this.database.findMany({ model: this.models.syncJobs, where: [{ field: 'status', operator: 'eq', value: 'queued' }], orderBy: [{ field: 'createdAt', direction: 'asc' }], limit, }), this.database.findMany({ model: this.models.syncJobs, where: [ { field: 'status', operator: 'eq', value: 'running' }, { field: 'updatedAt', operator: 'lte', value: staleBefore }, ], orderBy: [{ field: 'createdAt', direction: 'asc' }], limit, }), ]); const candidates = [...queued, ...abandoned] .sort((left, right) => toTime(left.createdAt) - toTime(right.createdAt)) .slice(0, limit); const claimed: PlugFnSyncJob[] = []; for (const job of candidates) { try { const where: WhereClause[] = [ { field: 'id', operator: 'eq', value: job.id }, { field: 'status', operator: 'eq', value: job.status }, ]; if (job.status === 'running') { where.push({ field: 'updatedAt', operator: 'lte', value: staleBefore }); } const claimToken = `claim_${randomBytes(24).toString('hex')}`; const updated = await this.database.update({ model: this.models.syncJobs, where, data: cloneRecord({ status: 'running', claimToken, metadata: claimMetadata(job.metadata, workerId, claimedAt), updatedAt: claimedAt, }), }); if (updated?.status === 'running') { claimed.push(updated); } } catch { // Another worker claimed or updated the job first. } } return claimed; } async updateSyncJob(id: string, updates: Partial): Promise { return this.database.update({ model: this.models.syncJobs, where: [{ field: 'id', operator: 'eq', value: id }], data: cloneRecord(updates), }); } async updateClaimedSyncJob( id: string, claimToken: string, updates: Partial ): Promise { try { return await this.database.update({ model: this.models.syncJobs, where: [ { field: 'id', operator: 'eq', value: id }, { field: 'status', operator: 'eq', value: 'running' }, { field: 'claimToken', operator: 'eq', value: claimToken }, ], data: cloneRecord(updates), }); } catch (error) { if (error instanceof NotFoundError) return null; throw error; } } async upsertSyncCheckpoint( checkpoint: PlugFnSyncCheckpoint ): Promise { return this.database.upsert({ model: this.models.syncCheckpoints, where: [ { field: 'connectionId', operator: 'eq', value: checkpoint.connectionId }, { field: 'resource', operator: 'eq', value: checkpoint.resource }, ], create: cloneRecord(checkpoint), update: cloneRecord({ provider: checkpoint.provider, checkpoint: checkpoint.checkpoint, updatedAt: checkpoint.updatedAt, }), conflictTarget: ['connectionId', 'resource'], }); } async getSyncCheckpoint( connectionId: string, resource: string ): Promise { return this.database.findOne({ model: this.models.syncCheckpoints, where: [ { field: 'connectionId', operator: 'eq', value: connectionId }, { field: 'resource', operator: 'eq', value: resource }, ], }); } async createProviderEvent(event: PlugFnProviderEvent): Promise { return this.database.create({ model: this.models.providerEvents, data: cloneRecord(event), }); } async listProviderEvents( filters: Record = {}, limit = 100 ): Promise { return this.database.findMany({ model: this.models.providerEvents, where: toWhereClauses(filters), orderBy: [{ field: 'createdAt', direction: 'desc' }], limit, }); } async upsertSecretRef(secretRef: PlugFnSecretRef): Promise { return this.database.upsert({ model: this.models.secretRefs, where: [{ field: 'id', operator: 'eq', value: secretRef.id }], create: cloneRecord(secretRef), update: cloneRecord({ keyRef: secretRef.keyRef, metadata: secretRef.metadata, updatedAt: secretRef.updatedAt, }), conflictTarget: 'id', }); } async listSecretRefs(filters: Record = {}): Promise { return this.database.findMany({ model: this.models.secretRefs, where: toWhereClauses(filters), orderBy: [{ field: 'createdAt', direction: 'desc' }], }); } } function cloneRecord(value: T): T { if (value === undefined || value === null) { return value; } if (typeof structuredClone === 'function') { return structuredClone(value); } return JSON.parse(JSON.stringify(value)) as T; } function cloneWorkflowRecord(value: T, seen = new WeakMap()): T { if (typeof value === 'function' || value === undefined || value === null) { return value; } if (value instanceof Date) { return new Date(value.getTime()) as T; } if (Array.isArray(value)) { const existing = seen.get(value); if (existing) { return existing as T; } const clone: unknown[] = []; seen.set(value, clone); for (const entry of value) { clone.push(cloneWorkflowRecord(entry, seen)); } return clone as T; } if (typeof value === 'object') { const existing = seen.get(value); if (existing) { return existing as T; } const prototype = Object.getPrototypeOf(value); if (prototype !== Object.prototype && prototype !== null) { return cloneRecord(value); } const clone: Record = {}; seen.set(value, clone); for (const [key, entry] of Object.entries(value)) { clone[key] = cloneWorkflowRecord(entry, seen); } return clone as T; } return value; } function assertWorkflowRecordPersistable(database: DbAdapter, value: unknown): void { if (database.id === 'memory') { return; } const ancestors = new WeakSet(); const visit = (entry: unknown, path: string): void => { if (typeof entry === 'function') { throw new TypeError( `Persistent PlugFn workflow storage cannot serialize callback at ${path}; use a memory adapter for executable callback workflows` ); } if (typeof entry === 'bigint' || typeof entry === 'symbol') { throw new TypeError(`Persistent PlugFn workflow storage cannot serialize ${typeof entry} at ${path}`); } if (entry === null || typeof entry !== 'object' || entry instanceof Date) { return; } if (!Array.isArray(entry)) { const prototype = Object.getPrototypeOf(entry); if (prototype !== Object.prototype && prototype !== null) { const typeName = entry.constructor?.name ?? 'object'; throw new TypeError( `Persistent PlugFn workflow storage cannot serialize ${typeName} at ${path}; use plain JSON-compatible objects` ); } } if (ancestors.has(entry)) { throw new TypeError(`Persistent PlugFn workflow storage cannot serialize cyclic value at ${path}`); } ancestors.add(entry); if (Array.isArray(entry)) { entry.forEach((item, index) => visit(item, `${path}[${index}]`)); } else { for (const [key, item] of Object.entries(entry)) { visit(item, `${path}.${key}`); } } ancestors.delete(entry); }; visit(value, 'workflow'); } function toWhereClauses(filters: Record): WhereClause[] { const where: WhereClause[] = []; for (const [field, value] of Object.entries(filters)) { if (value === undefined) { continue; } where.push({ field, operator: 'eq', value }); } return where; } function claimMetadata( metadata: Record | undefined, workerId: string, claimedAt: Date ): Record { return { ...(metadata ?? {}), workerClaim: { workerId, claimedAt: claimedAt.toISOString(), }, }; } function toTime(value: Date | string): number { return value instanceof Date ? value.getTime() : new Date(value).getTime(); }