///|
/// Platform-neutral WebSocket peer contract shared across Native (`core/async/websocket`),
/// Cloudflare Workers (`WebSocketPair`), Bun (`ServerWebSocket`), and Node.js (RFC 6455).
pub(open) trait WsPeer {
  async fn recv(Self) -> @http.WsMessage? raise @http.WsError
  async fn send(Self, msg : @http.WsMessage) -> Unit raise @http.WsError
  async fn close(Self, code? : @http.WsCloseCode, reason? : String) -> Unit
}

///|
/// Adapter-invoked upgrade callback receiving the established `&WsPeer`.
pub type WsUpgradeCallback = async (&WsPeer) -> Unit

///|
/// Per-request upgrade handoff slot populated by `App::ws` after all pipeline guards succeed.
pub struct WsUpgradeSlot {
  priv mut callback : WsUpgradeCallback?
}

///|
pub fn WsUpgradeSlot::WsUpgradeSlot() -> WsUpgradeSlot {
  { callback: None, }
}

///|
pub fn WsUpgradeSlot::set(self : WsUpgradeSlot, cb : WsUpgradeCallback) -> Unit {
  self.callback = Some(cb)
}

///|
pub fn WsUpgradeSlot::take(self : WsUpgradeSlot) -> WsUpgradeCallback? {
  let out = self.callback
  self.callback = None
  out
}

///|
pub fn WsUpgradeSlot::is_set(self : WsUpgradeSlot) -> Bool {
  self.callback is Some(_)
}

///|
/// Context binding key used by HTTP adapters to pass a per-request `WsUpgradeSlot` into `App::fetch`.
pub let ws_upgrade_slot_key : ContextKey[WsUpgradeSlot] = ContextKey::new(
  "ciallo.ws.upgrade_slot",
  missing_status=501,
)