packages feed

pykinos-core-0.1.1.0: src/Pykinos/Net/MsgAssoc.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}

-- | Module: Pykinos.Net.MsgAssoc
-- Description: Multi-stream framing and zero-HoL-blocking message association over SackWindow
--
-- Implements SCTP-like multi-stream delivery over an underlying 'SackWindow'.
-- Distinguishes 'StreamOrdered', 'StreamUnordered', and 'StreamPartialTTL' streams,
-- ensuring that un-sequenced datagrams bypass stalled ordered transmission queues
-- with zero head-of-line (HoL) blocking.
module Pykinos.Net.MsgAssoc
  ( StreamPolicy (..)
  , MsgChunk (..)
  , MsgAssoc (..)
  , initMsgAssoc
  , receiveChunk
  , extractDeliverable
  ) where

import qualified Data.ByteString as BS
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Word (Word16, Word32)
import Pykinos.Net.SackWindow
  ( SackWindow (..)
  , TsnOutcome (..)
  , initSackWindow
  , recordTsn
  )

-- | Per-stream delivery discipline.
data StreamPolicy
  = StreamOrdered
    -- ^ Strictly ordered stream delivery; gaps buffer until the missing SSN arrives.
  | StreamUnordered
    -- ^ Immediate zero-HoL delivery; delivered as soon as the chunk arrives.
  | StreamPartialTTL !Int
    -- ^ Partially reliable stream with hop/timeout drop semantics.
  deriving stock (Eq, Show)

-- | A discrete transmission chunk arriving on the wire.
data MsgChunk = MsgChunk
  { mcTsn      :: !Word32
    -- ^ Transmission Sequence Number (association-wide serial space).
  , mcStreamId :: !Word16
    -- ^ Stream identifier.
  , mcSsn      :: !Word16
    -- ^ Stream Sequence Number (per-stream ordered index).
  , mcPolicy   :: !StreamPolicy
    -- ^ Stream delivery policy.
  , mcPayload  :: !BS.ByteString
    -- ^ Message payload bytes.
  } deriving stock (Eq, Show)

-- | State of an active multi-stream reception association.
data MsgAssoc = MsgAssoc
  { maSackWindow :: !SackWindow
    -- ^ Underlying cumulative TSN and SACK bitmask.
  , maNextSsn    :: !(Map Word16 Word16)
    -- ^ Next expected Stream Sequence Number for ordered streams.
  , maBuffer     :: !(Map Word16 (Map Word16 BS.ByteString))
    -- ^ Buffered out-of-order chunks per stream: streamId -> (ssn -> payload).
  , maDelivered  :: ![BS.ByteString]
    -- ^ FIFO queue of payloads ready for consumption.
  } deriving stock (Eq, Show)

-- | Initializes a new 'MsgAssoc' starting at @initialTsn@.
initMsgAssoc :: Word32 -> MsgAssoc
initMsgAssoc initialTsn = MsgAssoc
  { maSackWindow = initSackWindow initialTsn
  , maNextSsn    = Map.empty
  , maBuffer     = Map.empty
  , maDelivered  = []
  }

-- | Processes an arriving chunk, returning the TSN outcome, the updated association,
-- and any payloads that became deliverable as a result of this chunk.
receiveChunk :: MsgChunk -> MsgAssoc -> (TsnOutcome, MsgAssoc, [BS.ByteString])
receiveChunk chunk assoc =
  let (outcome, sw') = recordTsn (mcTsn chunk) (maSackWindow assoc)
  in case outcome of
       TsnDuplicate -> (TsnDuplicate, assoc, [])
       TsnOutOfWindow -> (TsnOutOfWindow, assoc, [])
       TsnAcceptedNew ->
         let assoc1 = assoc { maSackWindow = sw' }
         in case mcPolicy chunk of
              -- Zero-HoL fast path: bypass stream ordering buffers entirely!
              StreamUnordered ->
                let delivered = [mcPayload chunk]
                    assoc2 = assoc1 { maDelivered = maDelivered assoc1 ++ delivered }
                in (TsnAcceptedNew, assoc2, delivered)

              -- Ordered delivery: check SSN sequence
              StreamOrdered ->
                let sid = mcStreamId chunk
                    ssn = mcSsn chunk
                    expected = Map.findWithDefault 0 sid (maNextSsn assoc1)
                in if ssn == expected
                     then
                       -- Immediate in-order delivery; drain any contiguous buffered chunks
                       let stBuf = Map.findWithDefault Map.empty sid (maBuffer assoc1)
                           (nextSsn', newlyDelivered, stBuf') = drainContiguous (ssn + 1) [mcPayload chunk] stBuf
                           assoc2 = assoc1
                             { maNextSsn = Map.insert sid nextSsn' (maNextSsn assoc1)
                             , maBuffer  = Map.insert sid stBuf' (maBuffer assoc1)
                             , maDelivered = maDelivered assoc1 ++ newlyDelivered
                             }
                       in (TsnAcceptedNew, assoc2, newlyDelivered)
                     else
                       -- Out of order: buffer chunk for future draining
                       let stBuf = Map.findWithDefault Map.empty sid (maBuffer assoc1)
                           stBuf' = Map.insert ssn (mcPayload chunk) stBuf
                           assoc2 = assoc1 { maBuffer = Map.insert sid stBuf' (maBuffer assoc1) }
                       in (TsnAcceptedNew, assoc2, [])

              -- Partial TTL: deliver immediately if fresh
              StreamPartialTTL ttl ->
                if ttl > 0
                  then
                    let delivered = [mcPayload chunk]
                        assoc2 = assoc1 { maDelivered = maDelivered assoc1 ++ delivered }
                    in (TsnAcceptedNew, assoc2, delivered)
                  else (TsnAcceptedNew, assoc1, [])

-- | Drains contiguous chunks starting from @curSsn@.
drainContiguous :: Word16 -> [BS.ByteString] -> Map Word16 BS.ByteString -> (Word16, [BS.ByteString], Map Word16 BS.ByteString)
drainContiguous !curSsn acc buf =
  case Map.lookup curSsn buf of
    Nothing -> (curSsn, reverse acc, buf)
    Just p  -> drainContiguous (curSsn + 1) (p : acc) (Map.delete curSsn buf)

-- | Extracts all pending deliverable payloads, clearing the delivery buffer.
extractDeliverable :: MsgAssoc -> ([BS.ByteString], MsgAssoc)
extractDeliverable assoc = (maDelivered assoc, assoc { maDelivered = [] })