mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
Discovered during review of #22868, ExecQueue allocated on every 0 -> 1 -> 0 transition and forced callers to allocate closures on the hot path: - go q.run(f) synthesized a heap-allocated gowrap closure capturing (q, f) on every idle-to-busy transition. - q.queue = nil on drain discarded the backing slice after every burst, reallocating on subsequent 1 -> 2 overlaps. - q.initCtxLocked() eagerly allocated a context.WithCancel on the first Add even when Wait or RunSync were never called. - ExecQueue.Add only accepts func(), forcing single-handler callers like LocalBackend.onPeerWireGuardState (called while wireguard-go holds peer locks) to allocate a closure per call. Add a generic Queue[T] backed by a single handler function (initialized with NewQueue or in-place Init) and eliminate steady-state allocations: - Store the 0 -> 1 item inline in an unexported first slot (zeroed before invoking the handler) and cache the q.run method value in runFunc so idle-to-busy launches go runFunc() with 0 allocations. - Drain the overflow slice with a head index, resetting to q.queue[:0] when empty while retaining capacities up to 16 (and compacting on sustained non-draining overlap, releasing on shutdown or after larger bursts). - Replace context.WithCancel with a lazily allocated closedCh channel created only when Wait or RunSync blocks before shutdown. Keep ExecQueue as a thin zero-value-ready wrapper around Queue[func()] rather than replacing it with a generic type. Go has no default type parameters, so parameterizing ExecQueue would break existing callers; heterogeneous queues still enqueue arbitrary closures without an Init step; and RunSync(ctx, func()) is specific to func() items. Switch LocalBackend.peerWGStateQueue to execqueue.Queue[peerWGStateEvent] so onPeerWireGuardState performs 0 heap allocations under wireguard-go's lock. Updates #22868 Change-Id: I048d0549781caa7dec9f2a44313f32d13a377d4b Signed-off-by: James Tucker <james@tailscale.com>