198 lines
9.4 KiB
Swift
198 lines
9.4 KiB
Swift
// RetainQueue.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
/// Type-safe wrapper around `SPSCQueue<Unmanaged<AnyObject>>` for the
|
|
/// Synthesizer / PreparedNode free-queue pattern.
|
|
///
|
|
/// Motivation
|
|
/// ==========
|
|
/// The pattern `_ = freeQueue.enqueue(Unmanaged.passRetained(x as AnyObject))`
|
|
/// appears at every RT-side enqueue site in `SynthesisEngine.applyEvent`.
|
|
/// Each site has the same three correctness invariants:
|
|
/// 1. `Unmanaged.passRetained` must run before the enqueue (RT-safe — just an
|
|
/// atomic refcount bump, no allocation).
|
|
/// 2. On enqueue success, exactly one `release()` must follow on the
|
|
/// drain side.
|
|
/// 3. On enqueue failure (queue full), no `release()` may run on the RT
|
|
/// thread (ARC deallocation is non-RT-safe). The retained ref leaks
|
|
/// until process exit; the leak is documented as graceful overflow
|
|
/// degradation, not a crash.
|
|
///
|
|
/// `RetainQueue<T>` centralises these invariants. It exposes:
|
|
/// - `enqueue(_:)` — RT-safe enqueue. Silent leak on overflow. Used by
|
|
/// `applyEvent` on the audio render thread.
|
|
/// - `enqueueBalanced(_:)` — Non-RT enqueue. On overflow, balances the
|
|
/// retain with a synchronous `release()`. Used by main-thread code
|
|
/// paths (`engine.remove(_:at:)` pre-retain) where the silent-leak
|
|
/// degradation is not appropriate.
|
|
/// - `dequeue()` — Returns `Unmanaged<T>?`. Caller invokes `release()`
|
|
/// after touching the strongly-typed underlying object. Called by
|
|
/// the background `freeWorker` drain.
|
|
///
|
|
/// RT vs non-RT enqueue
|
|
/// ====================
|
|
/// Use `enqueue(_:)` only on the audio render thread. The silent-leak
|
|
/// overflow path is the canonical RT-safe degradation under burst load —
|
|
/// `release()` is not safe to call from the RT thread (could cascade
|
|
/// through ARC into arbitrary `deinit` code, which can allocate / take
|
|
/// locks / call out to unbounded user code). Size the underlying SPSC
|
|
/// queue capacity at engine init time generously enough that overflow
|
|
/// is a misconfiguration signal, not steady-state behaviour.
|
|
///
|
|
/// Use `enqueueBalanced(_:)` from main-thread code paths where the
|
|
/// caller pre-retains a synth for handoff (e.g. `remove(_:at:)`
|
|
/// enqueues an `Unmanaged` carried inside a `ScheduledEvent`). If that
|
|
/// outer enqueue fails, the caller has already paid the retain and the
|
|
/// balanced release closes the loop. Calling `enqueueBalanced` from the
|
|
/// RT thread is a CLAUDE.md hard-rule violation.
|
|
///
|
|
/// Type safety
|
|
/// ===========
|
|
/// The generic parameter `T` is the underlying object type the caller is
|
|
/// retaining. The stored representation is `Unmanaged<AnyObject>` to
|
|
/// keep the wire type identical to the legacy `SPSCQueue<Unmanaged<AnyObject>>`
|
|
/// (so freeQueue can hold a heterogeneous mix of `Synthesizer`,
|
|
/// `PreparedNode`, `Group`, etc.). `dequeue()` returns `Unmanaged<T>` so
|
|
/// the drain side can call `release()` with the concrete type — though in
|
|
/// the freeQueue case, callers pass `AnyObject` and the type-erased
|
|
/// release is what they want.
|
|
///
|
|
/// Future direction
|
|
/// ================
|
|
/// Per the open question flagged when this queue was introduced, if multi-engine
|
|
/// processes ever start hitting queue overflow in steady state (rather
|
|
/// than as misconfiguration), candidate fixes are:
|
|
/// - Bump the per-engine queue capacity at init time.
|
|
/// - Add a second-chance overflow buffer that the main-thread drain
|
|
/// can absorb without RT thread involvement.
|
|
/// - Promote the enqueue API to return a sentinel "overflowed" state
|
|
/// instead of a bare `Bool` so callers can record metrics.
|
|
/// None ship in 196.5; the current shape preserves byte-for-byte
|
|
/// behaviour with the legacy code while typing the surface.
|
|
internal struct RetainQueue<T: AnyObject> {
|
|
|
|
/// Underlying SPSC queue. The element type stays `Unmanaged<AnyObject>`
|
|
/// to match the legacy freeQueue wire shape; the typed wrapper layers
|
|
/// `T` on top via casts at the API boundary.
|
|
private let _queue: SPSCQueue<Unmanaged<AnyObject>>
|
|
|
|
/// Construct a `RetainQueue` with `capacity` slots. The capacity is
|
|
/// forwarded directly to `SPSCQueue.init`, which preconditions on
|
|
/// power-of-two capacities.
|
|
///
|
|
/// - Parameter capacity: Number of pre-allocated slots. Must be a
|
|
/// power of two.
|
|
internal init(capacity: Int) {
|
|
self._queue = SPSCQueue<Unmanaged<AnyObject>>(capacity: capacity)
|
|
}
|
|
|
|
/// Number of pre-allocated slots in the underlying SPSC queue.
|
|
internal var capacity: Int { _queue.capacity }
|
|
|
|
/// **RT-safe** enqueue. Retains `object` (atomic refcount bump only —
|
|
/// no allocation) and posts the retained reference to the queue. On
|
|
/// overflow, the retained reference is silently dropped (leaks until
|
|
/// process exit). Use from the audio render thread only when the
|
|
/// silent-leak degradation is acceptable.
|
|
///
|
|
/// - Parameter object: The object to retain and enqueue.
|
|
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
|
/// Callers that need to know about overflow can record a counter
|
|
/// off the discarded return value.
|
|
@discardableResult
|
|
internal func enqueue(_ object: T) -> Bool {
|
|
let retained: Unmanaged<AnyObject> = Unmanaged.passRetained(object as AnyObject)
|
|
let inserted: Bool = _queue.enqueue(retained)
|
|
// RT-safety: on overflow, cannot call retained.release() — ARC
|
|
// deallocation cascades are non-RT-safe. The retain leaks.
|
|
return inserted
|
|
}
|
|
|
|
/// **Non-RT** enqueue. Retains `object` and posts the retained
|
|
/// reference; on overflow, balances the retain with a synchronous
|
|
/// `release()` so the object's refcount returns to its pre-call
|
|
/// value. Use from main-thread code paths where the silent-leak
|
|
/// degradation is not appropriate.
|
|
///
|
|
/// Calling this from the audio render thread is a CLAUDE.md hard-rule
|
|
/// violation — `release()` can run user `deinit` which may allocate
|
|
/// or block.
|
|
///
|
|
/// - Parameter object: The object to retain and enqueue.
|
|
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
|
@discardableResult
|
|
internal func enqueueBalanced(_ object: T) -> Bool {
|
|
let retained: Unmanaged<AnyObject> = Unmanaged.passRetained(object as AnyObject)
|
|
let inserted: Bool = _queue.enqueue(retained)
|
|
if !inserted {
|
|
retained.release()
|
|
}
|
|
return inserted
|
|
}
|
|
|
|
/// **RT-safe** enqueue accepting a pre-retained `Unmanaged<AnyObject>`
|
|
/// rather than a strong reference. Used by `SynthesisEngine.applyEvent`
|
|
/// to re-enqueue the pre-retained `ScheduledEvent.remove` payload and
|
|
/// the `.groupFree` orphan-group fallback.
|
|
///
|
|
/// The caller has already paid the retain; this method just moves
|
|
/// the reference into the queue. On overflow, the reference is
|
|
/// **silently dropped** — the retain count stays at +1 permanently
|
|
/// (leaks until process exit). `release()` cannot run on the RT
|
|
/// thread (cascades through arbitrary `deinit` code), so silent
|
|
/// leak is the only RT-safe degradation. Matches the legacy
|
|
/// `_ = freeQueue.enqueue(ref)` behaviour byte-for-byte.
|
|
///
|
|
/// Use ``enqueuePreretainedBalanced(_:)`` if calling from the main
|
|
/// thread (where `release()` is safe to balance the refcount).
|
|
///
|
|
/// - Parameter retainedRef: A pre-retained `Unmanaged` reference. The
|
|
/// caller transfers ownership of the +1 to the queue.
|
|
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
|
@discardableResult
|
|
internal func enqueuePreretained(_ retainedRef: Unmanaged<AnyObject>) -> Bool {
|
|
return _queue.enqueue(retainedRef)
|
|
}
|
|
|
|
/// **Non-RT** variant of ``enqueuePreretained(_:)`` that balances the
|
|
/// refcount on overflow via a synchronous `release()`. Use from
|
|
/// main-thread code paths (e.g. an `engine.remove(_:at:)` re-entry
|
|
/// path that has pre-retained the synth and needs the refcount to
|
|
/// balance if `pendingQueue` is full).
|
|
///
|
|
/// Calling from the RT thread is a CLAUDE.md hard-rule violation —
|
|
/// `release()` is non-RT-safe.
|
|
///
|
|
/// - Parameter retainedRef: A pre-retained `Unmanaged` reference.
|
|
/// - Returns: `true` on successful enqueue, `false` on overflow
|
|
/// (in which case the refcount has been balanced by `release()`).
|
|
@discardableResult
|
|
internal func enqueuePreretainedBalanced(_ retainedRef: Unmanaged<AnyObject>) -> Bool {
|
|
let inserted: Bool = _queue.enqueue(retainedRef)
|
|
if !inserted {
|
|
retainedRef.release()
|
|
}
|
|
return inserted
|
|
}
|
|
|
|
/// Dequeue one retained reference, or `nil` if the queue is empty.
|
|
/// The returned `Unmanaged<T>` carries the +1 retain count; caller
|
|
/// must invoke `release()` exactly once to balance.
|
|
///
|
|
/// Type-cast via `Unmanaged<T>.fromOpaque(toOpaque())` — the
|
|
/// underlying queue stores `Unmanaged<AnyObject>`, but the typed
|
|
/// `T` parameter lets the caller release with the correct concrete
|
|
/// type if needed. For the freeQueue case where `T = AnyObject`
|
|
/// and callers only care about `release()`, this is identical to a
|
|
/// direct dequeue.
|
|
///
|
|
/// - Returns: The next retained reference, or `nil` if empty.
|
|
internal func dequeue() -> Unmanaged<T>? {
|
|
guard let any: Unmanaged<AnyObject> = _queue.dequeue() else { return nil }
|
|
return Unmanaged<T>.fromOpaque(any.toOpaque())
|
|
}
|
|
}
|