🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(linear): retry a sync hand-off the async router rejects, and log why internal tokens fail (#22023)
Rdmclin2ca94f0db40a6
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.tsindex 78ea0bf76d5..846e9a5de5b 100644--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { getTestDB } from '@lobechat/database/test-utils';+import { TRPCClientError } from '@trpc/client';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -277,6 +278,78 @@ describe('linearRouter', () => {expect(await caller({ userId }).listSyncJobs({ projectId })).toHaveLength(1);});+ describe('when the async router rejects the hand-off', () => {+ // What the async router answers when it turns down the internal token.+ const rejected = () =>+ new TRPCClientError('Invalid JWT token', {+ result: {+ error: {+ code: -32_001,+ data: { code: 'UNAUTHORIZED', httpStatus: 401 },+ message: 'Invalid JWT token',+ },+ },+ } as any);++ const startRule = async () => {+ const connection = await connect({ userId });+ mocks.getToken.mockResolvedValue('token');+ const rule = await caller({ userId }).createSyncRule({+ connectionId: connection.id,+ projectId,+ stateTypes: ['unstarted'],+ teamId: 'team-1',+ teamName: 'Engineering',+ });+ return caller({ userId }).startRuleSync({ ruleId: rule.id });+ };++ const settled = async (calls: number) => {+ for (let i = 0; i < 200 && mocks.runSync.mock.calls.length < calls; i++) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ // Let the last attempt record its outcome.+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setImmediate(resolve));+ };++ it('hands it off again with a new token', async () => {+ mocks.runSync.mockRejectedValueOnce(rejected()).mockResolvedValueOnce({ ok: true });++ const { id } = await startRule();+ await settled(2);++ expect(mocks.runSync).toHaveBeenCalledTimes(2);+ expect(mocks.runSync).toHaveBeenLastCalledWith({ taskId: id, workspaceId: undefined });+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: null, id, status: 'pending' },+ ]);+ });++ it('fails the job at once when the retry is rejected too, so it can be started again', async () => {+ mocks.runSync.mockRejectedValue(rejected());++ const { id } = await startRule();+ await settled(2);++ expect(mocks.runSync).toHaveBeenCalledTimes(2);+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: 'failed', id, status: 'error' },+ ]);+ });++ it('leaves a job the router accepted to the router, even when the response is lost', async () => {+ mocks.runSync.mockRejectedValue(new TRPCClientError('fetch failed'));++ const { id } = await startRule();+ await settled(1);++ expect(mocks.runSync).toHaveBeenCalledTimes(1);+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: null, id, status: 'pending' },+ ]);+ });+ });+it('keeps a long sync alive, so it is not shown as cut off', async () => {vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });try {diff --git a/apps/server/src/services/linear/startSyncJob.ts b/apps/server/src/services/linear/startSyncJob.tsindex f031b22e00f..ed6d2c51c10 100644--- a/apps/server/src/services/linear/startSyncJob.ts+++ b/apps/server/src/services/linear/startSyncJob.ts@@ -1,16 +1,25 @@import type { LinearSyncJobErrorCode, LinearSyncJobMetadata } from '@lobechat/types';import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';import debug from 'debug';import { AsyncTaskModel } from '@/database/models/asyncTask';import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';import type { LobeChatDatabase } from '@/database/type';import { createAsyncCaller } from '@/server/routers/async';+import { after } from '@/server/utils/scheduleAfterResponse';import { toLinearSyncJobView } from './syncJob';const log = debug('lobe-server:linear:sync-job');+/**+ * Hand-offs per job. Only a hand-off the async router turned away before+ * claiming the job (its internal token was rejected) is tried again, with a+ * freshly signed token.+ */+const MAX_DISPATCH_ATTEMPTS = 2;+/*** Record a Linear sync job and hand it to the async router, which runs it with* `LinearSyncJobService`. Kept apart from that service so the async router can@@ -76,19 +85,46 @@ const dispatchJob = async (workspaceId: string | undefined,taskId: string,) => {- try {- const asyncCaller = await createAsyncCaller({ userId });- // Fire and forget: the async router owns the job once the request reaches- // it, so a dropped response here (a proxy timing out a long run) is not a- // failed sync; only log it.- asyncCaller.linear- .runSync({ taskId, workspaceId })- .catch((error: unknown) => log('async sync %s request failed: %O', taskId, error));- } catch (error) {- log('trigger sync %s failed: %O', taskId, error);- await new AsyncTaskModel(db, userId, workspaceId).update(taskId, {+ const fail = () =>+ new AsyncTaskModel(db, userId, workspaceId).update(taskId, {error: { code: 'failed' satisfies LinearSyncJobErrorCode },status: AsyncTaskStatus.Error,});- }++ // Kept alive past the response, so a rejected hand-off can still be retried+ // or reported; otherwise the job sits queued until the client gives up on it.+ after(async () => {+ for (let attempt = 1; ; attempt++) {+ let asyncCaller: Awaited<ReturnType<typeof createAsyncCaller>>;+ try {+ // Signs a new internal token, so a retry never resends a rejected one.+ asyncCaller = await createAsyncCaller({ userId });+ } catch (error) {+ log('trigger sync %s failed: %O', taskId, error);+ await fail();+ return;+ }+ try {+ await asyncCaller.linear.runSync({ taskId, workspaceId });+ return;+ } catch (error) {+ // Any other failure reached the async router, which owns the job from+ // there; a dropped response (a proxy timing out a long run) is not a+ // failed sync, so only log it.+ if (!isRejectedHandOff(error)) {+ log('async sync %s request failed: %O', taskId, error);+ return;+ }+ log('async sync %s hand-off rejected (attempt %d): %O', taskId, attempt, error);+ if (attempt >= MAX_DISPATCH_ATTEMPTS) {+ await fail();+ return;+ }+ }+ }+ });};++/** The async router refused the call before running it, so the job is still unclaimed. */+const isRejectedHandOff = (error: unknown) =>+ error instanceof TRPCClientError && error.data?.code === 'UNAUTHORIZED';diff --git a/packages/trpc/src/utils/internalJwt.rotation.test.ts b/packages/trpc/src/utils/internalJwt.rotation.test.tsindex 436b891a547..c689dea2617 100644--- a/packages/trpc/src/utils/internalJwt.rotation.test.ts+++ b/packages/trpc/src/utils/internalJwt.rotation.test.ts@@ -1,7 +1,7 @@import { generateKeyPairSync } from 'node:crypto';import { calculateJwkThumbprint, decodeProtectedHeader, SignJWT } from 'jose';-import { beforeAll, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';const { authEnvMock } = vi.hoisted(() => ({authEnvMock: {@@ -119,4 +119,42 @@ describe('internal JWT key rotation', () => {validateHeteroOperationJWT(await signHeteroToken(keys.old, null)),).resolves.toMatchObject({ operation_id: 'operation-1', sub: 'user-1' });});++ describe('a rejected token', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('logs that it expired, with the timing claims but not the token', async () => {+ const { validateInternalJWT } = await import('./internalJwt');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const iat = Math.floor(Date.now() / 1000) - 60;+ const token = await new SignJWT({ purpose: 'lobe-internal-call' })+ .setProtectedHeader({ alg: 'RS256', kid: keys.new.kid })+ .setIssuedAt(iat)+ .setExpirationTime(iat + 5)+ .sign(keys.new.privateKey);++ await expect(validateInternalJWT(token)).resolves.toBe(false);++ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('internal call token'),+ expect.objectContaining({ code: 'ERR_JWT_EXPIRED', exp: iat + 5, iat, kid: 'new-key' }),+ );+ expect(JSON.stringify(warn.mock.calls)).not.toContain(token);+ });++ it('logs a key the JWKS no longer holds', async () => {+ const { validateInternalJWT } = await import('./internalJwt');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const retired = createRsaKey('retired-key');++ await expect(validateInternalJWT(await signToken(retired))).resolves.toBe(false);++ expect(warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ code: 'ERR_JWKS_NO_MATCHING_KEY', kid: 'retired-key' }),+ );+ });+ });});diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.tsindex b1327dc71eb..a3e04f4ed90 100644--- a/packages/trpc/src/utils/internalJwt.ts+++ b/packages/trpc/src/utils/internalJwt.ts@@ -5,6 +5,7 @@ import type { JSONWebKeySet, JWK, JWK_RSA_Public, JWTVerifyOptions } from 'jose'import {calculateJwkThumbprint,createLocalJWKSet,+ decodeJwt,decodeProtectedHeader,importJWK,jwtVerify,@@ -350,7 +351,25 @@ export const validateInternalJWT = async (token: string): Promise<boolean> => {log('Internal JWT validation successful');return true;} catch (error) {- log('Internal JWT validation failed: %O', error);+ // Logged in production (not only under DEBUG): a rejected lambda → async+ // call leaves its job unclaimed, and without the reason an expired token,+ // a key missing after rotation and a bad signature all look the same.+ console.warn('[internalJwt] rejected an internal call token:', describeRejection(token, error));return false;}};++/** Why a token was rejected, from its public header and timing claims only. */+const describeRejection = (token: string, error: unknown) => {+ const reason = {+ code: (error as { code?: unknown } | null)?.code,+ message: error instanceof Error ? error.message : String(error),+ now: Math.floor(Date.now() / 1000),+ };+ try {+ const { exp, iat } = decodeJwt(token);+ return { ...reason, exp, iat, kid: decodeProtectedHeader(token).kid };+ } catch {+ return reason;+ }+};