Repository navigation
feat(service-disco): add discoverer #2306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
20bf048
150e172
e7c255f
14e449f
5df8d19
dd39963
a00e3ed
309c2e9
2d6dd67
423c403
fb9a9f2
a580dd0
fa6a3a3
b9ba880
d2eb3c7
81525ca
6700ef4
4e238c2
dfd941d
09bf42d
020f76b
de8380a
2e92486
1bd45da
3b3dcb2
7789b4c
0ae597f
5b6bfc6
c37e2d7
ef5c0de
025da11
ec6dbc9
a3ce5d6
1a0c6b9
17e220a
5c12571
30c58ac
8962f2b
b12ec17
1d66a04
ac5b09c
7e35075
65456aa
625ab8f
20b99a6
7854789
f497c2d
e494261
5476c74
2c9facc
e479534
44876d1
49f5fea
08afc7c
e788e4b
4656dac
e068796
2997f04
57243d7
3b26dbe
50415e3
b7ed4a7
1329f6a
c0e2f54
9a70757
061f286
a0823ba
12d83a8
6152f4e
f20a246
90466ba
dcd42d8
79551b5
c3209d8
a86ef56
be7cf81
83ba598
8b7af68
d1e3824
e217377
d077ad5
14c7c0f
779217d
5d0148b
2158743
a5b8d13
d731b1a
4baa2df
ca0c07a
97f3ca0
172c6f7
26d0e4e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 OR MIT | ||
| # Copyright (c) Status Research & Development GmbH | ||
|
|
||
| import std/sequtils | ||
| import chronos, chronicles, results | ||
| import ../../[peerid, switch, multiaddress, extended_peer_record] | ||
| import ../kademlia | ||
| import ../kademlia/types | ||
| import ./[types, routing_table_manager, service_discovery_metrics] | ||
|
|
||
| logScope: | ||
| topics = "service-disco discoverer" | ||
|
|
||
| type GetAdsResult = object | ||
| ads: seq[Advertisement] | ||
| closerPeers: seq[PeerId] | ||
|
|
||
| proc validAds(ads: seq[seq[byte]], serviceId: ServiceId): seq[Advertisement] = | ||
| var validAds: seq[Advertisement] = @[] | ||
| for adBuf in ads: | ||
| let ad = Advertisement.decode(adBuf).valueOr: | ||
| error "failed to decode advertisement", error | ||
| continue | ||
|
|
||
| if not ad.advertisesService(serviceId): | ||
| error "advert service mismatch", serviceId | ||
| continue | ||
|
|
||
| validAds.add(ad) | ||
| return validAds | ||
|
|
||
| proc dispatchGetAds( | ||
| disco: ServiceDiscovery, peerId: PeerId, serviceId: ServiceId, limit: int | ||
| ): Future[Opt[GetAdsResult]] {.async: (raises: [CancelledError]), gcsafe.} = | ||
| let addrs = disco.switch.peerStore[AddressBook][peerId] | ||
| if addrs.len == 0: | ||
| return Opt.none(GetAdsResult) | ||
|
|
||
| let connRes = catch: | ||
| await disco.switch.dial(peerId, addrs, disco.codec) | ||
| let conn = connRes.valueOr: | ||
| error "dialing peer failed", error = error.msg | ||
| return Opt.none(GetAdsResult) | ||
| defer: | ||
| await conn.close() | ||
|
|
||
| let msg = Message( | ||
| msgType: MessageType.getAds, | ||
| key: serviceId, | ||
| getAds: Opt.some(GetAdsMessage(limit: limit.uint32)), | ||
| ) | ||
| let encodedMsg = msg.encode().buffer | ||
|
|
||
| cd_messages_sent.inc(labelValues = [$MessageType.getAds]) | ||
| cd_message_bytes_sent.inc(encodedMsg.len.float64, labelValues = [$MessageType.getAds]) | ||
|
|
||
| var writeRes: Result[void, ref CatchableError] | ||
| var readRes: Result[seq[byte], ref CatchableError] | ||
| cd_message_duration_ms.time(labelValues = [$MessageType.getAds]): | ||
| writeRes = catch: | ||
| await conn.writeLp(encodedMsg) | ||
|
|
||
| if writeRes.isErr: | ||
| error "connection writing failed", error = writeRes.error.msg | ||
| return Opt.none(GetAdsResult) | ||
|
|
||
| cd_message_duration_ms.time(labelValues = [$MessageType.getAds]): | ||
| readRes = catch: | ||
| await conn.readLp(MaxMsgSize) | ||
| let replyBuf = readRes.valueOr: | ||
| error "connection reading failed", error = readRes.error.msg | ||
| return Opt.none(GetAdsResult) | ||
|
|
||
| cd_messages_received.inc(labelValues = [$MessageType.getAds]) | ||
| cd_message_bytes_received.inc( | ||
| replyBuf.len.float64, labelValues = [$MessageType.getAds] | ||
| ) | ||
|
|
||
| let reply = Message.decode(replyBuf).valueOr: | ||
| error "failed to decode message response", error = $error | ||
| return Opt.none(GetAdsResult) | ||
|
|
||
| let getAdsMsg = reply.getAds.valueOr: | ||
| error "get ads message response not found" | ||
| return Opt.none(GetAdsResult) | ||
|
|
||
| var closerPeerInfos: seq[PeerInfo] | ||
| for peer in reply.closerPeers: | ||
| let pid = PeerId.init(peer.id).valueOr: | ||
| continue | ||
| closerPeerInfos.add(PeerInfo(peerId: pid, addrs: peer.addrs)) | ||
| disco.updatePeers(closerPeerInfos) | ||
|
|
||
| return Opt.some( | ||
| GetAdsResult( | ||
| ads: getAdsMsg.advertisements.validAds(serviceId), | ||
| closerPeers: closerPeerInfos.mapIt(it.peerId), | ||
| ) | ||
| ) | ||
|
|
||
| proc peersToQuery(disco: ServiceDiscovery, bucket: Bucket): seq[PeerId] = | ||
| let peersToPick = min(disco.discoConfig.kLookup, bucket.peers.len) | ||
| disco.rng.pick(bucket.peers, peersToPick).withValue(picked): | ||
| return picked.toPeerIds() | ||
| else: | ||
| return @[] | ||
|
|
||
| proc insertCloserPeers( | ||
| disco: ServiceDiscovery, serviceId: ServiceId, peers: seq[PeerId] | ||
| ) = | ||
| for nodeId in peers: | ||
| disco.rtManager.insertPeer(serviceId, nodeId.toKey()) | ||
|
|
||
| proc processResponse( | ||
| disco: ServiceDiscovery, | ||
| serviceId: ServiceId, | ||
| response: GetAdsResult, | ||
| found: var seq[Advertisement], | ||
| limit: int, | ||
| ) = | ||
| disco.insertCloserPeers(serviceId, response.closerPeers) | ||
| let remaining = limit - found.len | ||
| if remaining > 0: | ||
| found.add(response.ads[0 ..< min(remaining, response.ads.len)]) | ||
|
|
||
| proc drainCompletedPeers( | ||
| disco: ServiceDiscovery, | ||
| serviceId: ServiceId, | ||
| pending: seq[Future[Opt[GetAdsResult]]], | ||
| ) = | ||
| for fut in pending.filterIt(it.completed()): | ||
| fut.value().withValue(response): | ||
| disco.insertCloserPeers(serviceId, response.closerPeers) | ||
|
|
||
| proc collectBucketAds( | ||
| disco: ServiceDiscovery, serviceId: ServiceId, peers: seq[PeerId], limit: int | ||
| ): Future[seq[Advertisement]] {.async: (raises: [CancelledError]).} = | ||
| var found = newSeqOfCap[Advertisement](limit) | ||
| var pending: seq[Future[Opt[GetAdsResult]]] = | ||
| peers.mapIt(Future[Opt[GetAdsResult]](dispatchGetAds(disco, it, serviceId, limit))) | ||
| defer: | ||
| for fut in pending: | ||
| if not fut.finished(): | ||
| fut.cancelSoon() | ||
|
|
||
|
gmelodie marked this conversation as resolved.
Resolved
|
||
| let deadline = Moment.fromNow(disco.config.timeout) | ||
| for _ in 0 ..< pending.len: | ||
| let timeLeft = deadline - Moment.now() | ||
| if timeLeft <= ZeroDuration: | ||
| break | ||
|
|
||
| let wrapper = one(pending) | ||
| if not (await wrapper.withTimeout(timeLeft)): | ||
| break | ||
|
|
||
| let completedFut = wrapper.value() | ||
| pending.del(pending.find(completedFut)) | ||
|
|
||
| if completedFut.completed(): | ||
| completedFut.value().withValue(response): | ||
| disco.processResponse(serviceId, response, found, limit) | ||
|
|
||
| if found.len >= limit: | ||
| disco.drainCompletedPeers(serviceId, pending) | ||
|
gmelodie marked this conversation as resolved.
Resolved
|
||
| break | ||
|
|
||
| return found | ||
|
|
||
| proc lookup*( | ||
| disco: ServiceDiscovery, serviceId: ServiceId | ||
| ): Future[Result[seq[Advertisement], string]] {.async: (raises: [CancelledError]).} = | ||
| ## Look up providers for a specific service id. | ||
| cd_lookup_requests.inc() | ||
|
|
||
| discard disco.rtManager.addService( | ||
| serviceId, disco.rtable, disco.config.replication, disco.discoConfig.bucketsCount, | ||
| Interest, | ||
| ) | ||
|
|
||
| let searchTable = disco.rtManager.getTable(serviceId).valueOr: | ||
| return err("service table not found for service id: " & $serviceId) | ||
|
|
||
| var found = newSeqOfCap[Advertisement](disco.discoConfig.fLookup) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. still, should be doable. but talking out from top of my head 1) not sure how this will work in nim 2) not sure how these would stack if there is really senergy or not |
||
|
|
||
| for bucket in searchTable.buckets: | ||
| if found.len >= disco.discoConfig.fLookup: | ||
| break | ||
|
|
||
| if bucket.peers.len == 0: | ||
| continue | ||
|
|
||
| let remaining = disco.discoConfig.fLookup - found.len | ||
| found.add( | ||
| await disco.collectBucketAds(serviceId, disco.peersToQuery(bucket), remaining) | ||
| ) | ||
|
|
||
| cd_lookup_peers_found.inc(found.len.int64) | ||
| return ok(found) | ||
Uh oh!
There was an error while loading. Please reload this page.