-
Notifications
You must be signed in to change notification settings - Fork 10
feat(agent): proxify ws executor call #1522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arnaud-moncel
wants to merge
1
commit into
feat/prd-214-setup-workflow-executor-package
Choose a base branch
from
feat/wf-executor-proxy
base: feat/prd-214-setup-workflow-executor-package
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
87 changes: 87 additions & 0 deletions
87
packages/agent/src/routes/workflow/workflow-executor-proxy.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import type { ForestAdminHttpDriverServices } from '../../services'; | ||
| import type { AgentOptionsWithDefaults } from '../../types'; | ||
| import type KoaRouter from '@koa/router'; | ||
| import type { Context } from 'koa'; | ||
|
|
||
| import { request as httpRequest } from 'http'; | ||
| import { request as httpsRequest } from 'https'; | ||
|
|
||
| import { HttpCode, RouteType } from '../../types'; | ||
| import BaseRoute from '../base-route'; | ||
|
|
||
| export default class WorkflowExecutorProxyRoute extends BaseRoute { | ||
| readonly type = RouteType.PrivateRoute; | ||
| private readonly executorUrl: URL; | ||
|
|
||
| constructor(services: ForestAdminHttpDriverServices, options: AgentOptionsWithDefaults) { | ||
| super(services, options); | ||
| // Remove trailing slash for clean URL joining | ||
| this.executorUrl = new URL(options.workflowExecutorUrl.replace(/\/+$/, '')); | ||
| } | ||
|
|
||
| private static readonly AGENT_PREFIX = '/_internal/workflow-executions'; | ||
| private static readonly EXECUTOR_PREFIX = '/runs'; | ||
|
|
||
| setupRoutes(router: KoaRouter): void { | ||
| router.get('/_internal/workflow-executions/:runId', this.handleProxy.bind(this)); | ||
| router.post('/_internal/workflow-executions/:runId/trigger', this.handleProxy.bind(this)); | ||
| router.patch( | ||
| '/_internal/workflow-executions/:runId/steps/:stepIndex/pending-data', | ||
| this.handleProxy.bind(this), | ||
| ); | ||
| } | ||
|
|
||
| private async handleProxy(context: Context): Promise<void> { | ||
| // Rewrite /_internal/workflow-executions/... → /runs/... | ||
| const executorPath = context.path.replace( | ||
| WorkflowExecutorProxyRoute.AGENT_PREFIX, | ||
| WorkflowExecutorProxyRoute.EXECUTOR_PREFIX, | ||
| ); | ||
| const targetUrl = new URL(executorPath, this.executorUrl); | ||
|
|
||
| const response = await this.forwardRequest(context.method, targetUrl, context.request.body); | ||
|
|
||
| context.response.status = response.status; | ||
| context.response.body = response.body; | ||
| } | ||
|
|
||
| private forwardRequest( | ||
| method: string, | ||
| url: URL, | ||
| body?: unknown, | ||
| ): Promise<{ status: number; body: unknown }> { | ||
| const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest; | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| const req = requestFn( | ||
| url, | ||
| { method, headers: { 'Content-Type': 'application/json' } }, | ||
| res => { | ||
| const chunks: Uint8Array[] = []; | ||
| res.on('data', chunk => chunks.push(chunk)); | ||
| res.on('end', () => { | ||
| const raw = Buffer.concat(chunks).toString('utf-8'); | ||
| let parsed: unknown; | ||
|
|
||
| try { | ||
| parsed = JSON.parse(raw); | ||
| } catch { | ||
| parsed = raw; | ||
| } | ||
|
|
||
| resolve({ status: res.statusCode ?? HttpCode.InternalServerError, body: parsed }); | ||
| }); | ||
| res.on('error', reject); | ||
| }, | ||
| ); | ||
|
|
||
| req.on('error', reject); | ||
|
|
||
| if (body && method !== 'GET') { | ||
| req.write(JSON.stringify(body)); | ||
| } | ||
|
|
||
| req.end(); | ||
| }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
201 changes: 201 additions & 0 deletions
201
packages/agent/test/routes/workflow/workflow-executor-proxy.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| import http from 'http'; | ||
|
|
||
| import { createMockContext } from '@shopify/jest-koa-mocks'; | ||
|
|
||
| import WorkflowExecutorProxyRoute from '../../../src/routes/workflow/workflow-executor-proxy'; | ||
| import { RouteType } from '../../../src/types'; | ||
| import * as factories from '../../__factories__'; | ||
|
|
||
| describe('WorkflowExecutorProxyRoute', () => { | ||
| const options = factories.forestAdminHttpDriverOptions.build(); | ||
| const services = factories.forestAdminHttpDriverServices.build(); | ||
| const router = factories.router.mockAllMethods().build(); | ||
|
|
||
| let executorServer: http.Server; | ||
| let executorPort: number; | ||
|
|
||
| // Start a real HTTP server to act as the workflow executor | ||
| beforeAll(async () => { | ||
| executorServer = http.createServer((req, res) => { | ||
| const chunks: Uint8Array[] = []; | ||
| req.on('data', chunk => chunks.push(chunk)); | ||
| req.on('end', () => { | ||
| const body = Buffer.concat(chunks).toString('utf-8'); | ||
|
|
||
| res.setHeader('Content-Type', 'application/json'); | ||
|
|
||
| if (req.url?.includes('not-found')) { | ||
| res.writeHead(404); | ||
| res.end(JSON.stringify({ error: 'Run not found or unavailable' })); | ||
| } else if (req.method === 'GET' && req.url?.match(/^\/runs\/[\w-]+$/)) { | ||
| res.writeHead(200); | ||
| res.end(JSON.stringify({ steps: [{ stepId: 's1', status: 'success' }] })); | ||
| } else if (req.method === 'POST' && req.url?.match(/^\/runs\/[\w-]+\/trigger$/)) { | ||
| res.writeHead(200); | ||
| res.end(JSON.stringify({ triggered: true })); | ||
| } else if ( | ||
| req.method === 'PATCH' && | ||
| req.url?.match(/^\/runs\/[\w-]+\/steps\/\d+\/pending-data$/) | ||
| ) { | ||
| const parsed = body ? JSON.parse(body) : {}; | ||
| res.writeHead(200); | ||
| res.end(JSON.stringify({ updated: true, received: parsed })); | ||
| } else { | ||
| res.writeHead(404); | ||
| res.end(JSON.stringify({ error: 'Not found' })); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| executorServer.listen(0, () => { | ||
| executorPort = (executorServer.address() as { port: number }).port; | ||
| resolve(); | ||
| }); | ||
| executorServer.on('error', reject); | ||
| }); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await new Promise<void>((resolve, reject) => { | ||
| executorServer.close(err => (err ? reject(err) : resolve())); | ||
| }); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| const buildOptions = (url: string) => | ||
| factories.forestAdminHttpDriverOptions.build({ workflowExecutorUrl: url }); | ||
|
|
||
| describe('constructor', () => { | ||
| test('should have RouteType.PrivateRoute', () => { | ||
| const route = new WorkflowExecutorProxyRoute(services, buildOptions('http://localhost:4001')); | ||
|
|
||
| expect(route.type).toBe(RouteType.PrivateRoute); | ||
| }); | ||
| }); | ||
|
|
||
| describe('setupRoutes', () => { | ||
| test('should register GET, POST and PATCH routes', () => { | ||
| const route = new WorkflowExecutorProxyRoute(services, buildOptions('http://localhost:4001')); | ||
| route.setupRoutes(router); | ||
|
|
||
| expect(router.get).toHaveBeenCalledWith( | ||
| '/_internal/workflow-executions/:runId', | ||
| expect.any(Function), | ||
| ); | ||
| expect(router.post).toHaveBeenCalledWith( | ||
| '/_internal/workflow-executions/:runId/trigger', | ||
| expect.any(Function), | ||
| ); | ||
| expect(router.patch).toHaveBeenCalledWith( | ||
| '/_internal/workflow-executions/:runId/steps/:stepIndex/pending-data', | ||
| expect.any(Function), | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('handleProxy', () => { | ||
| test('should forward GET /runs/:runId and return executor response', async () => { | ||
| const route = new WorkflowExecutorProxyRoute( | ||
| services, | ||
| buildOptions(`http://localhost:${executorPort}`), | ||
| ); | ||
|
|
||
| const context = createMockContext({ | ||
| customProperties: { params: { runId: 'run-123' } }, | ||
| }); | ||
| Object.defineProperty(context, 'path', { | ||
| value: '/_internal/workflow-executions/run-123', | ||
| }); | ||
|
|
||
| await (route as any).handleProxy(context); | ||
|
|
||
| expect(context.response.status).toBe(200); | ||
| expect(context.response.body).toEqual({ | ||
| steps: [{ stepId: 's1', status: 'success' }], | ||
| }); | ||
| }); | ||
|
|
||
| test('should forward POST /runs/:runId/trigger and return executor response', async () => { | ||
| const route = new WorkflowExecutorProxyRoute( | ||
| services, | ||
| buildOptions(`http://localhost:${executorPort}`), | ||
| ); | ||
|
|
||
| const context = createMockContext({ | ||
| method: 'POST', | ||
| customProperties: { params: { runId: 'run-456' } }, | ||
| }); | ||
| Object.defineProperty(context, 'path', { | ||
| value: '/_internal/workflow-executions/run-456/trigger', | ||
| }); | ||
|
|
||
| await (route as any).handleProxy(context); | ||
|
|
||
| expect(context.response.status).toBe(200); | ||
| expect(context.response.body).toEqual({ triggered: true }); | ||
| }); | ||
|
|
||
| test('should forward error status from executor', async () => { | ||
| const route = new WorkflowExecutorProxyRoute( | ||
| services, | ||
| buildOptions(`http://localhost:${executorPort}`), | ||
| ); | ||
|
|
||
| const context = createMockContext({ | ||
| customProperties: { params: { runId: 'not-found' } }, | ||
| }); | ||
| Object.defineProperty(context, 'path', { | ||
| value: '/_internal/workflow-executions/not-found', | ||
| }); | ||
|
|
||
| await (route as any).handleProxy(context); | ||
|
|
||
| expect(context.response.status).toBe(404); | ||
| expect(context.response.body).toEqual({ error: 'Run not found or unavailable' }); | ||
| }); | ||
|
|
||
| test('should forward PATCH pending-data and pass request body', async () => { | ||
| const route = new WorkflowExecutorProxyRoute( | ||
| services, | ||
| buildOptions(`http://localhost:${executorPort}`), | ||
| ); | ||
|
|
||
| const context = createMockContext({ | ||
| method: 'PATCH', | ||
| customProperties: { params: { runId: 'run-789', stepIndex: '2' } }, | ||
| requestBody: { fieldValues: { name: 'updated' } }, | ||
| }); | ||
| Object.defineProperty(context, 'path', { | ||
| value: '/_internal/workflow-executions/run-789/steps/2/pending-data', | ||
| }); | ||
|
|
||
| await (route as any).handleProxy(context); | ||
|
|
||
| expect(context.response.status).toBe(200); | ||
| expect(context.response.body).toEqual({ | ||
| updated: true, | ||
| received: { fieldValues: { name: 'updated' } }, | ||
| }); | ||
| }); | ||
|
|
||
| test('should reject when executor is unreachable', async () => { | ||
| const route = new WorkflowExecutorProxyRoute( | ||
| services, | ||
| buildOptions('http://localhost:1'), // port that should be unreachable | ||
| ); | ||
|
|
||
| const context = createMockContext({ | ||
| customProperties: { params: { runId: 'run-789' } }, | ||
| }); | ||
| Object.defineProperty(context, 'path', { | ||
| value: '/_internal/workflow-executions/run-789', | ||
| }); | ||
|
|
||
| await expect((route as any).handleProxy(context)).rejects.toThrow(); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| **/node_modules | ||
| **/dist | ||
| **/coverage | ||
| **/.git | ||
| **/*.test.ts | ||
| **/test |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium
workflow/workflow-executor-proxy.ts:36handleProxyusescontext.pathto construct the target URL, butpathcontains only the pathname without the query string. Requests with query parameters (e.g.,?foo=bar) lose those parameters when forwarded to the executor. Consider usingcontext.urlinstead, which includes both the pathname and query string.🚀 Reply "fix it for me" or copy this AI Prompt for your agent: