@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 442 lines 15.9 KB
Raw
1 /**
2 * Linear's GraphQL API, signed with the API key saved in Settings. The operations live in
3 * `LinearApi.graphql` and their client is generated (`vp run generate`). A rate-limit refusal
4 * arrives as HTTP 429 or as a `RATELIMITED` GraphQL error on a 400; both map to `rate-limited`.
5 */
6 import * as Clock from "effect/Clock";
7 import * as Config from "effect/Config";
8 import * as Context from "effect/Context";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Schema from "effect/Schema";
13 import {
14 GraphQLClient,
15 GraphQLClientError,
16 GraphQLMiddleware,
17 GraphQLProtocol,
18 } from "effect/graphql";
19 import { HttpClient } from "effect/http";
20 import * as Headers from "effect/http/Headers";
21 import { LINEAR_KIND } from "../shared/issueUrl.ts";
22 import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker";
23 import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost";
24
25 import type {
26 CommentCreateInput,
27 IssueCreateInput,
28 IssueFilter,
29 IssueUpdateInput,
30 } from "../../schema/linear.graphql.ts";
31 import {
32 LinearApiGraphQLGroup,
33 type Attachment,
34 type IssueHistory,
35 type LinearComment,
36 type LinearIssue,
37 type LinearReaction,
38 type LinearTeamLabel,
39 type LinearUser,
40 type T3Issue,
41 type T3Team,
42 type Template,
43 } from "./LinearApi.graphql.ts";
44
45 export type { IssueFilter } from "../../schema/linear.graphql.ts";
46 export type {
47 LinearComment,
48 LinearIssue,
49 LinearReaction,
50 LinearUser,
51 } from "./LinearApi.graphql.ts";
52 export type { LinearWorkflowState } from "./LinearApi.graphql.ts";
53 export type LinearAttachment = Attachment;
54 export type LinearHistoryEntry = IssueHistory;
55
56 export const KIND = LINEAR_KIND;
57 const DEFAULT_API_URL = "https://api.linear.app/graphql";
58
59 const LinearApiConfig = Config.all({
60 apiUrl: Config.String("T3CODE_LINEAR_API_URL").pipe(Config.withDefault(DEFAULT_API_URL)),
61 });
62
63 const LinearTemplateData = Schema.Struct({
64 title: Schema.optional(Schema.NullOr(Schema.String)),
65 description: Schema.optional(Schema.Unknown),
66 descriptionData: Schema.optional(Schema.Unknown),
67 labelIds: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
68 assigneeId: Schema.optional(Schema.NullOr(Schema.String)),
69 });
70 type LinearTemplateData = typeof LinearTemplateData.Type;
71 const decodeTemplateData = Schema.decodeUnknownOption(
72 Schema.Union([Schema.fromJsonString(LinearTemplateData), LinearTemplateData]),
73 );
74
75 /** A template with its data read: Linear sends it as a JSON string, and has sent an object. */
76 export interface LinearTemplate extends Omit<Template, "templateData"> {
77 readonly templateData: LinearTemplateData;
78 }
79
80 type LinearTeamDetail = T3Team.Result["teams"]["nodes"][number];
81 type LinearIssueDetail = NonNullable<T3Issue.Result["issue"]>;
82
83 /** The team with the workspace-wide labels that any of its issues may also carry. */
84 export interface LinearTeamScope {
85 readonly team: Omit<LinearTeamDetail, "templates"> & {
86 readonly templates: { readonly nodes: ReadonlyArray<LinearTemplate> };
87 };
88 readonly workspaceLabels: ReadonlyArray<LinearTeamLabel>;
89 /** Linear had more than one page of something; a missing label or member may still exist. */
90 readonly truncated: boolean;
91 }
92
93 export class LinearApi extends Context.Service<
94 LinearApi,
95 {
96 /** Who a credential is, and the teams it reaches. Takes the token so it can vet a new one. */
97 readonly viewer: (token?: string) => Effect.Effect<
98 {
99 readonly viewer: LinearUser;
100 /** The workspace's URL key, the first path segment of its issue links. */
101 readonly workspace: string;
102 readonly teams: ReadonlyArray<{
103 readonly id: string;
104 readonly key: string;
105 readonly name: string;
106 }>;
107 },
108 IssueTrackerError
109 >;
110 readonly listIssues: (input: {
111 readonly filter: IssueFilter;
112 readonly first: number;
113 readonly after?: string | undefined;
114 readonly orderBy: "updatedAt" | "createdAt";
115 }) => Effect.Effect<
116 { readonly nodes: ReadonlyArray<LinearIssue>; readonly nextCursor: string | null },
117 IssueTrackerError
118 >;
119 /** Null when Linear has no issue by that identifier, or the credential cannot see it. */
120 readonly getIssue: (
121 identifier: string,
122 comments: number,
123 ) => Effect.Effect<LinearIssueDetail | null, IssueTrackerError>;
124 readonly getComments: (input: {
125 readonly identifier: string;
126 readonly first: number;
127 readonly after: string;
128 }) => Effect.Effect<
129 { readonly nodes: ReadonlyArray<LinearComment>; readonly nextCursor: string | null },
130 IssueTrackerError
131 >;
132 readonly getTeam: (key: string) => Effect.Effect<LinearTeamScope | null, IssueTrackerError>;
133 readonly createIssue: (
134 input: IssueCreateInput,
135 ) => Effect.Effect<{ readonly identifier: string; readonly url: string }, IssueTrackerError>;
136 readonly updateIssue: (
137 identifier: string,
138 input: IssueUpdateInput,
139 ) => Effect.Effect<void, IssueTrackerError>;
140 readonly createComment: (input: CommentCreateInput) => Effect.Effect<void, IssueTrackerError>;
141 readonly createReaction: (input: {
142 readonly issueId?: string | undefined;
143 readonly commentId?: string | undefined;
144 readonly emoji: string;
145 }) => Effect.Effect<void, IssueTrackerError>;
146 readonly deleteReaction: (id: string) => Effect.Effect<void, IssueTrackerError>;
147 /** Reactions on an issue (by identifier) or a comment (by id), to find the viewer's own. */
148 readonly listReactions: (input: {
149 readonly issueId?: string | undefined;
150 readonly commentId?: string | undefined;
151 }) => Effect.Effect<
152 {
153 /** The issue the reactions hang off: the one asked for, or the comment's own. */
154 readonly issueId: string | null;
155 readonly reactions: ReadonlyArray<LinearReaction>;
156 },
157 IssueTrackerError
158 >;
159 }
160 >()("@t3tools/issue-tracker-linear/server/LinearApi") {}
161
162 /** The API key a call is sent with: the stored one, or a new one being vetted. */
163 class LinearToken extends Context.Service<LinearToken, string>()(
164 "@t3tools/issue-tracker-linear/server/LinearApi/LinearToken",
165 ) {}
166
167 class LinearAuth extends GraphQLMiddleware.Service<LinearAuth, { requires: LinearToken }>()(
168 "@t3tools/issue-tracker-linear/server/LinearApi/LinearAuth",
169 ) {}
170
171 const LinearGroup = LinearApiGraphQLGroup.middleware(LinearAuth);
172
173 const fail = (
174 operation: string,
175 reason: IssueTrackerError["reason"],
176 detail: string,
177 extra: { readonly retryAt?: number; readonly cause?: unknown } = {},
178 ) =>
179 new IssueTrackerError({
180 tracker: KIND,
181 operation,
182 reason,
183 detail,
184 ...(extra.retryAt === undefined ? {} : { retryAt: extra.retryAt }),
185 ...(extra.cause === undefined ? {} : { cause: extra.cause }),
186 });
187
188 const hasCode = (errors: ReadonlyArray<GraphQLClientError.GraphQLError>, code: string) =>
189 errors.some((error) => error.extensions?.["code"] === code);
190
191 /** Linear's reset headers are UTC epoch milliseconds, not the seconds-from-now of `Retry-After`. */
192 function resetAtFromHeader(value: string | undefined, now: number): number | undefined {
193 const resetAt = /^\d+$/u.test(value?.trim() ?? "") ? Number(value) : Number.NaN;
194 return Number.isSafeInteger(resetAt) && resetAt > now ? resetAt : undefined;
195 }
196
197 /** Linear's answer as the tracker's error. Linear writes its messages for people. */
198 const toTrackerError = (
199 operation: string,
200 error: GraphQLClientError.GraphQLClientError,
201 now: number,
202 ): IssueTrackerError => {
203 const reason = error.reason;
204 if (reason._tag !== "ResponseError" && reason._tag !== "TransportError") {
205 return fail(operation, "failed", "Linear returned an unexpected body.", { cause: error });
206 }
207 const errors = reason._tag === "ResponseError" ? reason.errors : [];
208 const headers = reason.headers ?? Headers.empty;
209 if (reason.status === 429 || hasCode(errors, "RATELIMITED")) {
210 const retryAt = resetAtFromHeader(
211 headers["x-ratelimit-requests-reset"] ?? headers["x-ratelimit-complexity-reset"],
212 now,
213 );
214 return fail(
215 operation,
216 "rate-limited",
217 "Linear's rate limit was reached.",
218 retryAt === undefined ? {} : { retryAt },
219 );
220 }
221 if (reason.status === 401 || reason.status === 403 || hasCode(errors, "AUTHENTICATION_ERROR")) {
222 return fail(operation, "unauthenticated", "Linear rejected the API key.");
223 }
224 if (reason._tag === "ResponseError") {
225 return fail(operation, "failed", errors[0]?.message.trim() || "Linear refused the request.");
226 }
227 return reason.status === undefined
228 ? fail(operation, "failed", "Linear could not be reached.", { cause: error })
229 : fail(operation, "failed", `Linear returned HTTP ${reason.status} with an unexpected body.`);
230 };
231
232 const nextCursor = (pageInfo: {
233 readonly hasNextPage: boolean;
234 readonly endCursor: string | null;
235 }) => (pageInfo.hasNextPage ? pageInfo.endCursor : null);
236
237 export const make = Effect.gen(function* () {
238 // Only a default-carrying string: nothing in the environment can make it fail.
239 const config = yield* LinearApiConfig.pipe(Effect.orDie);
240 const httpClient = yield* HttpClient.HttpClient;
241 const host = yield* IssueTrackerHost.IssueTrackerHost;
242
243 const client = yield* GraphQLClient.make(LinearGroup).pipe(
244 Effect.provide(
245 Layer.mergeAll(
246 Layer.succeed(
247 LinearAuth,
248 GraphQLMiddleware.mapRequest((request) =>
249 Effect.gen(function* () {
250 const token = yield* LinearToken;
251 // A personal API key goes in as-is; `Bearer` is for OAuth tokens, which this is not.
252 return { ...request, headers: Headers.set(request.headers, "authorization", token) };
253 }),
254 ),
255 ),
256 GraphQLProtocol.layerHttp({ url: config.apiUrl }).pipe(
257 Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)),
258 ),
259 ),
260 ),
261 );
262
263 const storedToken = (operation: string) =>
264 host.credentials
265 .get(KIND)
266 .pipe(
267 Effect.flatMap(
268 Effect.fromOption(() =>
269 fail(operation, "unauthenticated", "Linear is not connected on this server."),
270 ),
271 ),
272 );
273
274 const call = Effect.fn("LinearApi.call")(function* <A>(
275 operation: string,
276 run: (
277 linear: typeof client,
278 ) => Effect.Effect<A, GraphQLClientError.GraphQLClientError, LinearToken>,
279 token?: string,
280 ): Effect.fn.Return<A, IssueTrackerError> {
281 yield* Effect.annotateCurrentSpan({ "linear.operation": operation });
282 const key = token ?? (yield* storedToken(operation));
283 return yield* run(client).pipe(
284 Effect.catch((error) =>
285 Effect.flatMap(Clock.currentTimeMillis, (now) =>
286 Effect.fail(toTrackerError(operation, error, now)),
287 ),
288 ),
289 Effect.provideService(LinearToken, key),
290 );
291 });
292
293 const applied = (operation: string, result: { readonly success: boolean }) =>
294 result.success
295 ? Effect.void
296 : Effect.fail(fail(operation, "failed", "Linear did not apply the change."));
297
298 const viewer: LinearApi["Service"]["viewer"] = (token) =>
299 call("viewer", (linear) => linear.T3Viewer(), token).pipe(
300 Effect.map((data) => ({
301 viewer: data.viewer,
302 workspace: data.organization.urlKey,
303 teams: data.teams.nodes,
304 })),
305 );
306
307 const listIssues: LinearApi["Service"]["listIssues"] = (input) =>
308 call("listIssues", (linear) =>
309 linear.T3Issues({
310 first: input.first,
311 after: input.after ?? null,
312 filter: input.filter,
313 orderBy: input.orderBy,
314 }),
315 ).pipe(
316 Effect.map((data) => ({
317 nodes: data.issues.nodes,
318 nextCursor: nextCursor(data.issues.pageInfo),
319 })),
320 );
321
322 const getIssue: LinearApi["Service"]["getIssue"] = (identifier, comments) =>
323 call("getIssue", (linear) => linear.T3Issue({ id: identifier, comments })).pipe(
324 Effect.map((data) => data.issue),
325 // Linear answers an unknown identifier with an error and no data, not with null.
326 Effect.catchIf(
327 (error) => error.reason === "failed" && /not found/i.test(error.detail),
328 () => Effect.succeed(null),
329 ),
330 );
331
332 const getComments: LinearApi["Service"]["getComments"] = (input) =>
333 call("getComments", (linear) =>
334 linear.T3Comments({ id: input.identifier, first: input.first, after: input.after }),
335 ).pipe(
336 Effect.flatMap((data) =>
337 data.issue === null
338 ? Effect.fail(fail("getComments", "not-found", "This issue no longer exists."))
339 : Effect.succeed({
340 nodes: data.issue.comments.nodes,
341 nextCursor: nextCursor(data.issue.comments.pageInfo),
342 }),
343 ),
344 );
345
346 const getTeam: LinearApi["Service"]["getTeam"] = (key) =>
347 call("getTeam", (linear) => linear.T3Team({ key })).pipe(
348 Effect.map((data) => {
349 const team = data.teams.nodes[0];
350 if (team === undefined) return null;
351 return {
352 team: {
353 ...team,
354 templates: {
355 nodes: team.templates.nodes.map((template) => ({
356 ...template,
357 templateData: Option.getOrElse(
358 decodeTemplateData(template.templateData),
359 (): LinearTemplateData => ({}),
360 ),
361 })),
362 },
363 },
364 workspaceLabels: data.issueLabels.nodes,
365 truncated:
366 team.states.pageInfo.hasNextPage ||
367 team.labels.pageInfo.hasNextPage ||
368 team.members.pageInfo.hasNextPage ||
369 data.issueLabels.pageInfo.hasNextPage,
370 };
371 }),
372 );
373
374 const createIssue: LinearApi["Service"]["createIssue"] = (input) =>
375 call("createIssue", (linear) => linear.T3IssueCreate({ input })).pipe(
376 Effect.flatMap(({ issueCreate }) =>
377 issueCreate.success && issueCreate.issue !== null
378 ? Effect.succeed(issueCreate.issue)
379 : Effect.fail(fail("createIssue", "failed", "Linear did not create the issue.")),
380 ),
381 );
382
383 const updateIssue: LinearApi["Service"]["updateIssue"] = (identifier, input) =>
384 call("updateIssue", (linear) => linear.T3IssueUpdate({ id: identifier, input })).pipe(
385 Effect.flatMap(({ issueUpdate }) => applied("updateIssue", issueUpdate)),
386 );
387
388 const createComment: LinearApi["Service"]["createComment"] = (input) =>
389 call("createComment", (linear) => linear.T3CommentCreate({ input })).pipe(
390 Effect.flatMap(({ commentCreate }) => applied("createComment", commentCreate)),
391 );
392
393 const createReaction: LinearApi["Service"]["createReaction"] = (input) =>
394 call("createReaction", (linear) =>
395 linear.T3ReactionCreate({
396 input:
397 input.commentId === undefined
398 ? { issueId: input.issueId ?? null, emoji: input.emoji }
399 : { commentId: input.commentId, emoji: input.emoji },
400 }),
401 ).pipe(Effect.flatMap(({ reactionCreate }) => applied("createReaction", reactionCreate)));
402
403 const deleteReaction: LinearApi["Service"]["deleteReaction"] = (id) =>
404 call("deleteReaction", (linear) => linear.T3ReactionDelete({ id })).pipe(
405 Effect.flatMap(({ reactionDelete }) => applied("deleteReaction", reactionDelete)),
406 );
407
408 const listReactions: LinearApi["Service"]["listReactions"] = (input) =>
409 input.commentId === undefined
410 ? call("listReactions", (linear) =>
411 linear.T3IssueReactions({ id: input.issueId ?? "" }),
412 ).pipe(
413 Effect.map((data) => ({
414 issueId: input.issueId ?? null,
415 reactions: data.issue.reactions,
416 })),
417 )
418 : call("listReactions", (linear) =>
419 linear.T3CommentReactions({ id: input.commentId ?? "" }),
420 ).pipe(
421 Effect.map((data) => ({
422 issueId: data.comment.issue?.id ?? null,
423 reactions: data.comment.reactions,
424 })),
425 );
426
427 return LinearApi.of({
428 viewer,
429 listIssues,
430 getIssue,
431 getComments,
432 getTeam,
433 createIssue,
434 updateIssue,
435 createComment,
436 createReaction,
437 deleteReaction,
438 listReactions,
439 });
440 });
441
442 export const layer = Layer.effect(LinearApi, make);