Merge fix/review-2026-12-phase2 (2026-12-02 review fix plan)
This commit is contained in:
@@ -75,7 +75,9 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid.
|
||||
},
|
||||
"Protocol": {
|
||||
"WorkerProtocolVersion": 1,
|
||||
"MaxGrpcMessageBytes": 16777216
|
||||
"MaxGrpcMessageBytes": 16777216,
|
||||
"Http2KeepAlivePingDelaySeconds": 60,
|
||||
"Http2KeepAlivePingTimeoutSeconds": 10
|
||||
},
|
||||
"Galaxy": {
|
||||
"ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;",
|
||||
@@ -145,7 +147,7 @@ launch CWD (SEC-01, SEC-33).
|
||||
| `MxGateway:Worker:ExecutablePath` | `src\ZB.MOM.WW.MxGateway.Worker\bin\x86\Release\ZB.MOM.WW.MxGateway.Worker.exe` | Path to the x86 worker executable launched for each gateway session. The path must be valid and point to a `.exe` file. |
|
||||
| `MxGateway:Worker:WorkingDirectory` | `null` | Optional working directory for the worker process. When set, it must be a valid filesystem path. |
|
||||
| `MxGateway:Worker:RequiredArchitecture` | `X86` | Required Portable Executable architecture for the worker. Supported values are `X86` and `X64`; MXAccess parity uses `X86`. |
|
||||
| `MxGateway:Worker:StartupTimeoutSeconds` | `30` | Total startup budget for process launch, startup probe, pipe connect, handshake, and worker readiness. |
|
||||
| `MxGateway:Worker:StartupTimeoutSeconds` | `30` | Total startup budget for process launch, startup probe, pipe connect, handshake, and worker readiness. Also conveyed to the worker (`MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS`) as the deadline for its own startup handshake, so a worker whose gateway died mid-launch exits instead of hanging in MXAccess initialization. |
|
||||
| `MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds` | `2000` | Per-attempt timeout used by the worker named-pipe connect retry path. The overall pipe connection still stays under the startup budget. |
|
||||
| `MxGateway:Worker:WriteCompletionWaitMilliseconds` | `1500` | Bounded wait the worker holds a unary write reply (`Write`/`Write2`/`WriteSecured`/`WriteSecured2`; bulk writes excluded) for the matching MXAccess `OnWriteComplete` callback, so the reply's `statuses` carry the real commit outcome. `0` disables the wait (pure fire-and-forget replies). Must be `>= 0`. The gateway conveys the value to the worker via the `MXGATEWAY_WORKER_WRITE_COMPLETION_WAIT_MS` environment variable. Consumers that time their own writes must budget above this wait: OtOpcUa's GalaxyDriver wraps gateway writes in a 2 s Tier A resilience timeout, so a deployment raising this option past ~2000 must raise that driver `ResilienceConfig` write timeout in step or slow-but-successful commits surface as consumer-side failures. |
|
||||
| `MxGateway:Worker:EventQueueCapacity` | `10000` | Capacity, in events, of the worker's outbound MXAccess event queue. Must be between `1000` and `1000000`. This is burst headroom, not a throttle: the queue has no drop policy, so filling it records a `QueueOverflow` worker fault and faults the session. Raise it for sessions whose subscription set can outrun the drain loop (large advise sets, slow event consumers); the backing queue pre-allocates its slots, so the ceiling keeps a mistyped value from committing the 32-bit worker to an outsized allocation. The gateway conveys the value to the worker via the `MXGATEWAY_EVENT_QUEUE_CAPACITY` environment variable; a missing or unusable value leaves the worker on the 10000 default rather than failing the session. |
|
||||
@@ -153,7 +155,7 @@ launch CWD (SEC-01, SEC-33).
|
||||
| `MxGateway:Worker:HeartbeatCheckIntervalSeconds` | `5` | How often the gateway checks the age of the worker's last heartbeat against `HeartbeatGraceSeconds`. This is the gateway-side check cadence only; the worker's send interval is `WorkerHeartbeatSendIntervalSeconds`. Must be greater than zero. |
|
||||
| `MxGateway:Worker:HeartbeatIntervalSeconds` | *(unset)* | **Deprecated** alias of `HeartbeatCheckIntervalSeconds` (mxaccessgw#192). The old name implied the worker's send interval, but the value only ever set the gateway's check cadence, which is what it still sets. Setting both keys fails validation. |
|
||||
| `MxGateway:Worker:HeartbeatGraceSeconds` | `15` | Maximum age of the last worker heartbeat before the gateway faults the worker. This must be greater than or equal to `HeartbeatCheckIntervalSeconds`, and strictly greater than `WorkerHeartbeatSendIntervalSeconds` — a grace at or below the worker's send interval declares a healthy worker dead between two heartbeats (mxaccessgw#218). |
|
||||
| `MxGateway:Worker:HeartbeatStuckCeilingSeconds` | `75` | Ceiling on the gateway's in-flight-command heartbeat skip. While a command is pending the gateway tolerates a stale heartbeat, because the worker STA is busy inside a COM call; once the oldest pending command is older than this, the watchdog faults the worker anyway so a truly stuck COM call cannot hide a dead worker. Must be greater than or equal to `HeartbeatGraceSeconds`. The worker's own watchdog has its separate ceiling, `WorkerHeartbeatStuckCeilingSeconds`. |
|
||||
| `MxGateway:Worker:HeartbeatStuckCeilingSeconds` | `75` | Ceiling on the gateway's in-flight-command heartbeat skip. While a command is pending the gateway tolerates a stale heartbeat, because the worker STA is busy inside a COM call; once the oldest pending command is older than this, or the last heartbeat is, the watchdog faults the worker anyway so a truly stuck COM call cannot hide a dead worker. The heartbeat-age bound is what stops a client that keeps retrying timed-out commands from holding the skip open: a command that times out leaves the pending set, so with the default 30 s command timeout no pending command ever reaches 75 s. Heartbeat age is measured on the monotonic clock, so a wall-clock step does not fault workers. Must be greater than or equal to `HeartbeatGraceSeconds`. The worker's own watchdog has its separate ceiling, `WorkerHeartbeatStuckCeilingSeconds`. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatSendIntervalSeconds` | `5` | Interval at which the worker sends heartbeats to the gateway. Must be between `1` and `86400`, and below `HeartbeatGraceSeconds`. Conveyed to the worker via `MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS`; a missing or invalid value leaves the worker on 5 s. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatGraceSeconds` | `15` | The worker's own STA-watchdog grace: how long STA activity may go stale before the worker faults `StaHung` (no command in flight). Must be between `1` and `86400` and below `WorkerHeartbeatStuckCeilingSeconds`; validation uses this configured value, not a copied constant (mxaccessgw#224). Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS`; a missing or invalid value, or a grace the ceiling does not exceed, leaves the worker on 15 s. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatStuckCeilingSeconds` | `75` | Ceiling on the worker's own STA watchdog: once STA activity has been stale this long, the worker faults `StaHung` even while a command is in flight. Must be greater than `WorkerHeartbeatGraceSeconds` and at most `86400`. Raise it together with `HeartbeatStuckCeilingSeconds` for deployments that run very long bulk operations. Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS`; a missing or invalid value leaves the worker on 75 s. |
|
||||
@@ -440,8 +442,12 @@ is **not yet available**.
|
||||
|--------|---------|-------------|
|
||||
| `MxGateway:Protocol:WorkerProtocolVersion` | `1` | Worker IPC protocol version expected by the gateway and worker. This must match `GatewayContractInfo.WorkerProtocolVersion`. |
|
||||
| `MxGateway:Protocol:MaxGrpcMessageBytes` | `16777216` | Public gRPC max send and receive message size in bytes. The same default is used by official clients. The validator allows values from `1024` through `268435456`, and requires `MxGateway:Worker:MaxMessageBytes` to exceed this by at least the 64 KiB worker-frame envelope reserve and by no more than twice that reserve, so a `DrainEvents` reply budgeted at the pipe maximum still fits this send cap (see the Worker options). |
|
||||
| `MxGateway:Protocol:Http2KeepAlivePingDelaySeconds` | `60` | Seconds an HTTP/2 connection may go without receiving a frame before the gateway sends a keepalive PING (Kestrel `Limits.Http2.KeepAlivePingDelay`). `0` turns server pings off. Must be between `0` and `86400`. Without server pings, a client that vanished without closing its connection (power loss, a firewall or NAT idle drop) keeps its `StreamEvents` call open on a quiet session indefinitely: the session's subscriber slot stays taken, so the client's own resume is refused with `ResourceExhausted` (`EventSubscriberAlreadyActive`), and the session and its x86 worker are never swept. With pings, the dead peer is detected within the delay plus the timeout and the subscriber detaches. |
|
||||
| `MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds` | `10` | Seconds the gateway waits for any frame after a keepalive PING before it closes the connection (Kestrel `Limits.Http2.KeepAlivePingTimeout`). Must be between `1` and `3600`. |
|
||||
|
||||
The protocol option is exposed for diagnostics and explicit deployment
|
||||
Client keepalive pings need no server setting. Kestrel has no minimum client-ping interval (unlike grpc-core and grpc-go servers, it never answers frequent pings with `GOAWAY`/`ENHANCE_YOUR_CALM`), it answers pings with or without an active call, and a received ping resets the connection's idle keep-alive timeout. The official clients ping every 30 s with a 10 s timeout, also while no call is active, which keeps an idle connection open and detects a dead gateway from the client side.
|
||||
|
||||
The worker protocol version option is exposed for diagnostics and explicit deployment
|
||||
configuration, not for compatibility negotiation. A mismatch fails validation
|
||||
at startup.
|
||||
|
||||
|
||||
@@ -646,6 +646,18 @@ its lease expires. One session means one worker process backs every dashboard
|
||||
circuit; all access is serialised so the worker sees one in-flight command at a
|
||||
time. Tag reads go through `GatewaySession.SubscribeBulkAsync` / `ReadBulkAsync`.
|
||||
|
||||
When a read fails for any reason other than cancellation, the service closes that
|
||||
session before dropping it, and the next read opens a new one. A command timeout
|
||||
or a non-Ok bulk reply leaves the session `Ready` with a live worker and its
|
||||
advised tags; dropping only the reference left it in the registry until its lease
|
||||
expired, and a Browse page that kept failing opened a new session every poll
|
||||
until `MaxSessions` refused real clients. A Register failure on a freshly opened
|
||||
session closes it the same way. The subscribe-and-track step and the eviction
|
||||
unadvise run on `CancellationToken.None` (bounded by the session's command
|
||||
timeout) and observe the caller's token only afterwards, so a page that cancels
|
||||
its read mid-subscribe cannot leave tags advised on the worker that the advise
|
||||
set does not track.
|
||||
|
||||
The advise set that backs those reads is capped at 256 tags (one browse page plus
|
||||
headroom) and evicted least-recently-read-first. Without the cap every tag any
|
||||
viewer ever inspected stayed advised on the single dashboard worker until the
|
||||
|
||||
@@ -647,6 +647,21 @@ Pending command handling:
|
||||
Timeouts should not assume the COM call stopped. A timed-out command may still
|
||||
finish inside the worker.
|
||||
|
||||
The command timeout is one deadline for the whole call, the outbound enqueue
|
||||
included. The outbound channel is bounded, and a write loop parked in a pipe
|
||||
write the worker is not draining leaves it full; an enqueue bound only to the
|
||||
caller's token then waited indefinitely for a caller with no deadline. The
|
||||
common case (room in the channel) is a non-allocating `TryWrite`; only a full
|
||||
channel waits, under the deadline, and the reply wait gets what is left of it.
|
||||
An enqueue that runs out of time fails the command as `CommandTimeout` with no
|
||||
`WorkerCancel`, because the worker never saw it.
|
||||
|
||||
When the deadline fires, the timeout arm owns the outcome only if it removes the
|
||||
pending entry. If the read loop removed it first (the reply landed right at the
|
||||
deadline), the caller gets that reply, which is what the metrics already counted,
|
||||
instead of a `CommandTimeout` that would make it retry a write the worker
|
||||
performed.
|
||||
|
||||
On timeout **and on caller cancellation** the client also forwards a
|
||||
`WorkerCancel` carrying the abandoned correlation id, best-effort: the gateway
|
||||
has stopped waiting, but the worker has not stopped working, and the worker owns
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ The scalar fields mirror the counters and gauges. The three dictionaries provide
|
||||
|
||||
- `CommandFailuresByMethod` keys by gRPC method name.
|
||||
- `EventsByFamily` keys by event family (the `Family` enum on a worker event).
|
||||
- `EventsBySession` keys by `sessionId`; entries are removed via `RemoveSessionEvents` when a session closes so the map does not grow without bound.
|
||||
- `EventsBySession` keys by `sessionId`; entries are removed via `RemoveSessionEvents` when a session closes so the map does not grow without bound. The removal runs after the session (and with it the worker client, whose dispose waits for its read loop) is disposed: on the kill path the read loop is cancelled but not awaited, and a frame it had already read would otherwise re-create the entry after the removal.
|
||||
|
||||
`EventsReceived` is read with `Interlocked.Read(ref _eventsReceived)` because `EventReceived` increments it via `Interlocked.Increment` outside the lock to keep the event-ingestion path non-blocking. `CommandsStarted`, `CommandsSucceeded`, `CommandsFailed`, and `CommandFailuresByMethod` are read the same way: the command counters run two-to-three times per gRPC call, so they are recorded with `Interlocked` and a `ConcurrentDictionary` rather than under `_syncRoot` (PERF-02). The two queue depths are pulled from their registered sources before the lock is taken, since those delegates reach into subscriber channels and worker clients.
|
||||
|
||||
|
||||
@@ -127,6 +127,20 @@ Startup sequence:
|
||||
If validation fails before MXAccess creation, exit quickly with a non-zero exit
|
||||
code. If MXAccess creation fails, send `WorkerFault` when possible and exit.
|
||||
|
||||
Steps 5–10 run under one deadline, `WorkerPipeSessionOptions.StartupHandshakeTimeout`,
|
||||
which the launcher conveys as `MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS` from
|
||||
`MxGateway:Worker:StartupTimeoutSeconds` (default 120 s when absent). The worker
|
||||
notices gateway death only through a pipe read returning end-of-stream or a
|
||||
failed write, and the handshake has two windows with neither: a peer that
|
||||
connects and never sends `GatewayHello` (net48 pipe reads ignore the
|
||||
cancellation token), and MXAccess initialization, during which no read is
|
||||
outstanding. A COM activation that hangs after the gateway died would otherwise
|
||||
keep the x86 worker alive indefinitely. At the deadline the handshake throws
|
||||
`TimeoutException` and the worker exits with `PipeConnectionFailed`; the stuck
|
||||
step is abandoned, which is safe because the STA is a background thread. The
|
||||
gateway applies the same budget to the whole launch and starts its clock first,
|
||||
so a live gateway always gives up and kills the worker before this deadline.
|
||||
|
||||
The bootstrap layer returns structured exit codes before it creates pipes,
|
||||
starts the STA, or touches MXAccess:
|
||||
|
||||
@@ -1165,6 +1179,22 @@ are rejected and queued commands that have not started receive
|
||||
`ProtocolStatusCode.WorkerUnavailable`. The command already executing on the
|
||||
STA is allowed to finish until the shutdown grace period expires.
|
||||
|
||||
The grace period covers the whole method, including the two alarm-side steps
|
||||
that run before the data cleanup: joining the alarm poll loop and disposing the
|
||||
alarm handler on the STA. Both wait on the STA, and neither can be cancelled
|
||||
once its work item has started, so with the STA stuck in a COM call they used
|
||||
to wait forever, the timeout below was never reached, and no shutdown-timeout
|
||||
fault or `WorkerShutdownAck` was sent. Each step now gets what is left of the
|
||||
grace, and running out raises the same `TimeoutException` as a slow data
|
||||
cleanup.
|
||||
|
||||
The STA watchdog stands down once the session is `ShuttingDown` or `Stopped`.
|
||||
The data cleanup runs as one STA work item, which leaves `LastStaActivityUtc`
|
||||
frozen with no command correlation id on the heartbeat. With a grace longer than
|
||||
`HeartbeatGrace`, the watchdog would otherwise overwrite `ShuttingDown` with
|
||||
`Faulted` and report `StaHung` for a session that is closing cleanly. The
|
||||
shutdown's own timeout bounds it instead.
|
||||
|
||||
After command dispatch is closed, cleanup runs on the STA in MXAccess handle
|
||||
order:
|
||||
|
||||
|
||||
+8
-6
@@ -109,7 +109,7 @@ The named pipe is created with `maxNumberOfServerInstances: 1` so a second worke
|
||||
|
||||
### SessionShutdownHostedService
|
||||
|
||||
`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception.
|
||||
`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. The drain itself has normally already run by then: it starts at `ApplicationStopping` (see [Shutdown Coordination](#shutdown-coordination)), and `ShutdownAsync` awaits that same drain. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception.
|
||||
|
||||
### SessionOpenRequest
|
||||
|
||||
@@ -196,7 +196,7 @@ catch (Exception exception)
|
||||
}
|
||||
```
|
||||
|
||||
`RollBackOpenAsync` faults the session and, when it had been registered, routes it through `RemoveSessionAsync` — the single removal path every teardown uses, which deregisters, drops the session's per-session event metrics, releases the slot and disposes, in that order. The order matters because releasing the semaphore before disposal would let the next open race the worker process tear-down on the same machine. A session that was never registered (id collision) releases the slot and disposes directly. The open-session gauge is not touched by the rollback: `SessionOpened` is recorded inside the attach gate described next, after which nothing in the open sequence can fail.
|
||||
`RollBackOpenAsync` faults the session and, when it had been registered, routes it through `RemoveSessionAsync` — the single removal path every teardown uses, which deregisters, releases the slot, disposes, and then drops the session's per-session event metrics (after the dispose, so a worker read loop still finishing a frame cannot re-create the entry). The order matters because releasing the semaphore before disposal would let the next open race the worker process tear-down on the same machine. A session that was never registered (id collision) releases the slot and disposes directly. The open-session gauge is not touched by the rollback: `SessionOpened` is recorded inside the attach gate described next, after which nothing in the open sequence can fail.
|
||||
|
||||
#### Close or kill during worker startup
|
||||
|
||||
@@ -230,7 +230,7 @@ The repair transitions the monitor's reconcile broadcasts on the alarm feed (Rai
|
||||
|
||||
The same one-distributor-per-session rule is enforced at the other end of the lifecycle. Session disposal disposes the distributor and latches the fact, so an attach that passed its readiness gate and then lost the CPU until the session was torn down throws `SessionNotReady` rather than constructing a replacement distributor. A replacement can never be pumped — the pump-start flag is a one-way latch — so its subscriber would block on an empty channel that is never completed until the client's own deadline expired, with no error, log or metric to explain it. Every attach entry point (`AttachEventSubscriber`, `AttachEventSubscriberWithReplay`, `AttachInternalEventSubscriber`) fails this way, and each rolls back the subscriber-count slot it took, so a caller that loses the race to teardown sees the same failure it would have seen a moment later from the readiness gate.
|
||||
|
||||
Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity` is the only path that moves the lease). `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30).
|
||||
Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity`), and so does the detach of the last external event subscriber: streaming is client activity, and the lease does not age while a subscriber is attached (`IsLeaseExpired` is held false), but its deadline is only moved on unary calls. Without the renewal at detach, a client that streamed for longer than `DefaultLeaseSeconds` with no unary call would drop its stream with a lease already in the past, and the next sweep would close it as `lease-expired` (which takes precedence) before its detach-grace window. `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30).
|
||||
|
||||
#### Lazy dashboard mirror
|
||||
|
||||
@@ -258,7 +258,7 @@ The asymmetry with `CloseExpiredLeasesAsync` — whose `ParallelOptions` *is* to
|
||||
|
||||
`MxGateway:Sessions:DetachGraceSeconds` (default 30) is a bounded retention window kept after a session's *last external (gRPC) event-stream subscriber* drops, so a client can reconnect to the same session instead of having it torn down on the first stream disconnect. While the window is open the session stays `Ready` and fully usable — worker commands continue to work and a reconnecting subscriber re-attaches normally. Because retention is keyed on the *external* subscriber count (`_activeEventSubscriberCount`), and the gateway-owned internal dashboard mirror registers directly on the distributor with `isInternal: true` and is therefore *not* counted, a session whose only remaining subscriber is the dashboard mirror still enters detach-grace.
|
||||
|
||||
Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires.
|
||||
Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires, counted from the detach.
|
||||
|
||||
`DetachGraceSeconds` controls retention and expiry only; the reconnect/replay path that re-attaches a dropped client to a retained session is described in [Reconnect and replay](#reconnect-and-replay).
|
||||
|
||||
@@ -354,7 +354,9 @@ Only if both the graceful shutdown and the kill fall-back fail are the original
|
||||
|
||||
## Shutdown Coordination
|
||||
|
||||
`SessionShutdownHostedService.StopAsync` calls `SessionManager.ShutdownAsync`, which closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain:
|
||||
The drain starts at the host's `IHostApplicationLifetime.ApplicationStopping` signal, not at `SessionShutdownHostedService.StopAsync`. `WebApplication` registers Kestrel's hosted service last, so it stops first, and Kestrel's stop waits for in-flight requests. An open `StreamEvents` call is an in-flight request that ends only when its session closes. When the drain ran from `StopAsync`, every stop with an active stream waited out the whole host shutdown timeout (30 s by default); Kestrel then aborted the streams, and the drain ran on an already-cancelled token, so every worker fell to the kill fallback with no MXAccess cleanup. Starting at `ApplicationStopping`, the drain closes the sessions while Kestrel is still draining: each close completes the subscriber channels, the streams end with `OK`, and Kestrel's drain finishes at once. The manager starts the drain exactly once (`BeginShutdown`), and `ShutdownAsync` — called by `SessionShutdownHostedService.StopAsync`, or directly by a host without a lifetime — awaits that same task. The stop token passed to `ShutdownAsync` cancels the graceful closes still in flight, which turns them into the kill fallback; it never abandons the drain.
|
||||
|
||||
The drain closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain:
|
||||
|
||||
```csharp
|
||||
MarkStopping();
|
||||
@@ -422,7 +424,7 @@ public static IServiceCollection AddGatewaySessions(this IServiceCollection serv
|
||||
}
|
||||
```
|
||||
|
||||
The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore drains sessions during host stop.
|
||||
The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore awaits the session drain during host stop. Constructing `SessionManager` is also what subscribes the drain to `ApplicationStopping`.
|
||||
|
||||
## Related Documentation
|
||||
|
||||
|
||||
@@ -54,9 +54,15 @@ path exists, has a `.exe` extension, contains a valid Windows Portable
|
||||
Executable header, and matches the configured `RequiredArchitecture`.
|
||||
|
||||
After the process starts, `IWorkerStartupProbe` waits for startup readiness.
|
||||
The default probe only verifies that the worker did not exit immediately. The
|
||||
worker client replaces this probe when pipe connection, hello, and
|
||||
`WorkerReady` handling are implemented.
|
||||
The default probe only verifies that the worker did not exit immediately, which
|
||||
it checks once, microseconds after the process is created. A worker that dies
|
||||
after that and before it connects is caught by the session factory instead:
|
||||
`SessionWorkerClientFactory` races the pipe connect against the process exit,
|
||||
so an early exit fails the open at once with `StartupFailed` and the worker's
|
||||
exit code rather than holding the open (and its session slot) for the whole
|
||||
startup timeout and reporting a timeout. Once the pipe is connected, a worker
|
||||
exit surfaces as pipe end-of-stream in the handshake reads. The worker's stderr
|
||||
is not redirected, so the failure carries the exit code only.
|
||||
|
||||
The startup probe runs once, bounded by `WorkerOptions.StartupTimeoutSeconds`;
|
||||
it is not retried. The default probe only checks that the process is still
|
||||
@@ -71,7 +77,11 @@ retry loop.
|
||||
If startup fails or exceeds `WorkerOptions.StartupTimeoutSeconds`, the launcher
|
||||
kills the worker process tree, disposes the process handle, disposes the
|
||||
optional pipe reservation, records a worker kill metric, and reports a
|
||||
`WorkerProcessLaunchException`.
|
||||
`WorkerProcessLaunchException`. A `Kill` that throws during this cleanup (the
|
||||
process is mid-termination, access is denied, a descendant could not be
|
||||
terminated) is logged and does not replace the launch error; the process handle
|
||||
and the pipe are disposed regardless. The session factory's own cleanup follows
|
||||
the same rule.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
Reference in New Issue
Block a user