|
| 1 | +import type { ActionArgs } from "@remix-run/server-runtime"; |
| 2 | +import { json } from "@remix-run/server-runtime"; |
| 3 | +import { PrismaErrorSchema } from "~/db.server"; |
| 4 | +import { z } from "zod"; |
| 5 | +import { authenticateApiRequest } from "~/services/apiAuth.server"; |
| 6 | +import { CancelRunService } from "~/services/runs/cancelRun.server"; |
| 7 | +import { ApiRunPresenter } from "~/presenters/ApiRunPresenter.server"; |
| 8 | + |
| 9 | +const ParamsSchema = z.object({ |
| 10 | + runId: z.string(), |
| 11 | +}); |
| 12 | + |
| 13 | +export async function action({ request, params }: ActionArgs) { |
| 14 | + // Ensure this is a POST request |
| 15 | + if (request.method.toUpperCase() !== "POST") { |
| 16 | + return { status: 405, body: "Method Not Allowed" }; |
| 17 | + } |
| 18 | + |
| 19 | + // Authenticate the request |
| 20 | + const authenticationResult = await authenticateApiRequest(request); |
| 21 | + |
| 22 | + if (!authenticationResult) { |
| 23 | + return json({ error: "Invalid or Missing API Key" }, { status: 401 }); |
| 24 | + } |
| 25 | + |
| 26 | + const parsed = ParamsSchema.safeParse(params); |
| 27 | + |
| 28 | + if (!parsed.success) { |
| 29 | + return json({ error: "Invalid or Missing runId" }, { status: 400 }); |
| 30 | + } |
| 31 | + |
| 32 | + const { runId } = parsed.data; |
| 33 | + |
| 34 | + const service = new CancelRunService(); |
| 35 | + try { |
| 36 | + await service.call({ runId }); |
| 37 | + } catch (error) { |
| 38 | + const prismaError = PrismaErrorSchema.safeParse(error); |
| 39 | + // Record not found in the database |
| 40 | + if (prismaError.success && prismaError.data.code === "P2005") { |
| 41 | + return json({ error: "Run not found" }, { status: 404 }); |
| 42 | + } else { |
| 43 | + return json({ error: "Internal Server Error" }, { status: 500 }); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + const presenter = new ApiRunPresenter(); |
| 48 | + const jobRun = await presenter.call({ |
| 49 | + runId: runId, |
| 50 | + }); |
| 51 | + |
| 52 | + if (!jobRun) { |
| 53 | + return json({ message: "Run not found" }, { status: 404 }); |
| 54 | + } |
| 55 | + |
| 56 | + return json({ |
| 57 | + id: jobRun.id, |
| 58 | + status: jobRun.status, |
| 59 | + startedAt: jobRun.startedAt, |
| 60 | + updatedAt: jobRun.updatedAt, |
| 61 | + completedAt: jobRun.completedAt, |
| 62 | + output: jobRun.output, |
| 63 | + tasks: jobRun.tasks, |
| 64 | + statuses: jobRun.statuses.map((s) => ({ |
| 65 | + ...s, |
| 66 | + state: s.state ?? undefined, |
| 67 | + data: s.data ?? undefined, |
| 68 | + history: s.history ?? undefined, |
| 69 | + })), |
| 70 | + }); |
| 71 | +} |
0 commit comments