62 lines
1.7 KiB
Nim
Raw Normal View History

2025-02-07 13:57:57 +01:00
import pkg/chronicles
import pkg/chronos
2025-02-07 14:51:03 +01:00
import pkg/questionable
import pkg/questionable/results
2025-02-07 13:57:57 +01:00
2025-02-12 13:25:37 +01:00
import ../services/dht
import ./todolist
2025-02-10 14:49:30 +01:00
import ../config
2025-02-10 15:34:41 +01:00
import ../types
2025-02-12 13:25:37 +01:00
import ../component
2025-02-10 15:34:41 +01:00
import ../state
import ../utils/asyncdataevent
2025-02-07 13:57:57 +01:00
logScope:
2025-03-19 15:52:50 +01:00
topics = "dhtcrawler"
2025-02-07 13:57:57 +01:00
2025-03-19 15:52:50 +01:00
type DhtCrawler* = ref object of Component
2025-02-12 13:25:37 +01:00
state: State
2025-02-07 13:57:57 +01:00
dht: Dht
2025-02-12 13:25:37 +01:00
todo: TodoList
2025-02-07 14:51:03 +01:00
2025-02-12 13:50:12 +01:00
proc raiseCheckEvent(
2025-03-19 15:52:50 +01:00
c: DhtCrawler, nid: Nid, success: bool
2025-02-12 13:50:12 +01:00
): Future[?!void] {.async: (raises: []).} =
let event = DhtNodeCheckEventData(id: nid, isOk: success)
2025-02-12 13:25:37 +01:00
if err =? (await c.state.events.dhtNodeCheck.fire(event)).errorOption:
error "failed to raise check event", err = err.msg
2025-02-12 13:25:37 +01:00
return failure(err)
return success()
2025-02-07 15:35:40 +01:00
2025-03-19 15:52:50 +01:00
proc step(c: DhtCrawler): Future[?!void] {.async: (raises: []).} =
2025-02-12 13:25:37 +01:00
without nid =? (await c.todo.pop()), err:
error "failed to pop todolist", err = err.msg
2025-02-12 13:25:37 +01:00
return failure(err)
2025-02-07 14:51:03 +01:00
2025-02-12 13:25:37 +01:00
without response =? await c.dht.getNeighbors(nid), err:
error "failed to get neighbors", err = err.msg
2025-02-12 13:25:37 +01:00
return failure(err)
2025-02-07 14:51:03 +01:00
2025-02-12 13:25:37 +01:00
if err =? (await c.raiseCheckEvent(nid, response.isResponsive)).errorOption:
return failure(err)
2025-02-07 14:51:03 +01:00
2025-02-12 13:25:37 +01:00
if err =? (await c.state.events.nodesFound.fire(response.nodeIds)).errorOption:
error "failed to raise nodesFound event", err = err.msg
2025-02-12 13:25:37 +01:00
return failure(err)
2025-02-07 15:35:40 +01:00
2025-02-12 13:25:37 +01:00
return success()
2025-02-07 14:51:03 +01:00
2025-03-19 15:52:50 +01:00
method start*(c: DhtCrawler): Future[?!void] {.async.} =
info "starting..."
2025-02-12 13:25:37 +01:00
proc onStep(): Future[?!void] {.async: (raises: []), gcsafe.} =
await c.step()
2025-02-12 13:50:12 +01:00
2025-03-10 14:09:41 +01:00
if c.state.config.dhtEnable:
await c.state.whileRunning(onStep, c.state.config.stepDelayMs.milliseconds)
2025-02-07 14:51:03 +01:00
return success()
2025-02-07 13:57:57 +01:00
2025-03-19 15:52:50 +01:00
proc new*(T: type DhtCrawler, state: State, dht: Dht, todo: TodoList): DhtCrawler =
DhtCrawler(state: state, dht: dht, todo: todo)