Skip to content

Add server.isPrimaryThread for code an application runs in only one thread #3025

Description

@dawsontoth

Problem

Applications that should run some code in only one thread check server.workerIndex === 0. That works, but the intent is implicit: a reader has to know that index 0 is special. They also have to know two less obvious facts. server.workerIndex reports a worker dedicated to an isolated application as index 0 of 1 (the getter, applicationWorkerIndex). With threads.count: 0, the main thread is that worker. Harper already decides internally where an application's one-thread work belongs: isApplicationPrimaryWorker and runsApplicationCodeSingletons pick pool worker 0 for a shared application, and the dedicated worker for an isolated one. Applications cannot ask that question directly.

#2981 (canary rollout certification) makes the canary the replacement of worker 0, so code gated on server.workerIndex === 0 is part of the load the canary certifies. In review, Kris suggested making this an explicit API, server.isPrimaryThread. It is new public surface, so it was left out of #2981.

Proposal

Add a read-only server.isPrimaryThread. It is true on the thread that runs this application's one-thread work and false elsewhere, decided by the same rule as isApplicationPrimaryWorker. Document it as the supported way to gate one-thread work, and say that the canary's load always includes it.

Open questions

  • Which application? isApplicationPrimaryWorker takes an application name, and root-level plugins load on every thread. A global server.isPrimaryThread, read from a plugin or from shared code, has no application to ask about. A scoped form such as scope.isPrimaryThread would.
  • During a restart. Where replacements pre-start, a replacement boots beside its predecessor, so for a while two threads report index 0, and both would report isPrimaryThread. Document that the flag says where work belongs, not that it runs exactly once. Work that must never overlap needs a lock.
  • Naming. isPrimaryThread, or isPrimaryWorker to match the internal helpers.

Related: #2981, #2315.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    Priority

    P3

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions