-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathapi.v1.runs.$runFriendlyId.input-streams.wait.ts
More file actions
148 lines (130 loc) · 5 KB
/
api.v1.runs.$runFriendlyId.input-streams.wait.ts
File metadata and controls
148 lines (130 loc) · 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { json } from "@remix-run/server-runtime";
import { z } from "zod";
import {
CreateInputStreamWaitpointRequestBody,
type CreateInputStreamWaitpointResponseBody,
} from "@trigger.dev/core/v3";
import { WaitpointId } from "@trigger.dev/core/v3/isomorphic";
import { $replica } from "~/db.server";
import { createWaitpointTag, MAX_TAGS_PER_WAITPOINT } from "~/models/waitpointTag.server";
import {
deleteInputStreamWaitpoint,
setInputStreamWaitpoint,
} from "~/services/inputStreamWaitpointCache.server";
import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server";
import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server";
import { parseDelay } from "~/utils/delays";
import { resolveIdempotencyKeyTTL } from "~/utils/idempotencyKeys.server";
import { engine } from "~/v3/runEngine.server";
import { ServiceValidationError } from "~/v3/services/baseService.server";
const ParamsSchema = z.object({
runFriendlyId: z.string(),
});
const { action, loader } = createActionApiRoute(
{
params: ParamsSchema,
body: CreateInputStreamWaitpointRequestBody,
maxContentLength: 1024 * 10, // 10KB
method: "POST",
},
async ({ authentication, body, params }) => {
try {
const run = await $replica.taskRun.findFirst({
where: {
friendlyId: params.runFriendlyId,
runtimeEnvironmentId: authentication.environment.id,
},
select: {
id: true,
friendlyId: true,
realtimeStreamsVersion: true,
},
});
if (!run) {
return json({ error: "Run not found" }, { status: 404 });
}
const idempotencyKeyExpiresAt = body.idempotencyKeyTTL
? resolveIdempotencyKeyTTL(body.idempotencyKeyTTL)
: undefined;
const timeout = await parseDelay(body.timeout);
// Process tags (same pattern as api.v1.waitpoints.tokens.ts)
const bodyTags = typeof body.tags === "string" ? [body.tags] : body.tags;
if (bodyTags && bodyTags.length > MAX_TAGS_PER_WAITPOINT) {
throw new ServiceValidationError(
`Waitpoints can only have ${MAX_TAGS_PER_WAITPOINT} tags, you're trying to set ${bodyTags.length}.`
);
}
if (bodyTags && bodyTags.length > 0) {
for (const tag of bodyTags) {
await createWaitpointTag({
tag,
environmentId: authentication.environment.id,
projectId: authentication.environment.projectId,
});
}
}
// Step 1: Create the waitpoint
const result = await engine.createManualWaitpoint({
environmentId: authentication.environment.id,
projectId: authentication.environment.projectId,
idempotencyKey: body.idempotencyKey,
idempotencyKeyExpiresAt,
timeout,
tags: bodyTags,
});
// Step 2: Cache the mapping in Redis for fast lookup from .send()
const ttlMs = timeout ? timeout.getTime() - Date.now() : undefined;
await setInputStreamWaitpoint(
run.friendlyId,
body.streamId,
result.waitpoint.id,
ttlMs && ttlMs > 0 ? ttlMs : undefined
);
// Step 3: Check if data was already sent to this input stream (race condition handling).
// If .send() landed before .wait(), the data is in the S2 stream but no waitpoint
// existed to complete. We check from the client's last known position.
if (!result.isCached) {
try {
const realtimeStream = getRealtimeStreamInstance(
authentication.environment,
run.realtimeStreamsVersion
);
const records = await realtimeStream.readRecords(
run.friendlyId,
`$trigger.input:${body.streamId}`,
body.lastSeqNum
);
if (records.length > 0) {
const record = records[0]!;
// Record data is the raw user payload — no wrapper to unwrap
await engine.completeWaitpoint({
id: result.waitpoint.id,
output: {
value: record.data,
type: "application/json",
isError: false,
},
});
// Clean up the Redis cache since we completed it ourselves
await deleteInputStreamWaitpoint(run.friendlyId, body.streamId);
}
} catch {
// Non-fatal: if the S2 check fails, the waitpoint is still PENDING.
// The next .send() will complete it via the Redis cache path.
}
}
return json<CreateInputStreamWaitpointResponseBody>({
waitpointId: WaitpointId.toFriendlyId(result.waitpoint.id),
isCached: result.isCached,
});
} catch (error) {
if (error instanceof ServiceValidationError) {
return json({ error: error.message }, { status: 422 });
} else if (error instanceof Error) {
return json({ error: error.message }, { status: 500 });
}
return json({ error: "Something went wrong" }, { status: 500 });
}
}
);
export { action, loader };