-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathapi.v1.sessions.$session.close.ts
More file actions
79 lines (71 loc) · 2.5 KB
/
api.v1.sessions.$session.close.ts
File metadata and controls
79 lines (71 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { json } from "@remix-run/server-runtime";
import {
CloseSessionRequestBody,
type RetrieveSessionResponseBody,
} from "@trigger.dev/core/v3";
import { z } from "zod";
import { $replica, prisma } from "~/db.server";
import {
resolveSessionByIdOrExternalId,
serializeSessionWithFriendlyRunId,
} from "~/services/realtime/sessions.server";
import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server";
const ParamsSchema = z.object({
session: z.string(),
});
const { action, loader } = createActionApiRoute(
{
params: ParamsSchema,
body: CloseSessionRequestBody,
maxContentLength: 1024,
method: "POST",
allowJWT: true,
corsStrategy: "all",
authorization: {
action: "admin",
resource: (params) => ({ sessions: params.session }),
superScopes: ["admin:sessions", "admin:all", "admin"],
},
},
async ({ authentication, params, body }) => {
const existing = await resolveSessionByIdOrExternalId(
$replica,
authentication.environment.id,
params.session
);
if (!existing) {
return json({ error: "Session not found" }, { status: 404 });
}
// Idempotent: if already closed, return the current row without clobbering
// the original closedAt / closedReason.
if (existing.closedAt) {
return json<RetrieveSessionResponseBody>(
await serializeSessionWithFriendlyRunId(existing)
);
}
// `closedAt: null` on the where clause makes the update conditional at
// the DB level. Two concurrent closes race through the earlier read,
// but only one can win this update — the loser hits `count === 0` and
// falls back to reading the winning row. Closedness is write-once.
const { count } = await prisma.session.updateMany({
where: { id: existing.id, closedAt: null },
data: {
closedAt: new Date(),
closedReason: body.reason ?? null,
},
});
if (count === 0) {
const final = await prisma.session.findFirst({ where: { id: existing.id } });
if (!final) return json({ error: "Session not found" }, { status: 404 });
return json<RetrieveSessionResponseBody>(
await serializeSessionWithFriendlyRunId(final)
);
}
const updated = await prisma.session.findFirst({ where: { id: existing.id } });
if (!updated) return json({ error: "Session not found" }, { status: 404 });
return json<RetrieveSessionResponseBody>(
await serializeSessionWithFriendlyRunId(updated)
);
}
);
export { action, loader };