-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | The window "Ecluse.Core.Registry.Progress" keeps for each transfer, and its pure transitions.
Importing this module opts out of the public surface's stability promises. It exists so a spec can
hold the transitions to a reference.
-}
module Ecluse.Core.Registry.Progress.Internal (
    Window (..),
    freshWindow,
    beginAt,
    endAt,
    waitedBy,
) where

import Ecluse.Core.Security (ProgressFloor, floorMinBytes)

{- | The nanoseconds waited and the bytes moved in the current window, each constructor's last two
fields. 'Waiting' first holds the monotonic time its open wait on the upstream began.
-}
data Window
    = Waiting {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 {-# UNPACK #-} !Int
    | Idle {-# UNPACK #-} !Word64 {-# UNPACK #-} !Int

-- | No wait open, nothing waited, and nothing moved: a transfer's start, and the window after the floor's bytes.
freshWindow :: Window
freshWindow :: Window
freshWindow = Word64 -> Int -> Window
Idle Word64
0 Int
0

-- | Open a wait at a monotonic time in nanoseconds.
beginAt :: Word64 -> Window -> Window
beginAt :: Word64 -> Window -> Window
beginAt Word64
now = \case
    Waiting Word64
_ Word64
waited Int
moved -> Word64 -> Word64 -> Int -> Window
Waiting Word64
now Word64
waited Int
moved
    Idle Word64
waited Int
moved -> Word64 -> Word64 -> Int -> Window
Waiting Word64
now Word64
waited Int
moved

-- | Close the open wait with the bytes it moved. Reaching the floor's bytes starts a new window.
endAt :: ProgressFloor -> Word64 -> Int -> Window -> Window
endAt :: ProgressFloor -> Word64 -> Int -> Window -> Window
endAt ProgressFloor
progress Word64
now Int
bytes Window
current
    | Int
total Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= ProgressFloor -> Int
floorMinBytes ProgressFloor
progress = Window
freshWindow
    | Bool
otherwise = Word64 -> Int -> Window
Idle (Word64 -> Window -> Word64
waitedBy Word64
now Window
current) Int
total
  where
    total :: Int
total = Window -> Int
movedIn Window
current Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
bytes

{- | The nanoseconds waited by a monotonic time. The sweeper can read its clock just before the
transfer stamps a later wait, so the open wait's gap floors at zero.
-}
waitedBy :: Word64 -> Window -> Word64
waitedBy :: Word64 -> Window -> Word64
waitedBy Word64
now = \case
    Waiting Word64
began Word64
waited Int
_ -> Word64
waited Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ if Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Word64
began then Word64
now Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
began else Word64
0
    Idle Word64
waited Int
_ -> Word64
waited

movedIn :: Window -> Int
movedIn :: Window -> Int
movedIn = \case
    Waiting Word64
_ Word64
_ Int
moved -> Int
moved
    Idle Word64
_ Int
moved -> Int
moved