Last active
September 15, 2023 20:10
-
-
Save pchiusano/7415a56c0719c8a76cde8cba9fc61dde to your computer and use it in GitHub Desktop.
Batching transactions in durable storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unique ability Batch where | |
increment : Nat -> () | |
-- Like `State.transact`, but pauses the computation every `batchSize` calls to | |
-- `Batch.increment` and commits the work so far in one transaction, then resumes | |
-- the rest of the computation. | |
State.transact.batched : Nat -> Database -> '{Batch, Transaction, Exception} a ->{State, Exception} a | |
State.transact.batched batchSize db b = | |
go : Nat -> Request {Batch} a -> Either ('{Batch,Transaction,Exception} a) a | |
go acc = cases | |
{ a } -> Right a | |
{ Batch.increment by -> k } -> | |
acc' = acc + by | |
if acc' >= batchSize then Left k | |
else handle !k with go acc' | |
loop : '{Batch, Transaction, Exception} a ->{State, Exception} a | |
loop b = match transact db '(handle !b with go 0) with | |
Right a -> a | |
Left b -> loop b | |
loop b | |
ex = transact.batched 100 db do | |
c = Cell.named "hi" 0 | |
inc i = | |
Batch.increment 1 | |
Cell.write.tx c (Cell.read.tx c + 1) | |
List.range 0 1000 |> List.foreach inc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment