-
Notifications
You must be signed in to change notification settings - Fork 428
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(orchestrator): implement task processor (#2221)
## Describe your changes This PR is implementing the orchestrator processor which, for now, is being run by jobs. The processor is behind a flag `flag:orchestrator:dryrun:process:global`. It is still in dryrun mode since no real processing is happening, tasks are either immediately succeeded or failed. It is the last step before actually processing webhook/actions ### Notes - I have added orchestrator endpoints to support dequeueing, set task state, heartbeat and their respective functions in the orchestrator client - A processor dequeues tasks in a infinite loop and process the task via the `process` functions passed as argument. - A processor also check if pending tasks have been completed (ie: they might have expired or be cancelled) and send abort signal. - In jobs, 2 processor worker_thread are being started. One for action and one for webhook to reproduce what we have right now with webhooks being in a separate temporal queue Tested in staging ## Checklist before requesting a review (skip if just adding/editing APIs & templates) - [x] I added tests, otherwise the reason is: - [ ] I added observability, otherwise the reason is: - [ ] I added analytics, otherwise the reason is:
- Loading branch information
Showing
39 changed files
with
1,462 additions
and
265 deletions.
There are no files selected for viewing
This file contains 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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 was deleted.
Oops, something went wrong.
This file contains 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,3 @@ | ||
import { ENVS, parseEnvs } from '@nangohq/utils'; | ||
|
||
export const envs = parseEnvs(ENVS.required({ ORCHESTRATOR_SERVICE_URL: true })); |
This file contains 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,34 @@ | ||
import type { OrchestratorTask, TaskWebhook, TaskAction } from '@nangohq/nango-orchestrator'; | ||
import type { JsonValue } from 'type-fest'; | ||
import { Err, Ok } from '@nangohq/utils'; | ||
import type { Result } from '@nangohq/utils'; | ||
|
||
export async function handler(task: OrchestratorTask): Promise<Result<JsonValue>> { | ||
task.abortController.signal.onabort = () => { | ||
abort(task); | ||
}; | ||
if (task.isAction()) { | ||
return action(task); | ||
} | ||
if (task.isWebhook()) { | ||
return webhook(task); | ||
} | ||
return Err(`Unreachable`); | ||
} | ||
|
||
async function abort(_task: OrchestratorTask): Promise<Result<void>> { | ||
// TODO: Implement abort processing | ||
return Ok(undefined); | ||
} | ||
|
||
async function action(task: TaskAction): Promise<Result<JsonValue>> { | ||
// TODO: Implement action processing | ||
// Returning a successful result for now | ||
return Ok({ taskId: task.id, dryrun: true }); | ||
} | ||
|
||
async function webhook(task: TaskWebhook): Promise<Result<JsonValue>> { | ||
// TODO: Implement action processing | ||
// Returning an error for now | ||
return Err(`Not implemented: ${JSON.stringify({ taskId: task.id })}`); | ||
} |
This file contains 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,50 @@ | ||
import { getLogger } from '@nangohq/utils'; | ||
import { ProcessorWorker } from './processor.worker.js'; | ||
|
||
const logger = getLogger('jobs.processor'); | ||
|
||
export class Processor { | ||
private orchestratorServiceUrl: string; | ||
private workers: ProcessorWorker[]; | ||
private stopped: boolean; | ||
|
||
constructor(orchestratorServiceUrl: string) { | ||
this.orchestratorServiceUrl = orchestratorServiceUrl; | ||
this.workers = []; | ||
this.stopped = true; | ||
} | ||
|
||
isStopped() { | ||
return this.stopped; | ||
} | ||
|
||
start() { | ||
logger.info('Starting task processors'); | ||
try { | ||
const actionWorker = new ProcessorWorker({ | ||
orchestratorUrl: this.orchestratorServiceUrl, | ||
groupKey: 'action', | ||
maxConcurrency: 100 | ||
}); | ||
actionWorker.start(); | ||
|
||
const webhookWorker = new ProcessorWorker({ | ||
orchestratorUrl: this.orchestratorServiceUrl, | ||
groupKey: 'webhook', | ||
maxConcurrency: 50 | ||
}); | ||
webhookWorker.start(); | ||
this.workers = [actionWorker, webhookWorker]; | ||
this.stopped = false; | ||
} catch (e) { | ||
logger.error(e); | ||
} | ||
} | ||
|
||
stop() { | ||
if (this.workers) { | ||
this.workers.forEach((worker) => worker.stop()); | ||
} | ||
this.stopped = true; | ||
} | ||
} |
This file contains 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,11 @@ | ||
import { isMainThread, parentPort, workerData } from 'node:worker_threads'; | ||
import { getLogger } from '@nangohq/utils'; | ||
import { ProcessorChild } from './processor.worker.js'; | ||
|
||
const logger = getLogger('processor.worker.boot'); | ||
|
||
if (!isMainThread && parentPort) { | ||
new ProcessorChild(parentPort, workerData); | ||
} else { | ||
logger.error('Processor should not be instantiated in the main thread'); | ||
} |
This file contains 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,94 @@ | ||
import * as fs from 'fs'; | ||
import type { MessagePort } from 'node:worker_threads'; | ||
import { Worker, isMainThread } from 'node:worker_threads'; | ||
import { getLogger, stringifyError } from '@nangohq/utils'; | ||
import { OrchestratorClient, OrchestratorProcessor } from '@nangohq/nango-orchestrator'; | ||
import { handler } from './handler.js'; | ||
|
||
const logger = getLogger('jobs.processor.worker'); | ||
|
||
export class ProcessorWorker { | ||
private worker: Worker | null; | ||
constructor({ orchestratorUrl, groupKey, maxConcurrency }: { orchestratorUrl: string; groupKey: string; maxConcurrency: number }) { | ||
if (isMainThread) { | ||
const url = new URL('../../dist/processor/processor.worker.boot.js', import.meta.url); | ||
if (!fs.existsSync(url)) { | ||
throw new Error(`Processor worker boot script not found at ${url}`); | ||
} | ||
this.worker = new Worker(url, { workerData: { orchestratorUrl, groupKey, maxConcurrency } }); | ||
this.worker.on('error', (err) => { | ||
logger.error(`ProcessorWorker exited with error: ${stringifyError(err)}`); | ||
}); | ||
this.worker.on('exit', (code) => { | ||
if (code !== 0) { | ||
logger.error(`ProcessorWorker exited with exit code: ${code}`); | ||
} | ||
}); | ||
} else { | ||
throw new Error('ProcessorWorker should be instantiated in the main thread'); | ||
} | ||
} | ||
|
||
start(): void { | ||
this.worker?.postMessage('start'); | ||
} | ||
|
||
stop(): void { | ||
if (this.worker) { | ||
this.worker.postMessage('stop'); | ||
this.worker = null; | ||
} | ||
} | ||
} | ||
|
||
export class ProcessorChild { | ||
private parent: MessagePort; | ||
private processor: OrchestratorProcessor; | ||
private opts: { | ||
orchestratorUrl: string; | ||
groupKey: string; | ||
maxConcurrency: number; | ||
}; | ||
|
||
constructor(parent: MessagePort, workerData: { orchestratorUrl: string; groupKey: string; maxConcurrency: number }) { | ||
if (isMainThread) { | ||
throw new Error('Processor should not be instantiated in the main thread'); | ||
} | ||
if (!workerData.orchestratorUrl || !workerData.groupKey || workerData.maxConcurrency <= 0) { | ||
throw new Error( | ||
`Missing required options for processor worker. Expecting orchestratorUrl, groupKey, maxConcurrency > 0, got: ${JSON.stringify(workerData)}` | ||
); | ||
} | ||
this.opts = workerData; | ||
this.parent = parent; | ||
this.parent.on('message', async (msg: 'start' | 'stop') => { | ||
switch (msg) { | ||
case 'start': | ||
await this.start(); | ||
break; | ||
case 'stop': | ||
this.stop(); | ||
break; | ||
} | ||
}); | ||
const client = new OrchestratorClient({ baseUrl: this.opts.orchestratorUrl }); | ||
this.processor = new OrchestratorProcessor({ | ||
handler, | ||
opts: { | ||
orchestratorClient: client, | ||
groupKey: this.opts.groupKey, | ||
maxConcurrency: this.opts.maxConcurrency | ||
} | ||
}); | ||
} | ||
|
||
async start(): Promise<void> { | ||
logger.info(`Starting Processor: ${JSON.stringify(this.opts)}`); | ||
this.processor.start(); | ||
} | ||
|
||
stop(): void { | ||
logger.info(`Stopping Processor: ${JSON.stringify(this.opts)}`); | ||
this.processor.stop(); | ||
} | ||
} |
This file contains 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 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 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
Oops, something went wrong.