nim-codex/codex/sales/states/downloading.nim

96 lines
2.9 KiB
Nim
Raw Normal View History

[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
import pkg/chronicles
import pkg/questionable
import pkg/questionable/results
import ../../blocktype as bt
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
import ../../market
import ../salesagent
import ../statemachine
import ./errorhandling
import ./cancelled
import ./failed
import ./filled
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
import ./ignored
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
import ./proving
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
import ./errored
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
type
SaleDownloading* = ref object of ErrorHandlingState
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
logScope:
topics = "sales downloading"
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
method `$`*(state: SaleDownloading): string = "SaleDownloading"
method onCancelled*(state: SaleDownloading, request: StorageRequest): ?State =
return some State(SaleCancelled())
method onFailed*(state: SaleDownloading, request: StorageRequest): ?State =
return some State(SaleFailed())
method onSlotFilled*(state: SaleDownloading, requestId: RequestId,
slotIndex: UInt256): ?State =
return some State(SaleFilled())
method run*(state: SaleDownloading, machine: Machine): Future[?State] {.async.} =
let agent = SalesAgent(machine)
let data = agent.data
let context = agent.context
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
let reservations = context.reservations
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
await agent.retrieveRequest()
await agent.subscribe()
without onStore =? context.onStore:
raiseAssert "onStore callback not set"
without request =? data.request:
raiseAssert "no sale request"
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
without availability =? await reservations.find(
request.ask.slotSize,
request.ask.duration,
request.ask.pricePerSlot,
request.ask.collateral,
[marketplace] Add Reservations Module (#340) * [marketplace] reservations module - add de/serialization for Availability - add markUsed/markUnused in persisted availability - add query for unused - add reserve/release - reservation module tests - split ContractInteractions into client contracts and host contracts - remove reservations start/stop as the repo start/stop is being managed by the node - remove dedicated reservations metadata store and use the metadata store from the repo instead - Split ContractInteractions into: - ClientInteractions (with purchasing) - HostInteractions (with sales and proving) - compilation fix for nim 1.2 [repostore] fix started flag, add tests [marketplace] persist slot index For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded. * Revert repostore changes In favour of separate PR https://github.com/status-im/nim-codex/pull/374. * remove warnings * clean up * tests: stop repostore during teardown * change constructor type identifier Change Contracts constructor to accept Contracts type instead of ContractInteractions. * change constructor return type to Result instead of Option * fix and split interactions tests * clean up, fix tests * find availability by slot id * remove duplication in host/client interactions * add test for finding availability by slotId * log instead of raiseAssert when failed to mark availability as unused * move to SaleErrored state instead of raiseAssert * remove unneeded reverse It appears that order is not preserved in the repostore, so reversing does not have the intended effect here. * update open api spec for potential rest endpoint errors * move functions about available bytes to repostore * WIP: reserve and release availabilities as needed WIP: not tested yet Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use. As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well. During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes. Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur. * delete availability when all bytes released * fix tests + cleanup * remove availability from SalesContext callbacks Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart. Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed. * test clean up * - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie) - fix integration test that checks availabilities - there was a bug fixed that crashed the node due to a missing `return success` in onStore - the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced - change Availability back to non-ref object and constructor back to init - add trace logging of all state transitions in state machine - add generally useful trace logging * fixes after rebase 1. Fix onProve callbacks 2. Use Slot type instead of tuple for retrieving active slot. 3. Bump codex-contracts-eth that exposes getActivceSlot call. * swap contracts branch to not support slot collateral Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit. * modify Interactions and Deployment constructors - `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads - `Interactions` prepared simplified so there are no overloads - `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]` * Move `batchProc` declaration `batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency. * [reservations] rename `available` to `hasAvailable` * [reservations] default error message to inner error msg * add SaleIngored state When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
used = false):
info "no availability found for request, ignoring",
slotSize = request.ask.slotSize,
duration = request.ask.duration,
pricePerSlot = request.ask.pricePerSlot,
used = false
return some State(SaleIgnored())
# mark availability as used so that it is not matched to other requests
if markUsedErr =? (await reservations.markUsed(availability.id)).errorOption:
return some State(SaleErrored(error: markUsedErr))
proc onBatch(blocks: seq[bt.Block]) {.async.} =
# release batches of blocks as they are written to disk and
# update availability size
var bytes: uint = 0
for blk in blocks:
bytes += blk.data.len.uint
trace "Releasing batch of bytes written to disk", bytes
let r = await reservations.release(availability.id, bytes)
# `tryGet` will raise the exception that occurred during release, if there
# was one. The exception will be caught in the closure and sent to the
# SaleErrored state.
r.tryGet()
template markUnused(id: AvailabilityId) =
if markUnusedErr =? (await reservations.markUnused(id)).errorOption:
return some State(SaleErrored(error: markUnusedErr))
trace "Starting download"
if err =? (await onStore(request,
data.slotIndex,
onBatch)).errorOption:
markUnused(availability.id)
return some State(SaleErrored(error: err))
trace "Download complete"
markUnused(availability.id)
[marketplace] Load sales state from chain (#306) * [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com>
2023-03-08 13:34:26 +00:00
return some State(SaleProving())