🤯 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(workflow): cancel run guards with qstash rest payload (#16731)
Nekoc3547382bbd5
diff --git a/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts b/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.tsindex dd96c523c51..d1caa3cb6e1 100644--- a/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts+++ b/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts@@ -1,18 +1,24 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const { mockGetRedisConfig, redis, redisLib, workflowClient } = vi.hoisted(() => ({- mockGetRedisConfig: vi.fn(),- redis: {- set: vi.fn(),- },- redisLib: {- initializeRedis: vi.fn(),- isRedisEnabled: vi.fn(),- },- workflowClient: {- cancel: vi.fn(),- logs: vi.fn(),- },+import type * as RunGuardModule from '@/server/workflows/runGuard';++const { mockCancelWorkflowRunsByGuardPolicy, mockGetRedisConfig, redis, redisLib } = vi.hoisted(+ () => ({+ mockCancelWorkflowRunsByGuardPolicy: vi.fn(),+ mockGetRedisConfig: vi.fn(),+ redis: {+ set: vi.fn(),+ },+ redisLib: {+ initializeRedis: vi.fn(),+ isRedisEnabled: vi.fn(),+ },+ }),+);++vi.mock('@/server/workflows/runGuard', async (importOriginal) => ({+ ...(await importOriginal<typeof RunGuardModule>()),+ cancelWorkflowRunsByGuardPolicy: mockCancelWorkflowRunsByGuardPolicy,}));vi.mock('@/envs/redis', () => ({@@ -24,10 +30,6 @@ vi.mock('@/libs/redis', () => ({isRedisEnabled: redisLib.isRedisEnabled,}));-vi.mock('@/libs/qstash', () => ({- workflowClient,-}));-const { POST } = await import('./route');const originalEnv = {@@ -166,7 +168,10 @@ describe('workflow run guard webhook route', () => {it('cancels qstash runs for path guards when policy requests it', async () => {process.env.MEMORY_USER_MEMORY_WEBHOOK_BASE_URL = 'https://internal.lobehub.com';redis.set.mockResolvedValue('OK');- workflowClient.cancel.mockResolvedValue({ cancelled: 1 });+ mockCancelWorkflowRunsByGuardPolicy.mockResolvedValue({+ cancelled: 1,+ workflowUrlPrefix: 'https://internal.lobehub.com/api/workflows/memory-user-memory',+ });const response = await POST(new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {@@ -191,9 +196,9 @@ describe('workflow run guard webhook route', () => {},success: true,});- expect(workflowClient.logs).not.toHaveBeenCalled();- expect(workflowClient.cancel).toHaveBeenCalledWith({- urlStartingWith: 'https://internal.lobehub.com/api/workflows/memory-user-memory',+ expect(mockCancelWorkflowRunsByGuardPolicy).toHaveBeenCalledWith({+ appUrl: 'https://internal.lobehub.com',+ workflowPath: 'api/workflows/memory-user-memory',});});diff --git a/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts b/src/app/(backend)/api/webhooks/workflows/run-guard/route.tsindex 5a7aaf67300..7a5833f3bf6 100644--- a/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts+++ b/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts@@ -2,7 +2,6 @@ import { NextResponse } from 'next/server';import { z } from 'zod';import { getRedisConfig } from '@/envs/redis';-import { workflowClient } from '@/libs/qstash';import { initializeRedis, isRedisEnabled } from '@/libs/redis';import { parseWorkflowRunGuardConfig } from '@/server/globalConfig/parseWorkflowRunGuardConfig';import { cancelWorkflowRunsByGuardPolicy, setWorkflowRunGuard } from '@/server/workflows/runGuard';@@ -109,7 +108,7 @@ export const POST = async (request: Request) => {if (policy?.cancelQstash && scope.type === 'path') {if (!appUrl) throw new Error('App URL is not configured');- qstash = await cancelWorkflowRunsByGuardPolicy(workflowClient, {+ qstash = await cancelWorkflowRunsByGuardPolicy({appUrl,workflowPath: scope.workflowPath,});diff --git a/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts b/src/server/workflows/runGuard/__tests__/qstashCancel.test.tsindex 5e377adabee..bacdd48f852 100644--- a/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts+++ b/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts@@ -1,94 +1,145 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cancelWorkflowRunsByGuardPolicy } from '../qstashCancel';describe('workflow run guard qstash cancel', () => {+ const originalQstashToken = process.env.QSTASH_TOKEN;+ const originalQstashUrl = process.env.QSTASH_URL;++ beforeEach(() => {+ process.env.QSTASH_TOKEN = 'test-token';+ delete process.env.QSTASH_URL;+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(JSON.stringify({ cancelled: 12 }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ }),+ );+ });++ afterEach(() => {+ if (originalQstashToken === undefined) delete process.env.QSTASH_TOKEN;+ else process.env.QSTASH_TOKEN = originalQstashToken;++ if (originalQstashUrl === undefined) delete process.env.QSTASH_URL;+ else process.env.QSTASH_URL = originalQstashUrl;++ vi.restoreAllMocks();+ });+/*** @example- * cancelWorkflowRunsByGuardPolicy(client, {+ * cancelWorkflowRunsByGuardPolicy({* appUrl: 'https://app.lobehub.com',* workflowPath: 'api/workflows/memory-user-memory',* })* // cancels pending and active workflows whose URL starts with the workflow prefix*/- it('cancels workflows using the SDK url prefix API', async () => {- const client = {- cancel: vi.fn().mockResolvedValue({ cancelled: 12 }),- };-+ it('cancels workflows using the REST URL-prefix body shape expected by QStash', async () => {await expect(- cancelWorkflowRunsByGuardPolicy(- client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],- {- appUrl: 'https://app.lobehub.com',- workflowPath: 'api/workflows/memory-user-memory',- },- ),+ cancelWorkflowRunsByGuardPolicy({+ appUrl: 'https://app.lobehub.com',+ workflowPath: 'api/workflows/memory-user-memory',+ }),).resolves.toEqual({cancelled: 12,workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});- expect(client.cancel).toHaveBeenCalledWith({- urlStartingWith: 'https://app.lobehub.com/api/workflows/memory-user-memory',- });+ expect(globalThis.fetch).toHaveBeenCalledWith(+ new URL('/v2/workflows/runs', 'https://qstash.upstash.io'),+ {+ body: JSON.stringify({+ workflowUrl: ['https://app.lobehub.com/api/workflows/memory-user-memory'],+ }),+ headers: {+ 'Authorization': 'Bearer test-token',+ 'Content-Type': 'application/json',+ },+ method: 'DELETE',+ },+ );});/*** @example- * cancelWorkflowRunsByGuardPolicy(client, {+ * cancelWorkflowRunsByGuardPolicy({* appUrl: 'https://app.lobehub.com/',* workflowPath: '/api/workflows/memory-user-memory/?cursor=1#hash',* })* // normalizes the URL prefix before cancellation*/it('normalizes the workflow URL prefix before cancellation', async () => {- const client = {- cancel: vi.fn().mockResolvedValue({ cancelled: 1 }),- };+ vi.mocked(globalThis.fetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ cancelled: 1 }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ }),+ );await expect(- cancelWorkflowRunsByGuardPolicy(- client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],- {- appUrl: 'https://app.lobehub.com/',- workflowPath: '/api/workflows/memory-user-memory/?cursor=1#hash',- },- ),+ cancelWorkflowRunsByGuardPolicy({+ appUrl: 'https://app.lobehub.com/',+ workflowPath: '/api/workflows/memory-user-memory/?cursor=1#hash',+ }),).resolves.toEqual({cancelled: 1,workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});- expect(client.cancel).toHaveBeenCalledWith({- urlStartingWith: 'https://app.lobehub.com/api/workflows/memory-user-memory',- });+ expect(globalThis.fetch).toHaveBeenCalledWith(+ new URL('/v2/workflows/runs', 'https://qstash.upstash.io'),+ expect.objectContaining({+ body: JSON.stringify({+ workflowUrl: ['https://app.lobehub.com/api/workflows/memory-user-memory'],+ }),+ }),+ );});/*** @example- * cancelWorkflowRunsByGuardPolicy(client, {+ * cancelWorkflowRunsByGuardPolicy({* appUrl: 'https://app.lobehub.com',* workflowPath: 'api/workflows/memory-user-memory',* })* // returns the SDK cancellation count, including zero*/it('returns zero when QStash reports no cancelled workflows', async () => {- const client = {- cancel: vi.fn().mockResolvedValue({ cancelled: 0 }),- };+ vi.mocked(globalThis.fetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ cancelled: 0 }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ }),+ );await expect(- cancelWorkflowRunsByGuardPolicy(- client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],- {- appUrl: 'https://app.lobehub.com',- workflowPath: 'api/workflows/memory-user-memory',- },- ),+ cancelWorkflowRunsByGuardPolicy({+ appUrl: 'https://app.lobehub.com',+ workflowPath: 'api/workflows/memory-user-memory',+ }),).resolves.toEqual({cancelled: 0,workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});});++ /**+ * @example+ * cancelWorkflowRunsByGuardPolicy({+ * appUrl: 'https://app.lobehub.com',+ * workflowPath: 'api/workflows/memory-user-memory',+ * })+ * // throws when QSTASH_TOKEN is not configured+ */+ it('throws when QSTASH_TOKEN is missing', async () => {+ delete process.env.QSTASH_TOKEN;++ await expect(+ cancelWorkflowRunsByGuardPolicy({+ appUrl: 'https://app.lobehub.com',+ workflowPath: 'api/workflows/memory-user-memory',+ }),+ ).rejects.toThrow('QSTASH_TOKEN is required to cancel workflow runs');+ });});diff --git a/src/server/workflows/runGuard/qstashCancel.ts b/src/server/workflows/runGuard/qstashCancel.tsindex edc2f816784..825378a1372 100644--- a/src/server/workflows/runGuard/qstashCancel.ts+++ b/src/server/workflows/runGuard/qstashCancel.ts@@ -1,7 +1,10 @@-import type { Client as WorkflowClient } from '@upstash/workflow';-import { normalizeWorkflowRunGuardPath } from './keys';+/**+ * Default Upstash QStash origin used by the SDK when `QSTASH_URL` is not configured.+ */+const DEFAULT_QSTASH_URL = 'https://qstash.upstash.io';+/*** Input used to resolve active QStash workflow runs affected by a run guard.*/@@ -32,6 +35,11 @@ export interface CancelWorkflowRunsByGuardPolicyResult {workflowUrlPrefix: string;}+interface CancelWorkflowRunsResponse {+ cancelled?: number;+ error?: string;+}+/*** Builds the absolute workflow URL prefix used for QStash cancellation.*@@ -60,17 +68,42 @@ export const buildWorkflowUrlPrefix = ({* - QStash should resolve matching workflow runs by URL prefix.** Expects:- * - `client.cancel` supports `{ urlStartingWith }` for workflow URL prefix cancellation.+ * - `QSTASH_TOKEN` is configured for the Upstash Workflow REST API.** Returns:* - The workflow URL prefix and QStash cancellation count.*/export const cancelWorkflowRunsByGuardPolicy = async (- client: Pick<WorkflowClient, 'cancel'>,params: CancelWorkflowRunsByGuardPolicyParams,): Promise<CancelWorkflowRunsByGuardPolicyResult> => {+ const token = process.env.QSTASH_TOKEN;+ if (!token) throw new Error('QSTASH_TOKEN is required to cancel workflow runs');+const workflowUrlPrefix = buildWorkflowUrlPrefix(params);- const result = await client.cancel({ urlStartingWith: workflowUrlPrefix });+ const qstashUrl = process.env.QSTASH_URL || DEFAULT_QSTASH_URL;++ // NOTICE:+ // `@upstash/[email protected]` serializes `urlStartingWith` as `{ workflowUrl: string }`,+ // but the current Workflow REST API expects the body field to be an array.+ // Source/context: production returned+ // `json: cannot unmarshal string into Go struct field CancelWorkflowRunsRequest.workflowUrl of type []string`;+ // docs: `https://upstash.com/docs/workflow/api-reference/runs/bulk-cancel-workflow-runs`.+ // Removal condition: replace this direct REST call after upgrading the SDK to a version whose+ // `client.cancel` URL-prefix branch sends the current API shape.+ const response = await fetch(new URL('/v2/workflows/runs', qstashUrl), {+ body: JSON.stringify({ workflowUrl: [workflowUrlPrefix] }),+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ method: 'DELETE',+ });++ const result = (await response.json()) as CancelWorkflowRunsResponse;++ if (!response.ok || result.error) {+ throw new Error(result.error || `QStash workflow cancellation failed: ${response.status}`);+ }return {cancelled: result.cancelled || 0,