2022-12-03 00:00:55 +00:00
|
|
|
## Nim-Codex
|
|
|
|
## Copyright (c) 2022 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
|
|
|
import pkg/upraises
|
|
|
|
|
|
|
|
push: {.upraises: [].}
|
|
|
|
|
|
|
|
import pkg/chronos
|
2023-11-14 12:02:17 +00:00
|
|
|
import pkg/chronos/futures
|
2022-12-03 00:00:55 +00:00
|
|
|
import pkg/chronicles
|
2023-11-14 12:02:17 +00:00
|
|
|
import pkg/libp2p/[cid, multicodec, multihash]
|
|
|
|
import pkg/lrucache
|
2023-07-20 07:56:28 +00:00
|
|
|
import pkg/metrics
|
2022-12-03 00:00:55 +00:00
|
|
|
import pkg/questionable
|
|
|
|
import pkg/questionable/results
|
|
|
|
import pkg/datastore
|
|
|
|
import pkg/stew/endians2
|
|
|
|
|
|
|
|
import ./blockstore
|
2023-03-08 15:04:54 +00:00
|
|
|
import ./keyutils
|
2022-12-03 00:00:55 +00:00
|
|
|
import ../blocktype
|
2023-03-08 15:04:54 +00:00
|
|
|
import ../clock
|
|
|
|
import ../systemclock
|
2023-11-14 12:02:17 +00:00
|
|
|
import ../merkletree
|
|
|
|
import ../utils
|
2022-12-03 00:00:55 +00:00
|
|
|
|
2023-08-01 23:47:57 +00:00
|
|
|
export blocktype, cid
|
2022-12-03 00:00:55 +00:00
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "codex repostore"
|
|
|
|
|
2023-11-03 15:21:54 +00:00
|
|
|
declareGauge(codex_repostore_blocks, "codex repostore blocks")
|
|
|
|
declareGauge(codex_repostore_bytes_used, "codex repostore bytes used")
|
|
|
|
declareGauge(codex_repostore_bytes_reserved, "codex repostore bytes reserved")
|
2023-07-20 07:56:28 +00:00
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
const
|
|
|
|
DefaultBlockTtl* = 24.hours
|
|
|
|
DefaultQuotaBytes* = 1'u shl 33'u # ~8GB
|
|
|
|
|
|
|
|
type
|
|
|
|
QuotaUsedError* = object of CodexError
|
|
|
|
QuotaNotEnoughError* = object of CodexError
|
|
|
|
|
|
|
|
RepoStore* = ref object of BlockStore
|
|
|
|
postFixLen*: int
|
|
|
|
repoDs*: Datastore
|
|
|
|
metaDs*: Datastore
|
2023-03-08 15:04:54 +00:00
|
|
|
clock: Clock
|
2023-07-20 07:56:28 +00:00
|
|
|
totalBlocks*: uint # number of blocks in the store
|
2023-04-10 20:45:10 +00:00
|
|
|
quotaMaxBytes*: uint # maximum available bytes
|
|
|
|
quotaUsedBytes*: uint # bytes used by the repo
|
|
|
|
quotaReservedBytes*: uint # bytes reserved by the repo
|
2022-12-03 00:00:55 +00:00
|
|
|
blockTtl*: Duration
|
|
|
|
started*: bool
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
BlockExpiration* = object
|
|
|
|
cid*: Cid
|
|
|
|
expiration*: SecondsSince1970
|
2023-11-14 17:52:27 +00:00
|
|
|
|
2023-07-20 07:56:28 +00:00
|
|
|
proc updateMetrics(self: RepoStore) =
|
2023-11-03 15:21:54 +00:00
|
|
|
codex_repostore_blocks.set(self.totalBlocks.int64)
|
|
|
|
codex_repostore_bytes_used.set(self.quotaUsedBytes.int64)
|
|
|
|
codex_repostore_bytes_reserved.set(self.quotaReservedBytes.int64)
|
2023-07-20 07:56:28 +00:00
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
func totalUsed*(self: RepoStore): uint =
|
|
|
|
(self.quotaUsedBytes + self.quotaReservedBytes)
|
|
|
|
|
[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
|
|
|
func available*(self: RepoStore): uint =
|
|
|
|
return self.quotaMaxBytes - self.totalUsed
|
|
|
|
|
|
|
|
func available*(self: RepoStore, bytes: uint): bool =
|
|
|
|
return bytes < self.available()
|
|
|
|
|
2023-11-14 12:02:17 +00:00
|
|
|
proc encode(cidAndProof: (Cid, MerkleProof)): seq[byte] =
|
|
|
|
## Encodes a tuple of cid and merkle proof in a following format:
|
|
|
|
## | 8-bytes | n-bytes | remaining bytes |
|
|
|
|
## | n | cid | proof |
|
2023-11-14 17:52:27 +00:00
|
|
|
##
|
2023-11-14 12:02:17 +00:00
|
|
|
## where n is a size of cid
|
2023-11-14 17:52:27 +00:00
|
|
|
##
|
|
|
|
let
|
2023-11-14 12:02:17 +00:00
|
|
|
(cid, proof) = cidAndProof
|
|
|
|
cidBytes = cid.data.buffer
|
|
|
|
proofBytes = proof.encode
|
|
|
|
n = cidBytes.len
|
|
|
|
nBytes = n.uint64.toBytesBE
|
|
|
|
|
|
|
|
@nBytes & cidBytes & proofBytes
|
|
|
|
|
|
|
|
proc decode(_: type (Cid, MerkleProof), data: seq[byte]): ?!(Cid, MerkleProof) =
|
|
|
|
let
|
|
|
|
n = uint64.fromBytesBE(data[0..<sizeof(uint64)]).int
|
|
|
|
cid = ? Cid.init(data[sizeof(uint64)..<sizeof(uint64) + n]).mapFailure
|
|
|
|
proof = ? MerkleProof.decode(data[sizeof(uint64) + n..^1])
|
|
|
|
success((cid, proof))
|
|
|
|
|
|
|
|
method putBlockCidAndProof*(
|
|
|
|
self: RepoStore,
|
|
|
|
treeCid: Cid,
|
|
|
|
index: Natural,
|
|
|
|
blockCid: Cid,
|
|
|
|
proof: MerkleProof
|
|
|
|
): Future[?!void] {.async.} =
|
|
|
|
## Put a block to the blockstore
|
|
|
|
##
|
|
|
|
|
2023-11-16 16:05:36 +00:00
|
|
|
trace "putBlockCidAndProof", treeCid, index, blockCid
|
2023-11-14 12:02:17 +00:00
|
|
|
without key =? createBlockCidAndProofMetadataKey(treeCid, index), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
let value = (blockCid, proof).encode()
|
|
|
|
|
|
|
|
await self.metaDs.put(key, value)
|
|
|
|
|
|
|
|
proc getCidAndProof(
|
|
|
|
self: RepoStore,
|
|
|
|
treeCid: Cid,
|
|
|
|
index: Natural
|
|
|
|
): Future[?!(Cid, MerkleProof)] {.async.} =
|
|
|
|
without key =? createBlockCidAndProofMetadataKey(treeCid, index), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without value =? await self.metaDs.get(key), err:
|
|
|
|
if err of DatastoreKeyNotFound:
|
|
|
|
return failure(newException(BlockNotFoundError, err.msg))
|
|
|
|
else:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return (Cid, MerkleProof).decode(value)
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method getBlock*(self: RepoStore, cid: Cid): Future[?!Block] {.async.} =
|
|
|
|
## Get a block from the blockstore
|
|
|
|
##
|
|
|
|
|
2023-09-25 14:31:10 +00:00
|
|
|
logScope:
|
|
|
|
cid = cid
|
|
|
|
|
2023-08-21 02:51:04 +00:00
|
|
|
if cid.isEmpty:
|
|
|
|
trace "Empty block, ignoring"
|
2023-11-14 12:02:17 +00:00
|
|
|
return cid.emptyBlock
|
2023-08-21 02:51:04 +00:00
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
without key =? makePrefixKey(self.postFixLen, cid), err:
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Error getting key from provider", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without data =? await self.repoDs.get(key), err:
|
|
|
|
if not (err of DatastoreKeyNotFound):
|
|
|
|
trace "Error getting block from datastore", err = err.msg, key
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return failure(newException(BlockNotFoundError, err.msg))
|
|
|
|
|
|
|
|
trace "Got block for cid", cid
|
2023-11-14 12:02:17 +00:00
|
|
|
return Block.new(cid, data, verify = true)
|
|
|
|
|
|
|
|
|
|
|
|
method getBlockAndProof*(self: RepoStore, treeCid: Cid, index: Natural): Future[?!(Block, MerkleProof)] {.async.} =
|
|
|
|
without cidAndProof =? await self.getCidAndProof(treeCid, index), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
let (cid, proof) = cidAndProof
|
|
|
|
|
|
|
|
without blk =? await self.getBlock(cid), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
success((blk, proof))
|
|
|
|
|
|
|
|
method getBlock*(self: RepoStore, treeCid: Cid, index: Natural): Future[?!Block] {.async.} =
|
|
|
|
without cidAndProof =? await self.getCidAndProof(treeCid, index), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
await self.getBlock(cidAndProof[0])
|
|
|
|
|
|
|
|
method getBlock*(self: RepoStore, address: BlockAddress): Future[?!Block] =
|
|
|
|
## Get a block from the blockstore
|
|
|
|
##
|
|
|
|
|
|
|
|
if address.leaf:
|
|
|
|
self.getBlock(address.treeCid, address.index)
|
|
|
|
else:
|
|
|
|
self.getBlock(address.cid)
|
2022-12-03 00:00:55 +00:00
|
|
|
|
2023-11-06 08:10:30 +00:00
|
|
|
proc getBlockExpirationEntry(
|
|
|
|
self: RepoStore,
|
|
|
|
cid: Cid,
|
|
|
|
ttl: SecondsSince1970): ?!BatchEntry =
|
|
|
|
## Get an expiration entry for a batch with timestamp
|
|
|
|
##
|
|
|
|
|
|
|
|
without key =? createBlockExpirationMetadataKey(cid), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return success((key, ttl.toBytes))
|
2023-03-08 15:04:54 +00:00
|
|
|
|
2023-06-22 15:11:18 +00:00
|
|
|
proc getBlockExpirationEntry(
|
2023-09-25 14:31:10 +00:00
|
|
|
self: RepoStore,
|
|
|
|
cid: Cid,
|
|
|
|
ttl: ?Duration): ?!BatchEntry =
|
2023-11-06 08:10:30 +00:00
|
|
|
## Get an expiration entry for a batch for duration since "now"
|
2023-09-25 14:31:10 +00:00
|
|
|
##
|
|
|
|
|
2023-11-06 08:10:30 +00:00
|
|
|
let duration = ttl |? self.blockTtl
|
|
|
|
self.getBlockExpirationEntry(cid, self.clock.now() + duration.seconds)
|
|
|
|
|
|
|
|
method ensureExpiry*(
|
|
|
|
self: RepoStore,
|
|
|
|
cid: Cid,
|
|
|
|
expiry: SecondsSince1970
|
|
|
|
): Future[?!void] {.async.} =
|
|
|
|
## Ensure that block's assosicated expiry is at least given timestamp
|
|
|
|
## If the current expiry is lower then it is updated to the given one, otherwise it is left intact
|
|
|
|
##
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
cid = cid
|
|
|
|
|
|
|
|
if expiry <= 0:
|
|
|
|
return failure(newException(ValueError, "Expiry timestamp must be larger then zero"))
|
|
|
|
|
|
|
|
without expiryKey =? createBlockExpirationMetadataKey(cid), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without currentExpiry =? await self.metaDs.get(expiryKey), err:
|
|
|
|
if err of DatastoreKeyNotFound:
|
|
|
|
error "No current expiry exists for the block"
|
|
|
|
return failure(newException(BlockNotFoundError, err.msg))
|
|
|
|
else:
|
|
|
|
error "Could not read datastore key", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
if expiry <= currentExpiry.toSecondsSince1970:
|
|
|
|
trace "Current expiry is larger then the specified one, no action needed"
|
|
|
|
return success()
|
|
|
|
|
|
|
|
if err =? (await self.metaDs.put(expiryKey, expiry.toBytes)).errorOption:
|
|
|
|
trace "Error updating expiration metadata entry", err = err.msg
|
2023-03-08 15:04:54 +00:00
|
|
|
return failure(err)
|
|
|
|
|
2023-11-06 08:10:30 +00:00
|
|
|
return success()
|
2023-03-08 15:04:54 +00:00
|
|
|
|
2023-07-20 07:56:28 +00:00
|
|
|
proc persistTotalBlocksCount(self: RepoStore): Future[?!void] {.async.} =
|
|
|
|
if err =? (await self.metaDs.put(
|
|
|
|
CodexTotalBlocksKey,
|
|
|
|
@(self.totalBlocks.uint64.toBytesBE))).errorOption:
|
|
|
|
trace "Error total blocks key!", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
return success()
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method putBlock*(
|
2023-09-25 14:31:10 +00:00
|
|
|
self: RepoStore,
|
|
|
|
blk: Block,
|
|
|
|
ttl = Duration.none): Future[?!void] {.async.} =
|
2022-12-03 00:00:55 +00:00
|
|
|
## Put a block to the blockstore
|
|
|
|
##
|
|
|
|
|
2023-09-25 14:31:10 +00:00
|
|
|
logScope:
|
|
|
|
cid = blk.cid
|
|
|
|
|
2023-08-21 02:51:04 +00:00
|
|
|
if blk.isEmpty:
|
|
|
|
trace "Empty block, ignoring"
|
|
|
|
return success()
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
without key =? makePrefixKey(self.postFixLen, blk.cid), err:
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Error getting key from provider", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
if await key in self.repoDs:
|
|
|
|
trace "Block already in store", cid = blk.cid
|
|
|
|
return success()
|
|
|
|
|
|
|
|
if (self.totalUsed + blk.data.len.uint) > self.quotaMaxBytes:
|
|
|
|
error "Cannot store block, quota used!", used = self.totalUsed
|
|
|
|
return failure(
|
|
|
|
newException(QuotaUsedError, "Cannot store block, quota used!"))
|
|
|
|
|
|
|
|
trace "Storing block with key", key
|
|
|
|
|
|
|
|
var
|
|
|
|
batch: seq[BatchEntry]
|
|
|
|
|
|
|
|
let
|
|
|
|
used = self.quotaUsedBytes + blk.data.len.uint
|
|
|
|
|
|
|
|
if err =? (await self.repoDs.put(key, blk.data)).errorOption:
|
|
|
|
trace "Error storing block", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
trace "Updating quota", used
|
|
|
|
batch.add((QuotaUsedKey, @(used.uint64.toBytesBE)))
|
|
|
|
|
2023-11-06 08:10:30 +00:00
|
|
|
without blockExpEntry =? self.getBlockExpirationEntry(blk.cid, ttl), err:
|
2023-03-08 15:04:54 +00:00
|
|
|
trace "Unable to create block expiration metadata key", err = err.msg
|
2022-12-03 00:00:55 +00:00
|
|
|
return failure(err)
|
2023-03-08 15:04:54 +00:00
|
|
|
batch.add(blockExpEntry)
|
2022-12-03 00:00:55 +00:00
|
|
|
|
|
|
|
if err =? (await self.metaDs.put(batch)).errorOption:
|
|
|
|
trace "Error updating quota bytes", err = err.msg
|
|
|
|
|
|
|
|
if err =? (await self.repoDs.delete(key)).errorOption:
|
|
|
|
trace "Error deleting block after failed quota update", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
self.quotaUsedBytes = used
|
2023-07-20 07:56:28 +00:00
|
|
|
inc self.totalBlocks
|
|
|
|
if isErr (await self.persistTotalBlocksCount()):
|
|
|
|
trace "Unable to update block total metadata"
|
|
|
|
return failure("Unable to update block total metadata")
|
|
|
|
|
|
|
|
self.updateMetrics()
|
2022-12-03 00:00:55 +00:00
|
|
|
return success()
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
proc updateQuotaBytesUsed(self: RepoStore, blk: Block): Future[?!void] {.async.} =
|
|
|
|
let used = self.quotaUsedBytes - blk.data.len.uint
|
|
|
|
if err =? (await self.metaDs.put(
|
|
|
|
QuotaUsedKey,
|
|
|
|
@(used.uint64.toBytesBE))).errorOption:
|
|
|
|
trace "Error updating quota key!", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
self.quotaUsedBytes = used
|
2023-07-20 07:56:28 +00:00
|
|
|
self.updateMetrics()
|
2023-03-08 15:04:54 +00:00
|
|
|
return success()
|
|
|
|
|
|
|
|
proc removeBlockExpirationEntry(self: RepoStore, cid: Cid): Future[?!void] {.async.} =
|
|
|
|
without key =? createBlockExpirationMetadataKey(cid), err:
|
|
|
|
return failure(err)
|
|
|
|
return await self.metaDs.delete(key)
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method delBlock*(self: RepoStore, cid: Cid): Future[?!void] {.async.} =
|
|
|
|
## Delete a block from the blockstore
|
|
|
|
##
|
|
|
|
|
2023-09-25 14:31:10 +00:00
|
|
|
logScope:
|
|
|
|
cid = cid
|
|
|
|
|
|
|
|
trace "Deleting block"
|
|
|
|
|
2023-08-21 02:51:04 +00:00
|
|
|
if cid.isEmpty:
|
|
|
|
trace "Empty block, ignoring"
|
|
|
|
return success()
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
if blk =? (await self.getBlock(cid)):
|
2023-03-08 15:04:54 +00:00
|
|
|
if key =? makePrefixKey(self.postFixLen, cid) and
|
2022-12-03 00:00:55 +00:00
|
|
|
err =? (await self.repoDs.delete(key)).errorOption:
|
|
|
|
trace "Error deleting block!", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
if isErr (await self.updateQuotaBytesUsed(blk)):
|
|
|
|
trace "Unable to update quote-bytes-used in metadata store"
|
|
|
|
return failure("Unable to update quote-bytes-used in metadata store")
|
2022-12-03 00:00:55 +00:00
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
if isErr (await self.removeBlockExpirationEntry(blk.cid)):
|
|
|
|
trace "Unable to remove block expiration entry from metadata store"
|
|
|
|
return failure("Unable to remove block expiration entry from metadata store")
|
2022-12-03 00:00:55 +00:00
|
|
|
|
|
|
|
trace "Deleted block", cid, totalUsed = self.totalUsed
|
|
|
|
|
2023-07-20 07:56:28 +00:00
|
|
|
dec self.totalBlocks
|
|
|
|
if isErr (await self.persistTotalBlocksCount()):
|
|
|
|
trace "Unable to update block total metadata"
|
|
|
|
return failure("Unable to update block total metadata")
|
|
|
|
|
|
|
|
self.updateMetrics()
|
2022-12-03 00:00:55 +00:00
|
|
|
return success()
|
|
|
|
|
2023-11-14 12:02:17 +00:00
|
|
|
method delBlock*(self: RepoStore, treeCid: Cid, index: Natural): Future[?!void] {.async.} =
|
|
|
|
without key =? createBlockCidAndProofMetadataKey(treeCid, index), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without value =? await self.metaDs.get(key), err:
|
|
|
|
if err of DatastoreKeyNotFound:
|
|
|
|
return success()
|
|
|
|
else:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without cidAndProof =? (Cid, MerkleProof).decode(value), err:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
self.delBlock(cidAndProof[0])
|
|
|
|
|
|
|
|
await self.metaDs.delete(key)
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method hasBlock*(self: RepoStore, cid: Cid): Future[?!bool] {.async.} =
|
|
|
|
## Check if the block exists in the blockstore
|
|
|
|
##
|
|
|
|
|
2023-09-25 14:31:10 +00:00
|
|
|
logScope:
|
|
|
|
cid = cid
|
|
|
|
|
2023-08-21 02:51:04 +00:00
|
|
|
if cid.isEmpty:
|
|
|
|
trace "Empty block, ignoring"
|
2023-09-25 14:31:10 +00:00
|
|
|
return success true
|
2023-08-21 02:51:04 +00:00
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
without key =? makePrefixKey(self.postFixLen, cid), err:
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Error getting key from provider", err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return await self.repoDs.has(key)
|
|
|
|
|
2023-11-14 12:02:17 +00:00
|
|
|
method hasBlock*(self: RepoStore, treeCid: Cid, index: Natural): Future[?!bool] {.async.} =
|
|
|
|
without cidAndProof =? await self.getCidAndProof(treeCid, index), err:
|
|
|
|
if err of BlockNotFoundError:
|
|
|
|
return success(false)
|
|
|
|
else:
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
await self.hasBlock(cidAndProof[0])
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method listBlocks*(
|
2023-09-25 14:31:10 +00:00
|
|
|
self: RepoStore,
|
2023-11-14 12:02:17 +00:00
|
|
|
blockType = BlockType.Manifest
|
|
|
|
): Future[?!AsyncIter[?Cid]] {.async.} =
|
2022-12-03 00:00:55 +00:00
|
|
|
## Get the list of blocks in the RepoStore.
|
|
|
|
## This is an intensive operation
|
|
|
|
##
|
|
|
|
|
|
|
|
var
|
2023-11-14 12:02:17 +00:00
|
|
|
iter = AsyncIter[?Cid]()
|
2022-12-03 00:00:55 +00:00
|
|
|
|
|
|
|
let key =
|
|
|
|
case blockType:
|
|
|
|
of BlockType.Manifest: CodexManifestKey
|
|
|
|
of BlockType.Block: CodexBlocksKey
|
|
|
|
of BlockType.Both: CodexRepoKey
|
|
|
|
|
2023-08-22 06:26:58 +00:00
|
|
|
let query = Query.init(key, value=false)
|
|
|
|
without queryIter =? (await self.repoDs.query(query)), err:
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Error querying cids in repo", blockType, err = err.msg
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
proc next(): Future[?Cid] {.async.} =
|
|
|
|
await idleAsync()
|
2023-11-14 12:02:17 +00:00
|
|
|
if queryIter.finished:
|
|
|
|
iter.finish
|
|
|
|
else:
|
2022-12-03 00:00:55 +00:00
|
|
|
if pair =? (await queryIter.next()) and cid =? pair.key:
|
2023-08-22 06:26:58 +00:00
|
|
|
doAssert pair.data.len == 0
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Retrieved record from repo", cid
|
|
|
|
return Cid.init(cid.value).option
|
2023-11-14 12:02:17 +00:00
|
|
|
else:
|
|
|
|
return Cid.none
|
2022-12-03 00:00:55 +00:00
|
|
|
|
|
|
|
iter.next = next
|
|
|
|
return success iter
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
proc createBlockExpirationQuery(maxNumber: int, offset: int): ?!Query =
|
|
|
|
let queryKey = ? createBlockExpirationMetadataQueryKey()
|
|
|
|
success Query.init(queryKey, offset = offset, limit = maxNumber)
|
|
|
|
|
2023-06-22 15:11:18 +00:00
|
|
|
method getBlockExpirations*(
|
2023-09-25 14:31:10 +00:00
|
|
|
self: RepoStore,
|
|
|
|
maxNumber: int,
|
2023-11-14 12:02:17 +00:00
|
|
|
offset: int): Future[?!AsyncIter[?BlockExpiration]] {.async, base.} =
|
2023-09-25 14:31:10 +00:00
|
|
|
## Get block expirations from the given RepoStore
|
2023-07-20 07:56:28 +00:00
|
|
|
##
|
2023-09-25 14:31:10 +00:00
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
without query =? createBlockExpirationQuery(maxNumber, offset), err:
|
|
|
|
trace "Unable to format block expirations query"
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
without queryIter =? (await self.metaDs.query(query)), err:
|
|
|
|
trace "Unable to execute block expirations query"
|
|
|
|
return failure(err)
|
|
|
|
|
2023-11-14 12:02:17 +00:00
|
|
|
var iter = AsyncIter[?BlockExpiration]()
|
2023-03-08 15:04:54 +00:00
|
|
|
|
|
|
|
proc next(): Future[?BlockExpiration] {.async.} =
|
|
|
|
if not queryIter.finished:
|
|
|
|
if pair =? (await queryIter.next()) and blockKey =? pair.key:
|
|
|
|
let expirationTimestamp = pair.data
|
|
|
|
let cidResult = Cid.init(blockKey.value)
|
|
|
|
if not cidResult.isOk:
|
|
|
|
raiseAssert("Unable to parse CID from blockKey.value: " & blockKey.value & $cidResult.error)
|
|
|
|
return BlockExpiration(
|
|
|
|
cid: cidResult.get,
|
|
|
|
expiration: expirationTimestamp.toSecondsSince1970
|
|
|
|
).some
|
|
|
|
else:
|
|
|
|
discard await queryIter.dispose()
|
2023-11-14 12:02:17 +00:00
|
|
|
iter.finish
|
2023-03-08 15:04:54 +00:00
|
|
|
return BlockExpiration.none
|
|
|
|
|
|
|
|
iter.next = next
|
|
|
|
return success iter
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
method close*(self: RepoStore): Future[void] {.async.} =
|
|
|
|
## Close the blockstore, cleaning up resources managed by it.
|
|
|
|
## For some implementations this may be a no-op
|
|
|
|
##
|
|
|
|
|
|
|
|
(await self.repoDs.close()).expect("Should close datastore")
|
|
|
|
|
|
|
|
proc reserve*(self: RepoStore, bytes: uint): Future[?!void] {.async.} =
|
|
|
|
## Reserve bytes
|
|
|
|
##
|
|
|
|
|
|
|
|
trace "Reserving bytes", reserved = self.quotaReservedBytes, bytes
|
|
|
|
|
|
|
|
if (self.totalUsed + bytes) > self.quotaMaxBytes:
|
|
|
|
trace "Not enough storage quota to reserver", reserve = self.totalUsed + bytes
|
|
|
|
return failure(
|
|
|
|
newException(QuotaNotEnoughError, "Not enough storage quota to reserver"))
|
|
|
|
|
|
|
|
self.quotaReservedBytes += bytes
|
|
|
|
if err =? (await self.metaDs.put(
|
|
|
|
QuotaReservedKey,
|
|
|
|
@(toBytesBE(self.quotaReservedBytes.uint64)))).errorOption:
|
|
|
|
|
|
|
|
trace "Error reserving bytes", err = err.msg
|
|
|
|
|
|
|
|
self.quotaReservedBytes += bytes
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
return success()
|
|
|
|
|
|
|
|
proc release*(self: RepoStore, bytes: uint): Future[?!void] {.async.} =
|
|
|
|
## Release bytes
|
|
|
|
##
|
|
|
|
|
|
|
|
trace "Releasing bytes", reserved = self.quotaReservedBytes, bytes
|
|
|
|
|
|
|
|
if (self.quotaReservedBytes.int - bytes.int) < 0:
|
|
|
|
trace "Cannot release this many bytes",
|
|
|
|
quotaReservedBytes = self.quotaReservedBytes, bytes
|
|
|
|
|
|
|
|
return failure("Cannot release this many bytes")
|
|
|
|
|
|
|
|
self.quotaReservedBytes -= bytes
|
|
|
|
if err =? (await self.metaDs.put(
|
|
|
|
QuotaReservedKey,
|
|
|
|
@(toBytesBE(self.quotaReservedBytes.uint64)))).errorOption:
|
|
|
|
|
|
|
|
trace "Error releasing bytes", err = err.msg
|
|
|
|
|
|
|
|
self.quotaReservedBytes -= bytes
|
|
|
|
|
|
|
|
return failure(err)
|
|
|
|
|
|
|
|
trace "Released bytes", bytes
|
2023-07-20 07:56:28 +00:00
|
|
|
self.updateMetrics()
|
2022-12-03 00:00:55 +00:00
|
|
|
return success()
|
|
|
|
|
|
|
|
proc start*(self: RepoStore): Future[void] {.async.} =
|
|
|
|
## Start repo
|
|
|
|
##
|
|
|
|
|
|
|
|
if self.started:
|
|
|
|
trace "Repo already started"
|
|
|
|
return
|
|
|
|
|
|
|
|
trace "Starting repo"
|
|
|
|
|
2023-07-20 07:56:28 +00:00
|
|
|
without total =? await self.metaDs.get(CodexTotalBlocksKey), err:
|
|
|
|
if not (err of DatastoreKeyNotFound):
|
|
|
|
error "Unable to read total number of blocks from metadata store", err = err.msg, key = $CodexTotalBlocksKey
|
|
|
|
|
|
|
|
if total.len > 0:
|
|
|
|
self.totalBlocks = uint64.fromBytesBE(total).uint
|
|
|
|
trace "Number of blocks in store at start", total = self.totalBlocks
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
## load current persist and cache bytes from meta ds
|
|
|
|
without quotaUsedBytes =? await self.metaDs.get(QuotaUsedKey), err:
|
|
|
|
if not (err of DatastoreKeyNotFound):
|
|
|
|
error "Error getting cache bytes from datastore",
|
|
|
|
err = err.msg, key = $QuotaUsedKey
|
|
|
|
|
|
|
|
raise newException(Defect, err.msg)
|
|
|
|
|
|
|
|
if quotaUsedBytes.len > 0:
|
|
|
|
self.quotaUsedBytes = uint64.fromBytesBE(quotaUsedBytes).uint
|
|
|
|
|
|
|
|
notice "Current bytes used for cache quota", bytes = self.quotaUsedBytes
|
|
|
|
|
|
|
|
without quotaReservedBytes =? await self.metaDs.get(QuotaReservedKey), err:
|
|
|
|
if not (err of DatastoreKeyNotFound):
|
|
|
|
error "Error getting persist bytes from datastore",
|
|
|
|
err = err.msg, key = $QuotaReservedKey
|
|
|
|
|
|
|
|
raise newException(Defect, err.msg)
|
|
|
|
|
|
|
|
if quotaReservedBytes.len > 0:
|
|
|
|
self.quotaReservedBytes = uint64.fromBytesBE(quotaReservedBytes).uint
|
|
|
|
|
|
|
|
if self.quotaUsedBytes > self.quotaMaxBytes:
|
|
|
|
raiseAssert "All storage quota used, increase storage quota!"
|
|
|
|
|
|
|
|
notice "Current bytes used for persist quota", bytes = self.quotaReservedBytes
|
|
|
|
|
2023-07-20 07:56:28 +00:00
|
|
|
self.updateMetrics()
|
2022-12-03 00:00:55 +00:00
|
|
|
self.started = true
|
|
|
|
|
|
|
|
proc stop*(self: RepoStore): Future[void] {.async.} =
|
|
|
|
## Stop repo
|
|
|
|
##
|
2023-03-16 15:00:36 +00:00
|
|
|
if not self.started:
|
2022-12-03 00:00:55 +00:00
|
|
|
trace "Repo is not started"
|
|
|
|
return
|
|
|
|
|
|
|
|
trace "Stopping repo"
|
|
|
|
(await self.repoDs.close()).expect("Should close repo store!")
|
|
|
|
(await self.metaDs.close()).expect("Should close meta store!")
|
|
|
|
|
2023-03-16 15:00:36 +00:00
|
|
|
self.started = false
|
|
|
|
|
2022-12-03 00:00:55 +00:00
|
|
|
func new*(
|
2023-06-22 15:11:18 +00:00
|
|
|
T: type RepoStore,
|
|
|
|
repoDs: Datastore,
|
|
|
|
metaDs: Datastore,
|
|
|
|
clock: Clock = SystemClock.new(),
|
|
|
|
postFixLen = 2,
|
|
|
|
quotaMaxBytes = DefaultQuotaBytes,
|
|
|
|
blockTtl = DefaultBlockTtl
|
|
|
|
): RepoStore =
|
2023-07-20 07:56:28 +00:00
|
|
|
## Create new instance of a RepoStore
|
|
|
|
##
|
2023-06-22 15:11:18 +00:00
|
|
|
RepoStore(
|
2022-12-03 00:00:55 +00:00
|
|
|
repoDs: repoDs,
|
|
|
|
metaDs: metaDs,
|
2023-03-08 15:04:54 +00:00
|
|
|
clock: clock,
|
2022-12-03 00:00:55 +00:00
|
|
|
postFixLen: postFixLen,
|
|
|
|
quotaMaxBytes: quotaMaxBytes,
|
2023-11-14 12:02:17 +00:00
|
|
|
blockTtl: blockTtl
|
|
|
|
)
|