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

{- | The least a full JSON listing read pays for each entry it retains. Per-byte charges are
calibrated on realistic listings, so a document of many tiny entries would retain more than its
bytes pay for. Such a read raises its workspace charge to the floor after each piece it walks, and
keeps the floor once it completes.
-}
module Ecluse.Core.Registry.Metadata.EntryFloor (
    entryFloorBytes,
    releaseFloorBytes,
    RetainedEntries (..),
    noRetainedEntries,
    entryFloorCharge,
    countingEntries,
    readFlooredWalk,
) where

import Control.Monad.ST (RealWorld, ST, stToIO)
import Data.ByteString qualified as BS
import Data.JsonStream.Lexer (Cursor)
import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)

import Ecluse.Core.Registry.Json.Walk (readJsonWalkST)
import Ecluse.Core.Registry.JsonStream (Steps, StreamResult, maxChunkBytes)
import Ecluse.Core.Security (BodyLimit, LimitError)
import Ecluse.Core.Server.Admission.Budget (scaleCharge)

-- | The bytes each retained entry other than a version or file costs at least. A residency case measures dense listings to set it: see @docs/testing.md@.
entryFloorBytes :: Int
entryFloorBytes :: Int
entryFloorBytes = Int
512

-- | The bytes each retained npm version or PyPI file costs at least, which the residency tier measures on minimal valid bodies.
releaseFloorBytes :: Int
releaseFloorBytes :: Int
releaseFloorBytes = Int
1152

-- | The entries a full read retains, by the floor each pays.
data RetainedEntries = RetainedEntries
    { RetainedEntries -> Int
retainedReleases :: Int
    -- ^ npm versions and PyPI files, dropped ones included, which pay 'releaseFloorBytes'.
    , RetainedEntries -> Int
retainedOthers :: Int
    -- ^ Every other retained entry, which pays 'entryFloorBytes'.
    }
    deriving stock (RetainedEntries -> RetainedEntries -> Bool
(RetainedEntries -> RetainedEntries -> Bool)
-> (RetainedEntries -> RetainedEntries -> Bool)
-> Eq RetainedEntries
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RetainedEntries -> RetainedEntries -> Bool
== :: RetainedEntries -> RetainedEntries -> Bool
$c/= :: RetainedEntries -> RetainedEntries -> Bool
/= :: RetainedEntries -> RetainedEntries -> Bool
Eq, Int -> RetainedEntries -> ShowS
[RetainedEntries] -> ShowS
RetainedEntries -> String
(Int -> RetainedEntries -> ShowS)
-> (RetainedEntries -> String)
-> ([RetainedEntries] -> ShowS)
-> Show RetainedEntries
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RetainedEntries -> ShowS
showsPrec :: Int -> RetainedEntries -> ShowS
$cshow :: RetainedEntries -> String
show :: RetainedEntries -> String
$cshowList :: [RetainedEntries] -> ShowS
showList :: [RetainedEntries] -> ShowS
Show)

-- | No retained entries: a read with no floor, or a document no read produced.
noRetainedEntries :: RetainedEntries
noRetainedEntries :: RetainedEntries
noRetainedEntries = Int -> Int -> RetainedEntries
RetainedEntries Int
0 Int
0

-- | The floors the retained entries owe, saturating at the largest charge. Each step of a walk computes it, so it stays in 'Int'.
entryFloorCharge :: RetainedEntries -> Int
entryFloorCharge :: RetainedEntries -> Int
entryFloorCharge RetainedEntries
entries
    | Int
releases Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
bound Bool -> Bool -> Bool
|| Int
others Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
bound = Int
forall a. Bounded a => a
maxBound
    | Bool
otherwise = Int
releaseFloorBytes Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
releases Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
entryFloorBytes Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
others
  where
    releases :: Int
releases = RetainedEntries -> Int
retainedReleases RetainedEntries
entries
    others :: Int
others = RetainedEntries -> Int
retainedOthers RetainedEntries
entries
    -- Up to this count each product stays within half the largest 'Int'.
    bound :: Int
bound = Int
forall a. Bounded a => a
maxBound Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` (Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
releaseFloorBytes)

-- | Continue a step after publishing the floors its accepted state's retained entries owe.
countingEntries :: PrimVar st Int -> (s -> RetainedEntries) -> (Either LimitError s -> ST st r) -> Either LimitError s -> ST st r
countingEntries :: forall st s r.
PrimVar st Int
-> (s -> RetainedEntries)
-> (Either LimitError s -> ST st r)
-> Either LimitError s
-> ST st r
countingEntries PrimVar st Int
owed s -> RetainedEntries
entries Either LimitError s -> ST st r
next Either LimitError s
taken = do
    (s -> ST st ()) -> Either LimitError s -> ST st ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (PrimVar (PrimState (ST st)) Int -> Int -> ST st ()
forall (m :: * -> *) a.
(PrimMonad m, Prim a) =>
PrimVar (PrimState m) a -> a -> m ()
writePrimVar PrimVar st Int
PrimVar (PrimState (ST st)) Int
owed (Int -> ST st ()) -> (s -> Int) -> s -> ST st ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RetainedEntries -> Int
entryFloorCharge (RetainedEntries -> Int) -> (s -> RetainedEntries) -> s -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. s -> RetainedEntries
entries) Either LimitError s
taken
    Either LimitError s -> ST st r
next Either LimitError s
taken
{-# INLINE countingEntries #-}

{- | Walk a body, raising @pay@'s absolute workspace before each piece to the floors the walk has
published, less the per-byte charge at @permille@ the pieces read so far already paid.
-}
readFlooredWalk ::
    (Int -> IO ()) ->
    Int ->
    BodyLimit ->
    (PrimVar RealWorld Int -> Cursor -> ST RealWorld (Steps (ST RealWorld) s)) ->
    IO ByteString ->
    IO (Either LimitError (StreamResult s))
readFlooredWalk :: forall s.
(Int -> IO ())
-> Int
-> BodyLimit
-> (PrimVar RealWorld Int
    -> Cursor -> ST RealWorld (Steps (ST RealWorld) s))
-> IO ByteString
-> IO (Either LimitError (StreamResult s))
readFlooredWalk Int -> IO ()
pay Int
permille BodyLimit
bound PrimVar RealWorld Int
-> Cursor -> ST RealWorld (Steps (ST RealWorld) s)
walk IO ByteString
readChunk = do
    owed <- Int -> IO (PrimVar (PrimState IO) Int)
forall (m :: * -> *) a.
(PrimMonad m, Prim a) =>
a -> m (PrimVar (PrimState m) a)
newPrimVar Int
0
    seen <- newPrimVar 0
    held <- newIORef BS.empty
    let piece = do
            floors <- PrimVar (PrimState IO) Int -> IO Int
forall (m :: * -> *) a.
(PrimMonad m, Prim a) =>
PrimVar (PrimState m) a -> m a
readPrimVar PrimVar RealWorld Int
PrimVar (PrimState IO) Int
owed
            bytes <- readPrimVar seen
            let shortfall = Int
floors Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int -> Int -> Int
scaleCharge Int
permille Int
bytes
            when (shortfall > 0) (pay shortfall)
            pending <- readIORef held
            chunk <- if BS.null pending then readChunk else pure pending
            let (next, rest) = BS.splitAt maxChunkBytes chunk
            writeIORef held rest
            writePrimVar seen (bytes + BS.length next)
            pure next
    readJsonWalkST stToIO bound (walk owed) piece
-- Specialise in the reading module, which turns full laziness off. Compiled here, npm and PyPI full reads allocated 30% to 60% more.
{-# INLINE readFlooredWalk #-}