Sample data in tests, prompts and UI placeholders uses Alex Morgan instead of the maintainer's name; decision attributions say "owner". Personal details in two test fixtures are replaced. Local paths (D:/Projects/...) and paths into the maintainer's planning repository are reworded. Clone and install URLs in CONTRIBUTING.md and the getting started guide use placeholders until the public repository location is decided (Q9). The Benchmarks page no longer names the maintainer's hive-mind repository, and the upstream fixes log names the main Waggle repository instead of an internal git host.
237 lines
7.5 KiB
TypeScript
237 lines
7.5 KiB
TypeScript
/**
|
|
* Cron REST API Routes — CRUD + manual trigger for Solo cron schedules.
|
|
*
|
|
* Endpoints:
|
|
* POST /api/cron — create schedule
|
|
* GET /api/cron — list all schedules
|
|
* GET /api/cron/:id — get one schedule
|
|
* PATCH /api/cron/:id — update schedule
|
|
* DELETE /api/cron/:id — delete schedule
|
|
* POST /api/cron/:id/trigger — manually trigger a schedule
|
|
*
|
|
* Part of Wave 1.1 — Solo Cron Service.
|
|
*/
|
|
|
|
import type { FastifyPluginAsync } from 'fastify';
|
|
import type { CronSchedule, CronJobType } from '@waggle/core';
|
|
import { emitNotification } from './notifications.js';
|
|
|
|
/**
|
|
* Parse a stored job_config string, degrading gracefully on corrupt/legacy rows.
|
|
*
|
|
* R1-008: GET /api/cron maps every row through toResponse(). A single row with
|
|
* invalid JSON in job_config must not throw and 500 the entire list — that would
|
|
* lock the user out of ALL their schedules. On parse failure we fall back to an
|
|
* empty object and log a warning (never silently swallowed).
|
|
*/
|
|
function parseJobConfig(scheduleId: number, raw: string): Record<string, unknown> {
|
|
try {
|
|
return JSON.parse(raw) as Record<string, unknown>;
|
|
} catch (err) {
|
|
console.warn(
|
|
`[waggle:cron] corrupt job_config for schedule ${scheduleId}; falling back to {}: ${
|
|
err instanceof Error ? err.message : String(err)
|
|
}`,
|
|
);
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function clearAutoDisabled(config: Record<string, unknown>): Record<string, unknown> {
|
|
const cleaned = { ...config };
|
|
delete cleaned.auto_disabled;
|
|
return cleaned;
|
|
}
|
|
|
|
/** Convert DB snake_case CronSchedule to API camelCase response. */
|
|
function toResponse(s: CronSchedule) {
|
|
return {
|
|
id: s.id,
|
|
name: s.name,
|
|
cronExpr: s.cron_expr,
|
|
jobType: s.job_type,
|
|
jobConfig: parseJobConfig(s.id, s.job_config),
|
|
workspaceId: s.workspace_id,
|
|
enabled: s.enabled === 1,
|
|
lastRunAt: s.last_run_at,
|
|
nextRunAt: s.next_run_at,
|
|
createdAt: s.created_at,
|
|
};
|
|
}
|
|
|
|
export const cronRoutes: FastifyPluginAsync = async (server) => {
|
|
// POST /api/cron — create a new schedule
|
|
server.post<{
|
|
Body: {
|
|
name: string;
|
|
cronExpr: string;
|
|
jobType: CronJobType;
|
|
jobConfig?: Record<string, unknown>;
|
|
workspaceId?: string;
|
|
enabled?: boolean;
|
|
};
|
|
}>('/api/cron', async (request, reply) => {
|
|
const { name, cronExpr, jobType, jobConfig, workspaceId, enabled } = request.body ?? {};
|
|
if (!name || !cronExpr || !jobType) {
|
|
return reply.status(400).send({ error: 'name, cronExpr, and jobType are required' });
|
|
}
|
|
|
|
// F30: Normalize "global" to "*" for cross-workspace cron jobs
|
|
const normalizedWorkspaceId = workspaceId === 'global' ? '*' : workspaceId;
|
|
|
|
try {
|
|
const schedule = server.cronStore.create({
|
|
name,
|
|
cronExpr,
|
|
jobType,
|
|
jobConfig,
|
|
workspaceId: normalizedWorkspaceId,
|
|
enabled,
|
|
});
|
|
return toResponse(schedule);
|
|
} catch (err) {
|
|
return reply.status(400).send({
|
|
error: err instanceof Error ? err.message : 'Failed to create schedule',
|
|
});
|
|
}
|
|
});
|
|
|
|
// GET /api/cron — list all schedules
|
|
server.get('/api/cron', async () => {
|
|
const schedules = server.cronStore.list();
|
|
return { schedules: schedules.map(toResponse), count: schedules.length };
|
|
});
|
|
|
|
// GET /api/cron/:id — get one schedule
|
|
server.get<{
|
|
Params: { id: string };
|
|
}>('/api/cron/:id', async (request, reply) => {
|
|
const id = parseInt(request.params.id, 10);
|
|
if (isNaN(id)) {
|
|
return reply.status(400).send({ error: 'Invalid ID' });
|
|
}
|
|
const schedule = server.cronStore.getById(id);
|
|
if (!schedule) {
|
|
return reply.status(404).send({ error: 'Schedule not found' });
|
|
}
|
|
return toResponse(schedule);
|
|
});
|
|
|
|
// PATCH /api/cron/:id — update a schedule
|
|
server.patch<{
|
|
Params: { id: string };
|
|
Body: {
|
|
name?: string;
|
|
cronExpr?: string;
|
|
jobConfig?: Record<string, unknown>;
|
|
workspaceId?: string;
|
|
enabled?: boolean;
|
|
};
|
|
}>('/api/cron/:id', async (request, reply) => {
|
|
const id = parseInt(request.params.id, 10);
|
|
if (isNaN(id)) {
|
|
return reply.status(400).send({ error: 'Invalid ID' });
|
|
}
|
|
|
|
const existing = server.cronStore.getById(id);
|
|
if (!existing) {
|
|
return reply.status(404).send({ error: 'Schedule not found' });
|
|
}
|
|
|
|
try {
|
|
const changes = request.body ?? {};
|
|
const enabling = changes.enabled === true;
|
|
server.cronStore.update(id, enabling
|
|
? {
|
|
...changes,
|
|
jobConfig: clearAutoDisabled(
|
|
changes.jobConfig ?? parseJobConfig(existing.id, existing.job_config),
|
|
),
|
|
}
|
|
: changes);
|
|
if (enabling) server.scheduler.resetFailure(id);
|
|
const updated = server.cronStore.getById(id)!;
|
|
return toResponse(updated);
|
|
} catch (err) {
|
|
return reply.status(400).send({
|
|
error: err instanceof Error ? err.message : 'Failed to update schedule',
|
|
});
|
|
}
|
|
});
|
|
|
|
// DELETE /api/cron/:id — delete a schedule
|
|
server.delete<{
|
|
Params: { id: string };
|
|
}>('/api/cron/:id', async (request, reply) => {
|
|
const id = parseInt(request.params.id, 10);
|
|
if (isNaN(id)) {
|
|
return reply.status(400).send({ error: 'Invalid ID' });
|
|
}
|
|
|
|
const existing = server.cronStore.getById(id);
|
|
if (!existing) {
|
|
return reply.status(404).send({ error: 'Schedule not found' });
|
|
}
|
|
|
|
server.cronStore.delete(id);
|
|
return { ok: true, id };
|
|
});
|
|
|
|
// POST /api/cron/:id/trigger — manually trigger a schedule
|
|
//
|
|
// M-43 / P25: triggering a disabled job auto-enables it before
|
|
// execution. Rationale (owner, 2026-04-19): if the user is reaching
|
|
// for "Run now" they want the job running, and leaving it disabled
|
|
// after manual trigger produces the confusing "toggle stays off"
|
|
// effect the PDF-E2E issue list flagged. The response includes the
|
|
// post-trigger job state so clients can sync without a refetch.
|
|
server.post<{
|
|
Params: { id: string };
|
|
}>('/api/cron/:id/trigger', async (request, reply) => {
|
|
const id = parseInt(request.params.id, 10);
|
|
if (isNaN(id)) {
|
|
return reply.status(400).send({ error: 'Invalid ID' });
|
|
}
|
|
|
|
const existing = server.cronStore.getById(id);
|
|
if (!existing) {
|
|
return reply.status(404).send({ error: 'Schedule not found' });
|
|
}
|
|
|
|
// Auto-enable if disabled — do this BEFORE executeJob so the scheduler
|
|
// sees the current semantic state and any downstream side effects run
|
|
// against the enabled schedule row.
|
|
const wasDisabled = existing.enabled !== 1;
|
|
const schedule = wasDisabled
|
|
? server.cronStore.update(id, {
|
|
enabled: true,
|
|
jobConfig: clearAutoDisabled(parseJobConfig(existing.id, existing.job_config)),
|
|
})
|
|
: existing;
|
|
if (wasDisabled) server.scheduler.resetFailure(id);
|
|
|
|
try {
|
|
// W5.11: Actually execute the job handler (not just mark as run)
|
|
await server.scheduler.executeJob(schedule);
|
|
const updated = server.cronStore.getById(id);
|
|
emitNotification(server, {
|
|
title: 'Routine complete',
|
|
body: `${schedule.name || 'Scheduled task'} finished`,
|
|
category: 'cron',
|
|
actionUrl: '/settings/mission-control',
|
|
});
|
|
return {
|
|
triggered: true,
|
|
id,
|
|
nextRunAt: updated?.next_run_at,
|
|
autoEnabled: wasDisabled,
|
|
schedule: updated ? toResponse(updated) : undefined,
|
|
};
|
|
} catch (err) {
|
|
return reply.status(500).send({
|
|
error: err instanceof Error ? err.message : 'Trigger failed',
|
|
});
|
|
}
|
|
});
|
|
};
|