import Base import ./transaction.bend as T import ./bundle_install.bend as Install import ./world.bend as W import ./bundle_batch.bend as Batch # Explicit app-owned reversible receipts live outside the World journal. # Their generated position preserves ordering with ordinary resource/component # inverses. Recovered affine owners are returned to the Local adapter, never # placed into a resource that a subsequent inverse could overwrite. type Receipt is Type: Receipt{position:Nat,inverse:World -> Install.Restore} type Pending is Type:Pending{owner:Q,error:W.WorldError} type Returned is Type: Returned{world:World,owners:List

,pending:List>} def stepped(~World:Type,count:Nat,world:World,undo:List<(World -> World)>) -> World & List<(World -> World)>: match count undo: case 0n _:(world,undo) case 1n+rest Nil{}:(world,[]) case 1n+rest Con{inverse,tail}:stepped(~World,rest,inverse(world),tail) def restored(~World:Type,~P:Type,~Q:Type,next:World -> List

-> List> -> Returned,owners:List

,pending:List>,result:Install.Restore) -> Returned: match result: case Install.Restored{world,owner}:next(world,owner <> owners,pending) case Install.Pending{world,owner,error}:next(world,owners,Pending{owner,error} <> pending) def unwound(~World:Type,~P:Type,~Q:Type,inverse:World -> Install.Restore,next:List<(World -> World)> -> World -> List

-> List> -> Returned,owners:List

,pending:List>,result:World & List<(World -> World)>) -> Returned: match result: case (world,undo):restored(~World,~P,~Q,(world => owners => pending => next(undo,world,owners,pending)),owners,pending,inverse(world)) def rollback(~World:Type,~P:Type,~Q:Type,receipts:List>,undo:List<(World -> World)>,count:Nat,world:World,owners:List

,pending:List>) -> Returned: match receipts: case []:Returned{T.rollback(~World,undo,world),List.reverse(&1,P,owners),List.reverse(&1,Pending,pending)} case Receipt{+position,inverse} <> rest:unwound(~World,~P,~Q,inverse,(undo => world => owners => pending => rollback(~World,~P,~Q,rest,undo,position,world,owners,pending)),owners,pending,stepped(~World,Nat.sub(count,position),world,undo)) def counted(~World:Type,~P:Type,~Q:Type,receipts:List>,world:World,result:List<(World -> World)> & Nat) -> Returned: match result: case (undo,count):rollback(~World,~P,~Q,receipts,undo,count,world,[],[]) def inverse_counted(~World:Type,inverse:World -> World,result:List<(World -> World)> & Nat) -> List<(World -> World)> & Nat: match result: case (undo,count):(inverse <> undo,1n+count) def count_inverses(~World:Type,undo:List<(World -> World)>) -> List<(World -> World)> & Nat: match undo: case []:([],0n) case inverse <> rest:inverse_counted(~World,inverse,count_inverses(~World,rest)) def abort(~World:Type,~E:Data,~P:Type,~Q:Type,receipts:List>,tx:T.Tx) -> Returned: match tx: case T.Tx{world,undo,_,_,_}:counted(~World,~P,~Q,receipts,world,count_inverses(~World,undo))