generated from MapColonies/jobnik-worker-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: polling loop (MAPCO-9805) #21
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
almog8k
wants to merge
13
commits into
master
Choose a base branch
from
feat/polling-loop-MAPCO-9805
base: master
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
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0e36b1d
fix: config values and package0lock.json
almog8k 03fe6f5
feat(worker): implement TaskPoller and workerBuilder for task processing
almog8k 83c3562
feat(container): add QueueClient and ErrorHandler to dependency regis…
almog8k b5ed117
feat(tests): add TaskPoller implementation and associated mocks and f…
almog8k c04706f
feat(ci): update build-and-push.yaml with specific domain and context…
almog8k 1b7c840
ci(workflow): enable manual triggering of build and push workflow
almog8k 9e6cec0
Merge branch 'master' into feat/polling-loop-MAPCO-9805
almog8k 511166b
fix(workflow): remove unnecessary whitespace in build-and-push.yaml
almog8k a5e3641
chore: update @map-colonies/config to version 4.0.1
almog8k 203285a
fix(taskPoller): improve logging of task completion duration and erro…
almog8k 870242a
fix(validationHelper): add debug logging for task parameter validation
almog8k 26c9e62
fix(errorHandler): adding error sterilization
almog8k e6026e8
fix: change class and function exports
almog8k 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,7 +5,7 @@ on: | |
| tags: | ||
| - 'v*' | ||
| workflow_dispatch: | ||
|
|
||
| jobs: | ||
| build_and_push: | ||
| runs-on: ubuntu-latest | ||
|
|
||
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
Large diffs are not rendered by default.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,2 @@ | ||
| export { RecoverableError, UnrecoverableError, ConfigurationError, ValidationError, StrategyNotFoundError } from './errors'; | ||
| export { toError, RecoverableError, UnrecoverableError, ConfigurationError, ValidationError, StrategyNotFoundError } from './errors'; | ||
| export { ErrorHandler } from './errorHandler'; |
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
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 |
|---|---|---|
| @@ -1,14 +1 @@ | ||
| import type { IWorker } from '@map-colonies/jobnik-sdk'; | ||
| import type { FactoryFunction } from 'tsyringe'; | ||
|
|
||
| /** | ||
| * Worker factory function. | ||
| * TODO: Implement worker creation once TaskPoller is implemented. | ||
| * For now, this is a stub to satisfy the containerConfig registration. | ||
| */ | ||
| export const workerBuilder: FactoryFunction<IWorker> = () => { | ||
| // TODO: Replace with actual worker implementation | ||
| // When TaskPoller is ready, this will create and configure the worker | ||
| // For the skeleton, we return a minimal stub | ||
| throw new Error('Worker not implemented - TaskPoller integration pending'); | ||
| }; | ||
| export { workerBuilder } from './worker/workerBuilder'; |
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,142 @@ | ||
| import { setTimeout as sleep } from 'timers/promises'; | ||
| import { inject, injectable } from 'tsyringe'; | ||
| import type { Logger } from '@map-colonies/js-logger'; | ||
| import type { TaskHandler as QueueClient, ITaskResponse } from '@map-colonies/mc-priority-queue'; | ||
| import type { IWorker } from '@map-colonies/jobnik-sdk'; | ||
| import { SERVICES } from '@common/constants'; | ||
| import type { ConfigType } from '@common/config'; | ||
| import type { PollingPairConfig } from '../cleaner/types'; | ||
| import type { StrategyFactory } from '../cleaner/strategies'; | ||
| import { UnrecoverableError, type ErrorHandler } from '../cleaner/errors'; | ||
|
|
||
| /** | ||
| * TaskPoller - Simple bridge to implement IWorker using the old mc-priority-queue SDK | ||
| */ | ||
| @injectable() | ||
| export class TaskPoller implements IWorker { | ||
| private shouldStop = false; | ||
| private readonly dequeueIntervalMs: number; | ||
|
|
||
| public constructor( | ||
| @inject(SERVICES.LOGGER) private readonly logger: Logger, | ||
| @inject(SERVICES.CONFIG) config: ConfigType, | ||
| @inject(SERVICES.QUEUE_CLIENT) private readonly queueClient: QueueClient, | ||
| @inject(SERVICES.STRATEGY_FACTORY) private readonly strategyFactory: StrategyFactory, | ||
| @inject(SERVICES.ERROR_HANDLER) private readonly errorHandler: ErrorHandler, | ||
| @inject(SERVICES.POLLING_PAIRS) private readonly pollingPairs: PollingPairConfig[] | ||
| ) { | ||
| this.dequeueIntervalMs = config.get('queue.dequeueIntervalMs') as unknown as number; //TODO:when we create worker config schema we can remove the cast | ||
| } | ||
|
|
||
| public async start(): Promise<void> { | ||
| this.shouldStop = false; | ||
| await this.poll(); | ||
| } | ||
|
|
||
| public async stop(): Promise<void> { | ||
| this.shouldStop = true; | ||
| await Promise.resolve(); | ||
CL-SHLOMIKONCHA marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // IWorker event methods - delegated to internal EventEmitter (no-op since nothing listens) | ||
| public on(): this { | ||
| return this; | ||
| } | ||
|
|
||
| public off(): this { | ||
| return this; | ||
| } | ||
|
|
||
| public once(): this { | ||
| return this; | ||
| } | ||
|
|
||
| public removeAllListeners(): this { | ||
| return this; | ||
| } | ||
|
|
||
| private async poll(): Promise<void> { | ||
| while (!this.shouldStop) { | ||
| const result = await this.tryDequeue(); | ||
|
|
||
| if (!result) { | ||
| await sleep(this.dequeueIntervalMs); | ||
| continue; | ||
| } | ||
|
|
||
| await this.processTask(result); | ||
| } | ||
| } | ||
|
|
||
| private async tryDequeue(): Promise< | ||
| | { | ||
| task: ITaskResponse<unknown>; | ||
| pair: PollingPairConfig; | ||
| } | ||
| | undefined | ||
| > { | ||
| for (const pair of this.pollingPairs) { | ||
| if (this.shouldStop) { | ||
| return undefined; | ||
| } | ||
|
|
||
| try { | ||
| const task = await this.queueClient.dequeue<unknown>(pair.jobType, pair.taskType); | ||
almog8k marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (task) { | ||
| this.logger.info({ msg: 'Task dequeued', taskId: task.id, taskType: task.type, jobId: task.jobId }); | ||
| return { task, pair }; | ||
| } | ||
| } catch (error) { | ||
| this.logger.error({ msg: 'Dequeue error', error }); | ||
| } | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| private async processTask(dequeued: { task: ITaskResponse<unknown>; pair: PollingPairConfig }): Promise<void> { | ||
| const { task, pair } = dequeued; | ||
| const startTime = Date.now(); | ||
|
|
||
| this.logger.debug({ msg: 'Task started', taskId: task.id, jobId: task.jobId }); | ||
|
|
||
| try { | ||
| if (task.attempts >= pair.maxAttempts) { | ||
CL-SHLOMIKONCHA marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| throw new UnrecoverableError(`Task exceeded max attempts: ${task.attempts}/${pair.maxAttempts}`); | ||
| } | ||
|
|
||
| const strategy = this.strategyFactory.resolveWithContext({ | ||
| jobId: task.jobId, | ||
| taskId: task.id, | ||
| jobType: pair.jobType, | ||
| taskType: pair.taskType, | ||
| }); | ||
|
|
||
| const validated = strategy.validate(task.parameters); | ||
CL-SHLOMIKONCHA marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| await strategy.execute(validated); | ||
|
|
||
| await this.queueClient.ack(task.jobId, task.id); | ||
|
|
||
| const durationMs = Date.now() - startTime; | ||
| this.logger.info({ msg: 'Task completed', taskId: task.id, durationMs }); | ||
| } catch (error) { | ||
| await this.handleTaskFailure(error, task, pair); | ||
| } | ||
| } | ||
|
|
||
| private async handleTaskFailure(error: unknown, task: ITaskResponse<unknown>, pair: PollingPairConfig): Promise<void> { | ||
| const decision = this.errorHandler.handleError({ | ||
| jobId: task.jobId, | ||
| taskId: task.id, | ||
| attemptNumber: task.attempts, | ||
| maxAttempts: pair.maxAttempts, | ||
| error, | ||
| }); | ||
|
|
||
| try { | ||
| await this.queueClient.reject(task.jobId, task.id, decision.shouldRetry, decision.reason); | ||
| } catch (error) { | ||
| this.logger.error({ msg: 'Failed to reject task', taskId: task.id, error }); | ||
| } | ||
| } | ||
| } | ||
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,20 @@ | ||
| import type { FactoryFunction } from 'tsyringe'; | ||
| import type { IWorker } from '@map-colonies/jobnik-sdk'; | ||
| import { SERVICES } from '@common/constants'; | ||
| import type { ConfigType } from '@common/config'; | ||
| import type { WorkerCapabilities, JobDefinitions, PollingPairConfig } from '../cleaner/types'; | ||
| import { buildPollingPairs } from '../cleaner/utils'; | ||
| import { TaskPoller } from './taskPoller'; | ||
|
|
||
| export const workerBuilder: FactoryFunction<IWorker> = (container) => { | ||
| const config = container.resolve<ConfigType>(SERVICES.CONFIG); | ||
|
|
||
| const jobDefinitions = config.get('jobDefinitions') as JobDefinitions; //TODO:when we create worker config schema we can remove the cast | ||
| const workerCapabilities = config.get('worker.capabilities') as unknown as WorkerCapabilities; //TODO:when we create worker config schema we can remove the cast | ||
almog8k marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const pollingPairs = buildPollingPairs(jobDefinitions, workerCapabilities); | ||
|
|
||
| container.register<PollingPairConfig[]>(SERVICES.POLLING_PAIRS, { useValue: pollingPairs }); | ||
|
|
||
| return container.resolve(TaskPoller); | ||
| }; | ||
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.
Uh oh!
There was an error while loading. Please reload this page.