Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/app/migrations/0007_job_edit_deliveries.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
CREATE TABLE app.job_edit_deliveries (
tenant_id uuid NOT NULL,
event_id uuid NOT NULL,
trigger_id uuid NOT NULL,
source_job_id uuid NOT NULL,
edited_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, event_id, trigger_id),
FOREIGN KEY (tenant_id, trigger_id) REFERENCES app.triggers(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, source_job_id) REFERENCES app.jobs(tenant_id, id) ON DELETE CASCADE
);
CREATE INDEX job_edit_deliveries_pending ON app.job_edit_deliveries(edited_at, event_id);

CREATE OR REPLACE FUNCTION app.next_wake_at() RETURNS timestamptz LANGUAGE sql STABLE AS $$
SELECT min(candidate) FROM (
SELECT min(not_before) candidate FROM app.wake_hints
UNION ALL SELECT min(d.edited_at) FROM app.job_edit_deliveries d
JOIN app.triggers t ON t.tenant_id=d.tenant_id AND t.id=d.trigger_id
JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id
WHERE t.enabled AND t.removed_at IS NULL AND j.enabled
AND t.config->'sourceJobIds' ? d.source_job_id::text AND t.config->'states' ? 'edited'
UNION ALL SELECT min(next_run_at) FROM app.schedule_state
UNION ALL SELECT min(next_attempt_at) FROM app.pending_verifications
UNION ALL SELECT min(launch_lease_expires_at) FROM app.job_runs WHERE state='starting'
UNION ALL SELECT min(next_poll_at) FROM app.job_runs WHERE state IN ('running','blocked','stopping')
UNION ALL SELECT min(cleanup_next_at) FROM app.runs WHERE NOT vm_cleanup_complete
) wakes
$$;

2 changes: 1 addition & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const triggerSchema = z.discriminatedUnion("kind", [
}).strict() }).strict(),
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(),
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("jobLifecycle"), enabled: z.boolean().default(true), config: z.object({
sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped"])).min(1),
sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped", "edited"])).min(1),
}).strict() }).strict(),
]);
export const jobInputSchema = z.object({
Expand Down
9 changes: 7 additions & 2 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ export class ApiService {
async updateJob(jobId: string, input: JobInput) {
await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found");
const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId }));
return this.presentJob(await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }));
const updated = await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() });
await this.wakeScheduler();
return this.presentJob(updated);
}
async deleteJob(jobId: string) {
await this.authorize("flows:write");
Expand All @@ -121,7 +123,10 @@ export class ApiService {
if (!await repository.delete(jobId)) throw new ServiceError(404, "not_found", "Job not found");
return { id: jobId, deleted: true };
}
async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, enabled }; }
private async wakeScheduler() {
if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" });
}
async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; }
async invokeJob(jobId: string, input: ManualInvocationInput) {
await this.authorize("runs:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found");
const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled");
Expand Down
21 changes: 20 additions & 1 deletion packages/app/src/postgres/automation-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { invokeCustomHandler } from "../custom-handler";
/** Claims durable automatic signals in PostgreSQL. The alarm DO is only its clock. */
export class AutomationScheduler {
constructor(private database: Database, private env: Env) {}
async process(): Promise<void> { await this.githubVerifications(); await this.schedules(); await this.lifecycle(); }
async process(): Promise<void> { await this.githubVerifications(); await this.schedules(); await this.jobEdits(); await this.lifecycle(); }
private repository(tenantId: string) { return new PostgresJobRepository(this.database, tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); }
private async schedules() {
for (let count = 0; count < 50; count++) {
Expand All @@ -29,6 +29,25 @@ export class AutomationScheduler {
await service.invoke(due.job_id, { source: "schedule", triggerId: due.trigger_id, claimKey: `schedule:${due.trigger_id}:${occurredAt}`, context: { [due.slug]: occurrence }, occurrence });
}
}
private async jobEdits() {
const pending = await this.database.pool.query<any>(`SELECT d.*,t.job_id,t.slug FROM app.job_edit_deliveries d
JOIN app.triggers t ON t.tenant_id=d.tenant_id AND t.id=d.trigger_id
JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id
WHERE t.enabled AND t.removed_at IS NULL AND j.enabled
AND t.config->'sourceJobIds' ? d.source_job_id::text AND t.config->'states' ? 'edited'
ORDER BY d.edited_at,d.event_id LIMIT 100`);
for (const row of pending.rows) {
const context = { source_job_id: row.source_job_id, event: "edited", edited_at: row.edited_at.toISOString() };
// Acknowledge only after invocation succeeds. Retrying after a crash uses
// the same claim key and returns the existing run.
await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, {
source: "jobLifecycle", triggerId: row.trigger_id, claimKey: `job-edited:${row.trigger_id}:${row.event_id}`,
context: { [row.slug]: context }, occurrence: { occurredAt: context.edited_at, externalId: row.event_id, metadata: context },
});
await this.database.pool.query("DELETE FROM app.job_edit_deliveries WHERE tenant_id=$1 AND event_id=$2 AND trigger_id=$3", [row.tenant_id, row.event_id, row.trigger_id]);
}
}

private async lifecycle() {
const rows = await this.database.pool.query<any>(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,t.config,r.id source_run_id,r.job_id source_job_id,r.state,r.updated_at FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id JOIN app.runs r ON r.tenant_id=t.tenant_id AND r.job_id=(t.config->>'sourceJobId')::uuid LEFT JOIN app.lifecycle_deliveries d ON d.tenant_id=t.tenant_id AND d.trigger_id=t.id AND d.source_run_id=r.id AND d.terminal_state=r.state WHERE t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled AND r.state IN ('succeeded','failed','stopped') AND d.source_run_id IS NULL ORDER BY r.updated_at LIMIT 100`);
for (const row of rows.rows) {
Expand Down
16 changes: 15 additions & 1 deletion packages/app/src/postgres/job-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Invocation, Job, JobRepository, JobRun, Trigger } from "../job-dom
import type { Database, DatabaseClient } from "./database";
import { nextOccurrence, validateScheduleConfig } from "../schedule";
import { and, eq, isNull, sql } from "drizzle-orm";
import { invocations, jobs, lifecycleDeliveries, pendingVerifications, scheduleState, triggers } from "./schema";
import { invocations, jobs, jobEditDeliveries, lifecycleDeliveries, pendingVerifications, scheduleState, triggers } from "./schema";

type Crypt = (value: string) => Promise<string>;
type JobRow = typeof jobs.$inferSelect;
Expand Down Expand Up @@ -44,6 +44,7 @@ export class PostgresJobRepository implements JobRepository {
const existing: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, job.id), isNull(triggers.removedAt))).orderBy(triggers.position);
const [row] = await tx.update(jobs).set({ name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, updatedAt: new Date(job.updatedAt) }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).returning();
await this.reconcileTriggers(tx, job, existing);
await this.recordEdit(tx, job.id, job.updatedAt);
return this.mapped(row!, tx);
});
}
Expand All @@ -54,16 +55,29 @@ export class PostgresJobRepository implements JobRepository {
if (!job) return false;
const schedules: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, id), eq(triggers.kind, "schedule"), isNull(triggers.removedAt)));
for (const trigger of schedules) await tx.update(scheduleState).set({ nextRunAt: enabled && trigger.enabled ? nextOccurrence(validateScheduleConfig(trigger.config), new Date()) : null }).where(and(eq(scheduleState.tenantId, this.tenantId), eq(scheduleState.triggerId, trigger.id)));
await this.recordEdit(tx, id, changedAt);
return true;
});
}

private async recordEdit(tx: any, sourceJobId: string, editedAt: string): Promise<void> {
// Snapshot matching subscribers with the edit, so later subscriptions cannot
// replay old edits. The outbox commits or rolls back with the job update.
await tx.execute(sql`INSERT INTO app.job_edit_deliveries(tenant_id,event_id,trigger_id,source_job_id,edited_at)
SELECT t.tenant_id,${crypto.randomUUID()}::uuid,t.id,${sourceJobId}::uuid,${editedAt}::timestamptz
FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id
WHERE t.tenant_id=${this.tenantId}::uuid AND t.job_id<>${sourceJobId}::uuid
AND t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled
AND t.config->'sourceJobIds' ? ${sourceJobId} AND t.config->'states' ? 'edited'`);
}

private async reconcileTriggers(tx: any, job: Job, existing: TriggerRow[]): Promise<void> {
const desiredIds = new Set(job.triggers.map(trigger => trigger.id));
for (const old of existing.filter(trigger => !desiredIds.has(trigger.id))) {
const referenced = await tx.select({ value: sql<number>`1` }).from(invocations).where(and(eq(invocations.tenantId, this.tenantId), eq(invocations.triggerId, old.id))).limit(1)
.then((rows: unknown[]) => rows.length > 0) || await tx.select({ value: sql<number>`1` }).from(lifecycleDeliveries).where(and(eq(lifecycleDeliveries.tenantId, this.tenantId), eq(lifecycleDeliveries.triggerId, old.id))).limit(1).then((rows: unknown[]) => rows.length > 0)
|| await tx.select({ value: sql<number>`1` }).from(pendingVerifications).where(and(eq(pendingVerifications.tenantId, this.tenantId), eq(pendingVerifications.triggerId, old.id))).limit(1).then((rows: unknown[]) => rows.length > 0);
await tx.delete(jobEditDeliveries).where(and(eq(jobEditDeliveries.tenantId, this.tenantId), eq(jobEditDeliveries.triggerId, old.id)));
if (referenced) await tx.update(triggers).set({ enabled: false, removedAt: new Date(job.updatedAt), updatedAt: new Date(job.updatedAt) }).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.id, old.id)));
else await tx.delete(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.id, old.id)));
await tx.delete(scheduleState).where(and(eq(scheduleState.tenantId, this.tenantId), eq(scheduleState.triggerId, old.id)));
Expand Down
5 changes: 4 additions & 1 deletion packages/app/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ export const activeClaims = app.table("active_claims", { tenantId: uuid("tenant_

export const scheduleState = app.table("schedule_state", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), jobId: uuid("job_id").notNull(), nextRunAt: timestamp("next_run_at", { withTimezone: true }), lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("schedules_due").on(t.nextRunAt).where(sql`${t.nextRunAt} is not null`)]);
export const automaticWakes = app.table("automatic_wakes", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), trailingPending: boolean("trailing_pending").notNull().default(false), summary: jsonb("summary").$type<Record<string, unknown>>().notNull().default({}), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.jobId] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade")]);
export const jobEditDeliveries = app.table("job_edit_deliveries", {
tenantId: uuid("tenant_id").notNull(), eventId: uuid("event_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), editedAt: timestamp("edited_at", { withTimezone: true }).notNull(),
}, t => [primaryKey({ columns: [t.tenantId, t.eventId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_edit_deliveries_pending").on(t.editedAt, t.eventId)]);
export const lifecycleDeliveries = app.table("lifecycle_deliveries", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceRunId: uuid("source_run_id").notNull(), terminalState: text("terminal_state").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.triggerId, t.sourceRunId, t.terminalState] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceRunId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]);
export const jobEvents = app.table("job_events", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_events_by_job").on(t.tenantId, t.jobId, t.receivedAt)]);
export const webhookDeliveries = app.table("webhook_deliveries", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), eventType: text("event_type").notNull().default("unknown"), eventAction: text("event_action").notNull().default("unknown"), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.provider, t.deliveryId)]);
Expand Down Expand Up @@ -97,7 +100,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({
export const databaseSchema = {
schemaMigrations, tenants, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens,
connections, githubInstallations, githubSetupStates, jobs, triggers, invocations, jobRuns, runs, runArtifacts,
runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEvents,
runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents,
webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks,
tenantRelations, jobRelations, triggerRelations, invocationRelations, runRelations,
};
4 changes: 3 additions & 1 deletion packages/app/src/trigger-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ export const triggerContextCatalog: Record<string, ContextPath[]> = {
{ path: "exceptions", type: "array", description: "Sanitized exception records." },
],
jobLifecycle: [
{ path: "source_job_id", type: "string", description: "Job whose run reached a final state." },
{ path: "event", type: "string", description: "Event name: edited for a job edit." },
{ path: "edited_at", type: "string", description: "Job save timestamp for an edited event (ISO 8601)." },
{ path: "source_job_id", type: "string", description: "Job that was edited or whose run reached a final state." },
{ path: "source_run_id", type: "string", description: "Run that reached a final state." },
{ path: "final_state", type: "string", description: "Observed final state: succeeded, failed, or stopped." },
{ path: "transitioned_at", type: "string", description: "State transition as an ISO 8601 timestamp." },
Expand Down
Loading
Loading