-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-subscribe.ts
More file actions
241 lines (227 loc) · 6.47 KB
/
server-subscribe.ts
File metadata and controls
241 lines (227 loc) · 6.47 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import type { JobId } from "@arcp/core";
import type { BaseEnvelope } from "@arcp/core/envelope";
import { buildEnvelope } from "@arcp/core/envelope";
import { PermissionDeniedError } from "@arcp/core/errors";
import type {
Envelope,
JobListEntry,
SessionListJobsFilter,
} from "@arcp/core/messages";
import { newMessageId } from "@arcp/core/util";
import { forwardEventToSubscriber } from "./job-runner-helpers.js";
import type { Job } from "./job.js";
import {
compareJobListEntries,
compileListJobsFilter,
type ListJobsFilter,
paginateJobList,
} from "./list-jobs.js";
import type { ARCPServer } from "./server.js";
import type { SessionContext } from "./session-context.js";
import type { JobAuthorizationPolicy } from "./types.js";
export function defaultJobAuthorizationPolicy(
job: Job,
principal: string | undefined,
): boolean {
return job.submitterPrincipal === principal;
}
export async function handleListJobs(
server: ARCPServer,
ctx: SessionContext,
env: Envelope,
): Promise<void> {
if (env.type !== "session.list_jobs") return;
const sessionId = ctx.state.id;
if (sessionId === undefined) return;
const candidates = buildListJobsCandidates(server, ctx, env.payload.filter);
candidates.sort(compareJobListEntries);
const { page, nextCursor } = paginateJobList(
candidates,
env.payload.cursor ?? undefined,
env.payload.limit ?? 100,
);
await ctx.send(
buildEnvelope({
id: newMessageId(),
type: "session.jobs" as const,
payload: { request_id: env.id, jobs: page, next_cursor: nextCursor },
optional: { session_id: sessionId },
}),
);
}
function buildListJobsCandidates(
server: ARCPServer,
ctx: SessionContext,
rawFilter: SessionListJobsFilter | undefined,
): JobListEntry[] {
const principal = ctx.state.identity?.principal;
const policy: JobAuthorizationPolicy =
server.options.jobAuthorizationPolicy ?? defaultJobAuthorizationPolicy;
const filter: ListJobsFilter = compileListJobsFilter(rawFilter ?? {});
const out: JobListEntry[] = [];
for (const job of server.globalJobs.values()) {
if (!policy(job, principal)) continue;
if (!filter.matches(job)) continue;
out.push({
job_id: job.jobId,
agent: job.agentRef,
status: job.state,
lease: job.lease,
parent_job_id: job.parentJobId ?? null,
created_at: job.createdAt,
...(job.traceId === undefined ? {} : { trace_id: job.traceId }),
last_event_seq: ctx.latestEventSeq,
});
}
return out;
}
export async function handleJobSubscribe(
server: ARCPServer,
ctx: SessionContext,
env: Envelope,
): Promise<void> {
if (env.type !== "job.subscribe") return;
const sessionId = ctx.state.id;
if (sessionId === undefined) return;
const jobId = env.payload.job_id;
const job = server.globalJobs.get(jobId);
if (job === undefined) {
await emitSubscribeJobNotFound(ctx, jobId);
return;
}
if (!authorizeSubscribe(server, ctx, job)) {
await ctx.emitSessionError(
new PermissionDeniedError(
"Subscriber's principal is not authorized to observe this job",
),
);
return;
}
registerSubscriber(server, ctx, jobId);
const replayed = await maybeReplaySubscribeHistory({
server,
ctx,
job,
env,
});
await ctx.send(
buildEnvelope({
id: newMessageId(),
type: "job.subscribed" as const,
payload: buildSubscribedPayload(job, ctx.latestEventSeq, replayed),
optional: { session_id: sessionId, job_id: jobId },
}),
);
}
interface MaybeReplayArgs {
server: ARCPServer;
ctx: SessionContext;
job: Job;
env: Extract<Envelope, { type: "job.subscribe" }>;
}
async function maybeReplaySubscribeHistory(
args: MaybeReplayArgs,
): Promise<boolean> {
if (args.env.payload.history !== true) return false;
return replaySubscribeHistory({
server: args.server,
ctx: args.ctx,
job: args.job,
fromSeq: args.env.payload.from_event_seq,
});
}
async function emitSubscribeJobNotFound(
ctx: SessionContext,
jobId: JobId,
): Promise<void> {
await ctx.emitJobError(jobId, {
final_status: "error",
code: "JOB_NOT_FOUND",
message: `Job "${jobId}" not found`,
retryable: false,
});
}
function authorizeSubscribe(
server: ARCPServer,
ctx: SessionContext,
job: Job,
): boolean {
const principal = ctx.state.identity?.principal;
const policy: JobAuthorizationPolicy =
server.options.jobAuthorizationPolicy ?? defaultJobAuthorizationPolicy;
return policy(job, principal);
}
function registerSubscriber(
server: ARCPServer,
ctx: SessionContext,
jobId: JobId,
): void {
let set = server.subscribers.get(jobId);
if (set === undefined) {
set = new Set<SessionContext>();
server.subscribers.set(jobId, set);
}
set.add(ctx);
ctx.subscriptions.set(jobId, () => {
const s = server.subscribers.get(jobId);
if (s === undefined) return;
s.delete(ctx);
if (s.size === 0) server.subscribers.delete(jobId);
});
}
interface ReplaySubscribeHistoryArgs {
server: ARCPServer;
ctx: SessionContext;
job: Job;
fromSeq: number | undefined;
}
async function replaySubscribeHistory(
args: ReplaySubscribeHistoryArgs,
): Promise<boolean> {
const { server, ctx, job, fromSeq } = args;
if (job.owningSession === undefined) return false;
const ownerSessionId = job.owningSession.state.id;
if (ownerSessionId === undefined) return false;
try {
const events = await server.eventLog.readSinceSeq(
ownerSessionId,
fromSeq ?? 0,
10_000,
);
for (const e of events) {
if (!isReplayableForJob(e, job.jobId)) continue;
await forwardEventToSubscriber(ctx, e);
}
return events.some((e) => e.job_id === job.jobId);
} catch (error) {
ctx.logger.warn({ err: error }, "subscribe history replay failed");
return false;
}
}
function isReplayableForJob(env: BaseEnvelope, jobId: JobId): boolean {
if (env.job_id !== jobId) return false;
return (
env.type === "job.event" ||
env.type === "job.result" ||
env.type === "job.error"
);
}
function buildSubscribedPayload(
job: Job,
subscribedFrom: number,
replayed: boolean,
): Record<string, unknown> {
return {
job_id: job.jobId,
current_status: job.state,
agent: job.agentRef,
lease: job.lease,
...(job.leaseConstraints === undefined
? {}
: { lease_constraints: job.leaseConstraints }),
parent_job_id: job.parentJobId ?? null,
...(job.traceId === undefined ? {} : { trace_id: job.traceId }),
subscribed_from: subscribedFrom,
replayed,
};
}