mirror of
https://github.com/codex-storage/nim-codex.git
synced 2025-01-10 04:55:40 +00:00
25f68c1e4c
* [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>
188 lines
5.8 KiB
Nim
188 lines
5.8 KiB
Nim
import std/sequtils
|
|
import pkg/questionable
|
|
import pkg/upraises
|
|
import pkg/stint
|
|
import pkg/nimcrypto
|
|
import pkg/chronicles
|
|
import ./rng
|
|
import ./market
|
|
import ./clock
|
|
import ./proving
|
|
import ./contracts/requests
|
|
import ./sales/salescontext
|
|
import ./sales/salesagent
|
|
import ./sales/availability
|
|
import ./sales/statemachine
|
|
import ./sales/states/downloading
|
|
import ./sales/states/unknown
|
|
|
|
## Sales holds a list of available storage that it may sell.
|
|
##
|
|
## When storage is requested on the market that matches availability, the Sales
|
|
## object will instruct the Codex node to persist the requested data. Once the
|
|
## data has been persisted, it uploads a proof of storage to the market in an
|
|
## attempt to win a storage contract.
|
|
##
|
|
## Node Sales Market
|
|
## | | |
|
|
## | -- add availability --> | |
|
|
## | | <-- storage request --- |
|
|
## | <----- store data ------ | |
|
|
## | -----------------------> | |
|
|
## | | |
|
|
## | <----- prove data ---- | |
|
|
## | -----------------------> | |
|
|
## | | ---- storage proof ---> |
|
|
|
|
export stint
|
|
export availability
|
|
|
|
type
|
|
Sales* = ref object
|
|
context*: SalesContext
|
|
subscription*: ?market.Subscription
|
|
available: seq[Availability]
|
|
agents*: seq[SalesAgent]
|
|
|
|
proc `onStore=`*(sales: Sales, onStore: OnStore) =
|
|
sales.context.onStore = some onStore
|
|
|
|
proc `onProve=`*(sales: Sales, onProve: OnProve) =
|
|
sales.context.onProve = some onProve
|
|
|
|
proc `onClear=`*(sales: Sales, onClear: OnClear) =
|
|
sales.context.onClear = some onClear
|
|
|
|
proc `onSale=`*(sales: Sales, callback: OnSale) =
|
|
sales.context.onSale = some callback
|
|
|
|
proc onStore*(sales: Sales): ?OnStore = sales.context.onStore
|
|
|
|
proc onProve*(sales: Sales): ?OnProve = sales.context.onProve
|
|
|
|
proc onClear*(sales: Sales): ?OnClear = sales.context.onClear
|
|
|
|
proc onSale*(sales: Sales): ?OnSale = sales.context.onSale
|
|
|
|
proc available*(sales: Sales): seq[Availability] = sales.available
|
|
|
|
proc init*(_: type Availability,
|
|
size: UInt256,
|
|
duration: UInt256,
|
|
minPrice: UInt256): Availability =
|
|
var id: array[32, byte]
|
|
doAssert randomBytes(id) == 32
|
|
Availability(id: id, size: size, duration: duration, minPrice: minPrice)
|
|
|
|
func add*(sales: Sales, availability: Availability) =
|
|
if not sales.available.contains(availability):
|
|
sales.available.add(availability)
|
|
# TODO: add to disk (persist), serialise to json.
|
|
|
|
func remove*(sales: Sales, availability: Availability) =
|
|
sales.available.keepItIf(it != availability)
|
|
# TODO: remove from disk availability, mark as in use by assigning
|
|
# a slotId, so that it can be used for restoration (node restart)
|
|
|
|
func new*(_: type Sales,
|
|
market: Market,
|
|
clock: Clock,
|
|
proving: Proving): Sales =
|
|
|
|
let sales = Sales(context: SalesContext(
|
|
market: market,
|
|
clock: clock,
|
|
proving: proving
|
|
))
|
|
|
|
proc onSaleErrored(availability: Availability) =
|
|
sales.add(availability)
|
|
|
|
sales.context.onSaleErrored = some onSaleErrored
|
|
sales
|
|
|
|
func findAvailability*(sales: Sales, ask: StorageAsk): ?Availability =
|
|
for availability in sales.available:
|
|
if ask.slotSize <= availability.size and
|
|
ask.duration <= availability.duration and
|
|
ask.pricePerSlot >= availability.minPrice:
|
|
return some availability
|
|
|
|
proc randomSlotIndex(numSlots: uint64): UInt256 =
|
|
let rng = Rng.instance
|
|
let slotIndex = rng.rand(numSlots - 1)
|
|
return slotIndex.u256
|
|
|
|
proc findSlotIndex(numSlots: uint64,
|
|
requestId: RequestId,
|
|
slotId: SlotId): ?UInt256 =
|
|
for i in 0..<numSlots:
|
|
if slotId(requestId, i.u256) == slotId:
|
|
return some i.u256
|
|
|
|
return none UInt256
|
|
|
|
proc handleRequest(sales: Sales,
|
|
requestId: RequestId,
|
|
ask: StorageAsk) =
|
|
without availability =? sales.findAvailability(ask):
|
|
return
|
|
sales.remove(availability)
|
|
# TODO: check if random slot is actually available (not already filled)
|
|
let slotIndex = randomSlotIndex(ask.slots)
|
|
let agent = newSalesAgent(
|
|
sales.context,
|
|
requestId,
|
|
slotIndex,
|
|
some availability,
|
|
none StorageRequest
|
|
)
|
|
agent.start(SaleDownloading())
|
|
sales.agents.add agent
|
|
|
|
proc load*(sales: Sales) {.async.} =
|
|
let market = sales.context.market
|
|
|
|
# TODO: restore availability from disk
|
|
let slotIds = await market.mySlots()
|
|
|
|
for slotId in slotIds:
|
|
# TODO: this needs to be optimised
|
|
if request =? await market.getRequestFromSlotId(slotId):
|
|
let availability = sales.findAvailability(request.ask)
|
|
without slotIndex =? findSlotIndex(request.ask.slots,
|
|
request.id,
|
|
slotId):
|
|
raiseAssert "could not find slot index"
|
|
|
|
let agent = newSalesAgent(
|
|
sales.context,
|
|
request.id,
|
|
slotIndex,
|
|
availability,
|
|
some request)
|
|
agent.start(SaleUnknown())
|
|
sales.agents.add agent
|
|
|
|
proc start*(sales: Sales) {.async.} =
|
|
doAssert sales.subscription.isNone, "Sales already started"
|
|
|
|
proc onRequest(requestId: RequestId, ask: StorageAsk) {.gcsafe, upraises:[].} =
|
|
sales.handleRequest(requestId, ask)
|
|
|
|
try:
|
|
sales.subscription = some await sales.context.market.subscribeRequests(onRequest)
|
|
except CatchableError as e:
|
|
error "Unable to start sales", msg = e.msg
|
|
|
|
proc stop*(sales: Sales) {.async.} =
|
|
if subscription =? sales.subscription:
|
|
sales.subscription = market.Subscription.none
|
|
try:
|
|
await subscription.unsubscribe()
|
|
except CatchableError as e:
|
|
warn "Unsubscribe failed", msg = e.msg
|
|
|
|
for agent in sales.agents:
|
|
await agent.stop()
|