ADR 0009 · Code and packages
Run jobs on remote workers through a self-hosted hub
Two new packages let job code run in separate worker processes with no hosted service: TickerNet.Hub turns the scheduler into the hub, and TickerNet.Worker connects to it. Workers and hub prove a shared secret to each other, a worker only touches its own node's jobs, and the scheduler sends one attempt at a time and keeps retries, status and history. The hooks TickerQ's remote executor used keep working.
Context
ADR 0005 removed TickerQ.SDK, TickerQ.RemoteExecutor and the Node SDK, which connect to TickerQ Hub, a hosted service with its own terms. That left TickerNet with no way to run job code outside the scheduler's process, and with public hooks for remote execution in src/: SdkOfflineSkipException, the TickerFunctionProvider merge and resolver members, and the CronTickerEntity.IsSystemPaused column.
Before the repository went public, the maintainer asked for remote execution that TickerNet owns, and for the TickerQ Hub hooks to stay backward compatible while TickerNet gets its own names for them.
At the fork point (3acd0f31), TickerQ's design worked like this. The SDK registered its functions with TickerQ Hub, got the scheduler's address and a shared secret from it, and opened a gRPC worker stream to the scheduler. The scheduler sent each run down that stream. The SDK ran the retry loop and reported each status change back over the stream. The hub endpoints were fixed in code.
Decision
- Two packages.
TickerNet.Hub(AddTickerNetHub,MapTickerNetHub,TickerNetHubOptions,RemoteExecutionException) runs in the scheduler.TickerNet.Worker(AddTickerNetWorker,TickerNetWorkerOptions) runs in each worker app. The scheduler is the hub; nothing else is deployed. - One stream per worker. The worker opens a bidirectional gRPC stream over HTTP/2 to the scheduler, defined in
src/TickerNet.Hub/Protos/worker.proto(packagetickernet.worker.v1, serviceWorkerHub, protocol version 1). It keeps the message shapes and field numbers of TickerQ's worker stream at the fork point and reserves the field numbers of parts TickerNet doesn't use: the hub API key, hosted-hub ids, resync and remove-function commands, status updates from the worker, and log lines. It adds aDrainingmessage, a signature onHelloAckand arejectedflag onExecutionResult. The worker needs only outbound access. - Authentication before anything is read. Scheduler and workers share a secret of at least 32 characters. The worker opens the stream with the headers
tickernet-node,tickernet-nonce,tickernet-timestampandtickernet-signature, a base64 HMAC-SHA256 over the node, nonce and timestamp. The hub checks freshness (5 minutes), the HMAC and the nonce (HelloReplayGuard, in memory) before it reads the stream. The Hello must then arrive within 10 seconds and match the headers. Its own HMAC covers the worker and protocol versions, the worker's concurrency limit and each function's name, cron expression, priority and concurrency limit. The hub rejects control characters and over-long values in signed fields. Signing and checking live inHelloSignature, compiled into both packages. - The hub proves the secret too. The hub signs its
HelloAckover the worker's nonce and the worker id. A worker refuses a server that can't, so it never takes runs from a server that doesn't have the secret. A plainhttphub address on another machine is refused at startup unlessAllowUnencryptedHttpis set. function@node, as a union. Remote functions are stored and scheduled asfunction@node, the rule TickerQ already used, now documented inRemoteFunctionNameinTickerNet.Utilities.RemoteFunctionCatalogpublishes each node's functions intoTickerFunctionProviderwithMergeRemoteFunctionsandMergeRemoteRequestInfo. A node's list is the union of what its workers declared since the hub started, so a replica on another version never removes functions. A worker with no functions changes nothing. Functions stay registered after their workers disconnect. The catalog replaces only names it published, so a local function whose name contains@is left alone.- One attempt per dispatch; the scheduler keeps the rest. The scheduler's own job runner,
TickerExecutionTaskHandler, runs remote functions through a delegate fromRemoteDispatch. The delegate picks a worker of the node that declared the function and isn't draining, preferring the one with the fewest runs in progress, and waits up toWorkerWaitTimeoutif there is none. It sends one attempt with the stored request and turns the result into the outcome the runner expects: success;TaskCanceledExceptionfor a cancel;TerminateExecutionExceptionfor a skip;WorkerOfflineExceptionwhen no worker takes the run, which recordsSkipped;RemoteExecutionExceptionfor a failure, a timeout or a disconnect during the run. A run that never reached a worker (the connection closed first, or the worker rejected it) goes to another worker within the same wait, without using a retry. Retries, cancelling, status, history, logs, tracing and the dashboard stay on the scheduler. This differs from TickerQ's design, where the SDK ran the retry loop and reported each status. - A worker only touches its own node. It can add, update and remove only
function@itsnodejobs, children included. The hub resets status, lock and history fields on added jobs. Updates change only the schedule fields: for time jobsFunction(same node),Description,ExecutionTime,Request,Retries,RetryIntervalsandRunCondition; for cron jobsFunction,Description,Expression,Request,Retries,RetryIntervalsandIsEnabled. A worker can read only the stored request of a run it is executing. The hub handles at most 8 requests from one worker at a time. The hub saves accepted changes through its managers, with the host's lifetime rather than the worker's connection. - After a restart.
HubTaskHandlerwraps the job runner and gives afunction@noderun that has no delegate yet the dispatch delegate for its node, so it waits for a worker instead of being skipped at once. - Liveness and shutdown. Workers send a heartbeat every 15 seconds by default.
WorkerLivenessMonitordrops a worker that sends nothing withinWorkerTimeout(45 seconds), and its outstanding runs fail. A stopping worker sendsDraining, rejects new runs, finishes and reports the runs it has, then disconnects; it cancels runs still going afterShutdownTimeout(25 seconds, under the host's 30-second default). When the scheduler stops, the hub sends each workerDisconnectand closes its stream at once instead of holding shutdown open. - Cron jobs.
RemoteCronSeedercreates and updates cron jobs for worker functions with a cron expression throughMigrateDefinedCronTickers, and never deletes one.WorkerPauseMonitorsetsIsSystemPausedon remote cron jobs while no connected worker that declares the function can take runs, so a seeded cron job whose function no worker declares stays paused until someone removes it. Local functions are never paused. WithPauseCronTickersWhileOfflineoff, the monitor clears earlier pauses once at startup. Seeding and pausing share a lock (CronWriteGate), so neither overwrites the other. Cron seeding at startup no longer deletes seeded cron jobs forfunction@nodein the in-memory, EF Core, MongoDB and Redis stores. - The worker side.
AddTickerNetWorkerturns off the background services and cron seeding.WorkerClientkeeps the stream open, reconnects with backoff, runs functions within the worker-wide and per-function concurrency limits, honours cancels, rejects runs of functions it doesn't offer, and drains on shutdown.RemotePersistenceProvidersends add, update and remove requests to the scheduler, and throwsNotSupportedExceptionfor reads and queries. - Jobs dispatched straight away run with the host's lifetime.
TickerNetDispatcherno longer passes the caller'sCancellationTokento the jobs it dispatches at once, for example a time job added for now withAddAsync. They use the host's stopping token. A worker's connection, or an HTTP request, ending could otherwise cancel a job it had just added, or leave itInProgress. - The old hooks keep working.
SdkOfflineSkipExceptionis kept as an obsolete subclass of the newWorkerOfflineException, and the job runner handles both. TheTickerFunctionProviderhooks,IsSystemPausedand the internalRetriesandRetryIntervalsonTickerFunctionContextare kept, with comments that describe TickerNet's hub.
Alternatives considered
- Restore the TickerQ Hub clients under TickerNet names, still connecting to TickerQ Hub. Rejected: they depend on a paid hosted service with its own terms, which TickerNet doesn't control and whose protocol can change at any time, and its endpoints are fixed in the client code.
- Keep only the hooks, or remove them under a new ADR, with no remote execution. Rejected by the maintainer, who asked for TickerNet's own remote execution and compatibility with existing TickerQ Hub hooks and data.
- Delete seeded cron jobs a node no longer declares. The first version did this. Rejected: a replica on another version, or one started without its functions, would delete cron jobs, and their history, that other replicas still serve. They are paused instead.
- Keep TickerQ's split, where the worker runs the retry loop and reports each status. Not chosen. With one attempt per dispatch, retries, cancelling, status and tracing have a single code path on the scheduler, a retry can go to another replica, and two processes never write the same job's status.
Consequences
- Job code can run in separate processes, behind NAT or in another cluster, with the scheduler as the only server. The Remote workers guide covers set-up and behaviour.
- New public API: the two packages, plus
RemoteFunctionNameandWorkerOfflineExceptioninTickerNet.Utilities.SdkOfflineSkipExceptionis obsolete. - New dependencies:
Grpc.AspNetCore.Serverin the hub,Grpc.Net.Clientin the worker,Google.Protobufin both, andGrpc.Toolsat build time. The scheduler must accept HTTP/2. - Anyone with the shared secret can connect as any node: take that node's runs, with their requests, report their results, and change that node's jobs. They can't touch local jobs. Without TLS the traffic can be read and changed, which is why plain HTTP to another machine needs
AllowUnencryptedHttp. - Rolling deploys are safe: draining workers finish their runs, runs that never reached a worker go to another one without using a retry, and replicas on different versions don't remove each other's functions or cron jobs.
- Seeded cron jobs are never deleted by the hub. One for a function no worker declares any more stays paused until someone removes it from the dashboard.
- Behaviour change in the core, for all apps: jobs dispatched straight away no longer run with the caller's
CancellationToken, but with the host's stopping token. TickerQ, and TickerNet before this change, used the caller's token. Code that relied on cancelling such a job through that token must useTickerCancellationTokenManager.RequestTickerCancellationById. The migration guide notes it. - Extra properties on custom entity subclasses can't be changed from workers; change them on the scheduler.
TickerQ.SDKworkers can't connect: the gRPC package and service names differ, the authentication is new, and the SDK only connects through TickerQ Hub. Workers move toTickerNet.Worker. Jobs stored asfunction@nodecarry over.- Known limits (still true in 1.0.0): with several scheduler instances every worker must list each instance's address, workers can't read jobs other than their current runs' requests, there is no per-run log forwarding to the dashboard, and
SkipIfAlreadyRunning()only sees runs on the same worker. - Rule for later changes to
worker.proto: never reuse a field number, reserve the numbers of removed fields, and raiseHelloSignature.ProtocolVersionfor an incompatible change. TickerNet.UtilitiesandTickerNetexpose internals toTickerNet.Hub,TickerNet.WorkerandTickerNet.Hub.Tests.
Where it lives
src/TickerNet.Hub/:Protos/worker.proto,Protocol/HelloSignature.cs,TickerNetHubServiceExtensions.cs,TickerNetHubOptions.cs,RemoteExecutionException.cs, andInternal/(WorkerStreamService.cs,WorkerConnection.cs,WorkerRegistry.cs,RemoteDispatch.cs,RemoteFunctionCatalog.cs,RemoteCronSeeder.cs(withCronWriteGate),RemotePayloadLoader.cs,HubTaskHandler.cs,HelloReplayGuard.cs,WorkerMonitors.cs)src/TickerNet.Worker/:TickerNetWorkerServiceExtensions.cs,TickerNetWorkerOptions.cs, andInternal/(WorkerClient.cs,RemotePersistenceProvider.cs,FunctionManifest.cs)src/TickerNet.Utilities/RemoteFunctionName.cs,Exceptions/WorkerOfflineException.cs,Exceptions/SdkOfflineSkipException.cs,TickerFunctionProvider.cs,Entities/CronTickerEntity.cssrc/TickerNet/Src/TickerExecutionTaskHandler.csandsrc/TickerNet/Src/Dispatcher/TickerNetDispatcher.csMigrateDefinedCronTickersinsrc/TickerNet/Src/Provider/TickerInMemoryPersistenceProvider.cs,src/TickerNet.EntityFrameworkCore/Infrastructure/BasePersistenceProvider.cs,src/TickerNet.MongoDB/Infrastructure/TickerMongoPersistenceProvider.csandsrc/TickerNet.Caching.StackExchangeRedis/Infrastructure/BaseRedisPersistenceProvider.cstests/TickerNet.Hub.Tests/(includingHubSafetyTests.cs),tests/TickerNet.Tests/TickerNetDispatcherExtendedTests.cs,samples/TickerNet.Sample.Hub,samples/TickerNet.Sample.HubWorkersite/remote-workers.html
Sources
7a56abdBackward compatibility with TickerQ, and a self-hosted hub for remote workers302fc65Remove TickerQ Hub, upstream CI, CLA and cacheshub/at3acd0f31, TickerQ's remote executor and SDK at the fork point, MIT OR Apache-2.0