2023-03-02 15:23:30 +00:00
|
|
|
## Waku Filter protocol for subscribing and filtering messages
|
|
|
|
|
|
|
|
when (NimMajor, NimMinor) < (1, 4):
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
else:
|
|
|
|
{.push raises: [].}
|
|
|
|
|
|
|
|
import
|
2023-04-11 08:12:54 +00:00
|
|
|
std/[options,sequtils,sets,strutils,tables],
|
2023-08-30 22:10:51 +00:00
|
|
|
stew/byteutils,
|
2023-03-02 15:23:30 +00:00
|
|
|
chronicles,
|
|
|
|
chronos,
|
|
|
|
libp2p/peerid,
|
|
|
|
libp2p/protocols/protocol
|
|
|
|
import
|
2023-04-18 13:22:10 +00:00
|
|
|
../node/peer_manager,
|
2023-04-19 11:29:23 +00:00
|
|
|
../waku_core,
|
2023-03-02 15:23:30 +00:00
|
|
|
./common,
|
|
|
|
./protocol_metrics,
|
|
|
|
./rpc_codec,
|
2023-03-20 11:19:53 +00:00
|
|
|
./rpc,
|
|
|
|
./subscriptions
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "waku filter"
|
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
const
|
2024-01-16 16:27:40 +00:00
|
|
|
MaxContentTopicsPerRequest* = 100
|
2023-03-22 08:32:53 +00:00
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
type
|
|
|
|
WakuFilter* = ref object of LPProtocol
|
2023-03-20 11:19:53 +00:00
|
|
|
subscriptions*: FilterSubscriptions # a mapping of peer ids to a sequence of filter criteria
|
2023-03-02 15:23:30 +00:00
|
|
|
peerManager: PeerManager
|
2023-04-11 08:12:54 +00:00
|
|
|
maintenanceTask: TimerCallback
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
proc pingSubscriber(wf: WakuFilter, peerId: PeerID): FilterSubscribeResult =
|
|
|
|
trace "pinging subscriber", peerId=peerId
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
if not wf.subscriptions.isSubscribed(peerId):
|
2023-03-02 15:23:30 +00:00
|
|
|
debug "pinging peer has no subscriptions", peerId=peerId
|
|
|
|
return err(FilterSubscribeError.notFound())
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
wf.subscriptions.refreshSubscription(peerId)
|
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
ok()
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
proc subscribe(wf: WakuFilter,
|
|
|
|
peerId: PeerID,
|
|
|
|
pubsubTopic: Option[PubsubTopic],
|
|
|
|
contentTopics: seq[ContentTopic]): FilterSubscribeResult =
|
|
|
|
|
|
|
|
# TODO: check if this condition is valid???
|
|
|
|
if pubsubTopic.isNone() or contentTopics.len == 0:
|
2023-03-02 15:23:30 +00:00
|
|
|
return err(FilterSubscribeError.badRequest("pubsubTopic and contentTopics must be specified"))
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
if contentTopics.len > MaxContentTopicsPerRequest:
|
|
|
|
return err(FilterSubscribeError.badRequest("exceeds maximum content topics: " &
|
|
|
|
$MaxContentTopicsPerRequest))
|
2023-03-22 08:32:53 +00:00
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
let filterCriteria = toHashSet(contentTopics.mapIt((pubsubTopic.get(), it)))
|
|
|
|
|
|
|
|
trace "subscribing peer to filter criteria", peerId=peerId, filterCriteria=filterCriteria
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
wf.subscriptions.addSubscription(peerId, filterCriteria).isOkOr:
|
|
|
|
return err(FilterSubscribeError.serviceUnavailable(error))
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
ok()
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
proc unsubscribe(wf: WakuFilter,
|
|
|
|
peerId: PeerID,
|
|
|
|
pubsubTopic: Option[PubsubTopic],
|
|
|
|
contentTopics: seq[ContentTopic]): FilterSubscribeResult =
|
|
|
|
if pubsubTopic.isNone() or contentTopics.len == 0:
|
2023-03-02 15:23:30 +00:00
|
|
|
return err(FilterSubscribeError.badRequest("pubsubTopic and contentTopics must be specified"))
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
if contentTopics.len > MaxContentTopicsPerRequest:
|
2023-03-22 08:32:53 +00:00
|
|
|
return err(FilterSubscribeError.badRequest("exceeds maximum content topics: " & $MaxContentTopicsPerRequest))
|
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
let filterCriteria = toHashSet(contentTopics.mapIt((pubsubTopic.get(), it)))
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
debug "unsubscribing peer from filter criteria", peerId=peerId, filterCriteria=filterCriteria
|
2023-11-15 09:26:01 +00:00
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
wf.subscriptions.removeSubscription(peerId, filterCriteria).isOkOr:
|
2023-11-15 09:26:01 +00:00
|
|
|
return err(FilterSubscribeError.notFound())
|
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
ok()
|
|
|
|
|
|
|
|
proc unsubscribeAll(wf: WakuFilter, peerId: PeerID): FilterSubscribeResult =
|
2024-01-16 16:27:40 +00:00
|
|
|
if not wf.subscriptions.isSubscribed(peerId):
|
2023-04-11 08:12:54 +00:00
|
|
|
debug "unsubscribing peer has no subscriptions", peerId=peerId
|
2023-03-02 15:23:30 +00:00
|
|
|
return err(FilterSubscribeError.notFound())
|
|
|
|
|
|
|
|
debug "removing peer subscription", peerId=peerId
|
2024-01-16 16:27:40 +00:00
|
|
|
wf.subscriptions.removePeer(peerId)
|
|
|
|
wf.subscriptions.cleanUp()
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
ok()
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
proc handleSubscribeRequest*(wf: WakuFilter,
|
|
|
|
peerId: PeerId,
|
|
|
|
request: FilterSubscribeRequest): FilterSubscribeResponse =
|
2023-03-02 15:23:30 +00:00
|
|
|
info "received filter subscribe request", peerId=peerId, request=request
|
|
|
|
waku_filter_requests.inc(labelValues = [$request.filterSubscribeType])
|
|
|
|
|
|
|
|
var subscribeResult: FilterSubscribeResult
|
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
let requestStartTime = Moment.now()
|
|
|
|
|
|
|
|
block:
|
|
|
|
## Handle subscribe request
|
|
|
|
case request.filterSubscribeType
|
|
|
|
of FilterSubscribeType.SUBSCRIBER_PING:
|
|
|
|
subscribeResult = wf.pingSubscriber(peerId)
|
|
|
|
of FilterSubscribeType.SUBSCRIBE:
|
|
|
|
subscribeResult = wf.subscribe(peerId, request.pubsubTopic, request.contentTopics)
|
|
|
|
of FilterSubscribeType.UNSUBSCRIBE:
|
|
|
|
subscribeResult = wf.unsubscribe(peerId, request.pubsubTopic, request.contentTopics)
|
|
|
|
of FilterSubscribeType.UNSUBSCRIBE_ALL:
|
|
|
|
subscribeResult = wf.unsubscribeAll(peerId)
|
|
|
|
|
|
|
|
let
|
|
|
|
requestDuration = Moment.now() - requestStartTime
|
|
|
|
requestDurationSec = requestDuration.milliseconds.float / 1000 # Duration in seconds with millisecond precision floating point
|
2024-01-16 16:27:40 +00:00
|
|
|
waku_filter_request_duration_seconds.observe(
|
|
|
|
requestDurationSec, labelValues = [$request.filterSubscribeType])
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
if subscribeResult.isErr():
|
|
|
|
return FilterSubscribeResponse(
|
|
|
|
requestId: request.requestId,
|
|
|
|
statusCode: subscribeResult.error.kind.uint32,
|
|
|
|
statusDesc: some($subscribeResult.error)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return FilterSubscribeResponse.ok(request.requestId)
|
|
|
|
|
2023-03-20 11:19:53 +00:00
|
|
|
proc pushToPeer(wf: WakuFilter, peer: PeerId, buffer: seq[byte]) {.async.} =
|
|
|
|
trace "pushing message to subscribed peer", peer=peer
|
|
|
|
|
|
|
|
if not wf.peerManager.peerStore.hasPeer(peer, WakuFilterPushCodec):
|
|
|
|
# Check that peer has not been removed from peer store
|
|
|
|
trace "no addresses for peer", peer=peer
|
|
|
|
return
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
## TODO: Check if dial is necessary always???
|
2023-03-20 11:19:53 +00:00
|
|
|
let conn = await wf.peerManager.dialPeer(peer, WakuFilterPushCodec)
|
|
|
|
if conn.isNone():
|
|
|
|
## We do not remove this peer, but allow the underlying peer manager
|
|
|
|
## to do so if it is deemed necessary
|
|
|
|
trace "no connection to peer", peer=peer
|
|
|
|
return
|
|
|
|
|
|
|
|
await conn.get().writeLp(buffer)
|
|
|
|
|
|
|
|
proc pushToPeers(wf: WakuFilter, peers: seq[PeerId], messagePush: MessagePush) {.async.} =
|
2024-01-16 16:27:40 +00:00
|
|
|
debug "pushing message to subscribed peers", pubsubTopic=messagePush.pubsubTopic,
|
|
|
|
contentTopic=messagePush.wakuMessage.contentTopic,
|
|
|
|
peers=peers,
|
|
|
|
hash=messagePush.pubsubTopic.computeMessageHash(messagePush.wakuMessage).to0xHex()
|
2023-03-20 11:19:53 +00:00
|
|
|
|
|
|
|
let bufferToPublish = messagePush.encode().buffer
|
|
|
|
|
|
|
|
var pushFuts: seq[Future[void]]
|
|
|
|
for peerId in peers:
|
|
|
|
let pushFut = wf.pushToPeer(peerId, bufferToPublish)
|
|
|
|
pushFuts.add(pushFut)
|
|
|
|
|
|
|
|
await allFutures(pushFuts)
|
|
|
|
|
|
|
|
proc maintainSubscriptions*(wf: WakuFilter) =
|
|
|
|
trace "maintaining subscriptions"
|
|
|
|
|
2023-04-11 08:12:54 +00:00
|
|
|
## Remove subscriptions for peers that have been removed from peer store
|
2023-03-20 11:19:53 +00:00
|
|
|
var peersToRemove: seq[PeerId]
|
2024-01-16 16:27:40 +00:00
|
|
|
for peerId in wf.subscriptions.peersSubscribed.keys:
|
2023-03-20 11:19:53 +00:00
|
|
|
if not wf.peerManager.peerStore.hasPeer(peerId, WakuFilterPushCodec):
|
|
|
|
debug "peer has been removed from peer store, removing subscription", peerId=peerId
|
|
|
|
peersToRemove.add(peerId)
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
if peersToRemove.len > 0:
|
2023-04-11 08:12:54 +00:00
|
|
|
wf.subscriptions.removePeers(peersToRemove)
|
|
|
|
|
2024-01-16 16:27:40 +00:00
|
|
|
wf.subscriptions.cleanUp()
|
|
|
|
|
2023-04-11 08:12:54 +00:00
|
|
|
## Periodic report of number of subscriptions
|
2024-01-16 16:27:40 +00:00
|
|
|
waku_filter_subscriptions.set(wf.subscriptions.peersSubscribed.len.float64)
|
2023-03-20 11:19:53 +00:00
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
const MessagePushTimeout = 20.seconds
|
2023-03-20 11:19:53 +00:00
|
|
|
proc handleMessage*(wf: WakuFilter, pubsubTopic: PubsubTopic, message: WakuMessage) {.async.} =
|
|
|
|
trace "handling message", pubsubTopic=pubsubTopic, message=message
|
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
let handleMessageStartTime = Moment.now()
|
|
|
|
|
|
|
|
block:
|
|
|
|
## Find subscribers and push message to them
|
|
|
|
let subscribedPeers = wf.subscriptions.findSubscribedPeers(pubsubTopic, message.contentTopic)
|
2024-01-16 16:27:40 +00:00
|
|
|
if subscribedPeers.len == 0:
|
2023-03-22 08:32:53 +00:00
|
|
|
trace "no subscribed peers found", pubsubTopic=pubsubTopic, contentTopic=message.contentTopic
|
|
|
|
return
|
|
|
|
|
|
|
|
let messagePush = MessagePush(
|
|
|
|
pubsubTopic: pubsubTopic,
|
|
|
|
wakuMessage: message)
|
2023-03-20 11:19:53 +00:00
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
if not await wf.pushToPeers(subscribedPeers, messagePush).withTimeout(MessagePushTimeout):
|
2024-01-16 16:27:40 +00:00
|
|
|
debug "timed out pushing message to peers", pubsubTopic=pubsubTopic,
|
|
|
|
contentTopic=message.contentTopic,
|
|
|
|
hash=pubsubTopic.computeMessageHash(message).to0xHex()
|
2023-03-22 08:32:53 +00:00
|
|
|
waku_filter_errors.inc(labelValues = [pushTimeoutFailure])
|
2023-08-30 22:10:51 +00:00
|
|
|
else:
|
2024-01-16 16:27:40 +00:00
|
|
|
debug "pushed message succesfully to all subscribers",
|
|
|
|
pubsubTopic=pubsubTopic,
|
|
|
|
contentTopic=message.contentTopic,
|
|
|
|
hash=pubsubTopic.computeMessageHash(message).to0xHex()
|
2023-03-20 11:19:53 +00:00
|
|
|
|
2023-03-22 08:32:53 +00:00
|
|
|
let
|
|
|
|
handleMessageDuration = Moment.now() - handleMessageStartTime
|
|
|
|
handleMessageDurationSec = handleMessageDuration.milliseconds.float / 1000 # Duration in seconds with millisecond precision floating point
|
|
|
|
waku_filter_handle_message_duration_seconds.observe(handleMessageDurationSec)
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
proc initProtocolHandler(wf: WakuFilter) =
|
|
|
|
|
|
|
|
proc handler(conn: Connection, proto: string) {.async.} =
|
2023-04-11 08:12:54 +00:00
|
|
|
trace "filter subscribe request handler triggered", peerId=conn.peerId
|
|
|
|
|
2024-01-03 12:11:50 +00:00
|
|
|
let buf = await conn.readLp(int(MaxSubscribeSize))
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
let decodeRes = FilterSubscribeRequest.decode(buf)
|
|
|
|
if decodeRes.isErr():
|
2023-05-09 07:18:14 +00:00
|
|
|
error "Failed to decode filter subscribe request", peerId=conn.peerId, err=decodeRes.error
|
2023-03-02 15:23:30 +00:00
|
|
|
waku_filter_errors.inc(labelValues = [decodeRpcFailure])
|
|
|
|
return
|
|
|
|
|
|
|
|
let request = decodeRes.value #TODO: toAPI() split here
|
|
|
|
|
|
|
|
let response = wf.handleSubscribeRequest(conn.peerId, request)
|
|
|
|
|
2023-04-11 08:12:54 +00:00
|
|
|
debug "sending filter subscribe response", peerId=conn.peerId, response=response
|
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
await conn.writeLp(response.encode().buffer) #TODO: toRPC() separation here
|
|
|
|
return
|
|
|
|
|
|
|
|
wf.handler = handler
|
|
|
|
wf.codec = WakuFilterSubscribeCodec
|
|
|
|
|
|
|
|
proc new*(T: type WakuFilter,
|
2024-01-16 16:27:40 +00:00
|
|
|
peerManager: PeerManager,
|
|
|
|
subscriptionTimeout: Duration = DefaultSubscriptionTimeToLiveSec,
|
|
|
|
maxFilterPeers: uint32 = MaxFilterPeers,
|
|
|
|
maxFilterCriteriaPerPeer: uint32 = MaxFilterCriteriaPerPeer): T =
|
2023-03-02 15:23:30 +00:00
|
|
|
|
|
|
|
let wf = WakuFilter(
|
2024-01-16 16:27:40 +00:00
|
|
|
subscriptions: FilterSubscriptions.init(subscriptionTimeout,
|
|
|
|
maxFilterPeers,
|
|
|
|
maxFilterCriteriaPerPeer
|
|
|
|
),
|
2023-03-02 15:23:30 +00:00
|
|
|
peerManager: peerManager
|
|
|
|
)
|
2024-01-16 16:27:40 +00:00
|
|
|
|
2023-03-02 15:23:30 +00:00
|
|
|
wf.initProtocolHandler()
|
2024-01-16 16:27:40 +00:00
|
|
|
return wf
|
2023-03-20 11:19:53 +00:00
|
|
|
|
|
|
|
const MaintainSubscriptionsInterval* = 1.minutes
|
|
|
|
|
|
|
|
proc startMaintainingSubscriptions*(wf: WakuFilter, interval: Duration) =
|
|
|
|
trace "starting to maintain subscriptions"
|
2023-09-18 16:51:49 +00:00
|
|
|
var maintainSubs: CallbackFunc
|
|
|
|
maintainSubs = CallbackFunc(
|
|
|
|
proc(udata: pointer) {.gcsafe.} =
|
|
|
|
maintainSubscriptions(wf)
|
|
|
|
wf.maintenanceTask = setTimer(Moment.fromNow(interval), maintainSubs)
|
|
|
|
)
|
2023-03-20 11:19:53 +00:00
|
|
|
|
2023-04-11 08:12:54 +00:00
|
|
|
wf.maintenanceTask = setTimer(Moment.fromNow(interval), maintainSubs)
|
2023-03-20 11:19:53 +00:00
|
|
|
|
|
|
|
method start*(wf: WakuFilter) {.async.} =
|
|
|
|
debug "starting filter protocol"
|
|
|
|
wf.startMaintainingSubscriptions(MaintainSubscriptionsInterval)
|
|
|
|
|
|
|
|
await procCall LPProtocol(wf).start()
|
|
|
|
|
|
|
|
method stop*(wf: WakuFilter) {.async.} =
|
|
|
|
debug "stopping filter protocol"
|
2023-08-02 11:31:14 +00:00
|
|
|
if not wf.maintenanceTask.isNil():
|
|
|
|
wf.maintenanceTask.clearTimer()
|
2024-01-16 16:27:40 +00:00
|
|
|
|
2023-03-20 11:19:53 +00:00
|
|
|
await procCall LPProtocol(wf).stop()
|