60 lines
1.5 KiB
Nim
Raw Normal View History

2025-02-05 15:21:11 +01:00
import pkg/chronos
import pkg/chronicles
2025-02-05 14:05:18 +01:00
import pkg/metrics
2025-02-05 15:21:11 +01:00
import pkg/datastore
import pkg/datastore/typedds
import pkg/questionable
import pkg/questionable/results
import std/os
2025-02-05 16:06:04 +01:00
import ./nodeentry
2025-02-05 15:21:11 +01:00
logScope:
topics = "list"
2025-02-05 14:05:18 +01:00
type
2025-02-05 16:06:04 +01:00
OnUpdateMetric = proc(value: int64): void {.gcsafe, raises: [].}
2025-02-05 15:21:11 +01:00
List* = ref object
name: string
store: TypedDatastore
2025-02-05 16:06:04 +01:00
items: seq[NodeEntry]
2025-02-05 14:05:18 +01:00
onMetric: OnUpdateMetric
2025-02-05 15:21:11 +01:00
2025-02-05 16:06:04 +01:00
proc saveItem(this: List, item: NodeEntry): Future[?!void] {.async.} =
2025-02-05 15:59:48 +01:00
without itemKey =? Key.init(this.name / item.id), err:
return failure(err)
2025-02-05 16:06:04 +01:00
?await this.store.put(itemKey, item)
2025-02-05 15:21:11 +01:00
return success()
2025-02-05 16:06:04 +01:00
proc load*(this: List): Future[?!void] {.async.} =
2025-02-05 15:59:48 +01:00
without queryKey =? Key.init(this.name), err:
return failure(err)
2025-02-05 16:06:04 +01:00
without iter =? (await query[NodeEntry](this.store, Query.init(queryKey))), err:
2025-02-05 15:59:48 +01:00
return failure(err)
2025-02-05 15:21:11 +01:00
2025-02-05 15:59:48 +01:00
while not iter.finished:
without item =? (await iter.next()), err:
return failure(err)
without value =? item.value, err:
return failure(err)
if value.id.len > 0:
this.items.add(value)
2025-02-05 15:21:11 +01:00
info "Loaded list", name = this.name, items = this.items.len
return success()
proc new*(
2025-02-05 16:06:04 +01:00
_: type List, name: string, store: TypedDatastore, onMetric: OnUpdateMetric
2025-02-05 15:21:11 +01:00
): List =
2025-02-05 16:06:04 +01:00
List(name: name, store: store, items: newSeq[NodeEntry](), onMetric: onMetric)
2025-02-05 14:05:18 +01:00
2025-02-05 16:06:04 +01:00
proc add*(this: List, item: NodeEntry): Future[?!void] {.async.} =
2025-02-05 14:05:18 +01:00
this.items.add(item)
this.onMetric(this.items.len.int64)
2025-02-05 15:21:11 +01:00
2025-02-05 15:59:48 +01:00
if err =? (await this.saveItem(item)).errorOption:
return failure(err)
return success()