123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2023 Nomadic Labs, <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)moduleSliding_message_id_map(C:Gossipsub_intf.AUTOMATON_SUBCONFIG):sig(** A data structure containing a mapping from message ids to values of type
['a]. Message ids are grouped by topic and by slot (which is a just an
integer). The grouping by slots is used to remove entries from old slots,
thus it allows to use this data structure as a sliding window. *)type'at(** [make ~window_size] creates an empty map with window size [window_size].
This means that the values will be removed from the map after [window_size] shifts. *)valmake:window_size:int->'at(** [add topic message_id ~update_value t] adds an entry to the map for [message_id] with [topic].
[update_value] is used to update the value stored for [message_id]. *)valadd:C.Topic.t->C.Message_id.t->update_value:('aoption->'aoption)->'at->'at(** [update_value message_id f t] updates the value stored for key [message_id]
by applying [f] to the stored value. Returns [None] if no value was stored
for the [message_id], and otherwise returns [Some (t, value)] where [t] is the new map
and [value] is the updated value. *)valupdate_value:C.Message_id.t->('a->'a)->'at->('at*'a)option(** [get_value message_id t] returns the value stored for key [message_id].
Returns [None] if nothing is stored. *)valget_value:C.Message_id.t->'at->'aoption(** [get_message_ids ~slots t] returns the [topic] to [message list] mapping
for the past [slots] slots. *)valget_latest_message_ids:slots:int->'at->(Int64.t*C.Message_id.tlistC.Topic.Map.t)Seq.t(** Shifts the sliding window by one slot. *)valshift:'at->'atmoduleIntrospection:sigmoduleMap:Map.Swithtypekey=Int64.tvalget_slot_entries:'at->C.Message_id.tlistC.Topic.Map.tMap.tendmoduleInternal_for_tests:sigvalget_values:'at->(C.Message_id.t*'a)Seq.tendend=structmoduleTopic=C.TopicmoduleMessage_id=C.Message_id(* TODO: https://gitlab.com/tezos/tezos/-/issues/5536
Transform the list into a set? *)typeslot_entry=Message_id.tlistTopic.Map.t(* A slot is just an index, normally a heartbeat tick, and this is why the
same type, namely [Int64], is used. Note that a bigger slot is a more
recent slot. *)moduleMap=Map.Make(Int64)type'avalue_with_counter={value:'a;store_counter:int;(* This field is used to count how many times the message has been added to
the map. Normally the caller ensures that the same messages (that is,
with the same id) is not inserted twice; however, this module does not make
this assumption. *)(* TODO: https://gitlab.com/tezos/tezos/-/issues/5536
Make the above assumption and remove this field? *)}type'at={values_with_counter:'avalue_with_counterMessage_id.Map.t;slot_entries:slot_entryMap.t;(** The slot entries without the entry for the last slot, which is stored
separately, see next field. *)latest_slot_entry:slot_entry;latest_slot:Int64.t;window_size:int;}letmake~window_size={values_with_counter=Message_id.Map.empty;slot_entries=Map.empty;latest_slot_entry=Topic.Map.empty;latest_slot=0L;window_size;}letaddtopicmessage_id~update_valuet=letlatest_slot_entry=Topic.Map.updatetopic(function|None->Some[message_id]|Somemessage_ids->Some(message_id::message_ids))t.latest_slot_entryinletvalues_with_counter=Message_id.Map.updatemessage_id(function|None->update_valueNone|>Option.map(funvalue->{value;store_counter=1})|Some{value;store_counter}->update_value(Somevalue)|>Option.map(funvalue->{value;store_counter=store_counter+1}))t.values_with_counterin{twithlatest_slot_entry;values_with_counter}letupdate_valuemessage_idft=letupdated_value=refNoneinletvalues_with_counter=Message_id.Map.updatemessage_id(function|None->None|Some{value;store_counter}->letvalue=fvalueinupdated_value:=Somevalue;Some{value;store_counter})t.values_with_counterin!updated_value|>Option.map(funvalue->({twithvalues_with_counter},value))letget_valuemessage_idt=Message_id.Map.findmessage_idt.values_with_counter|>Option.map(fun{value;_}->value)letget_latest_message_ids~slotst=letslots=Map.to_rev_seqt.slot_entries|>Seq.take~when_negative_length:()(slots-1)|>WithExceptions.Result.get_ok~loc:__LOC__inSeq.cons(t.latest_slot,t.latest_slot_entry)slotsletshiftt=letdrop_old_valuesoldest_entries=Topic.Map.fold(fun_topicmessage_idsmessages->List.fold_left(funmessagesmessage_id->Message_id.Map.updatemessage_id(function|None->None|Some{value;store_counter}->ifstore_counter=1thenNoneelseSome{value;store_counter=store_counter-1})messages)messagesmessage_ids)oldest_entriest.values_with_counterinletslot_entries=Map.addt.latest_slott.latest_slot_entryt.slot_entriesinletlatest_slot=Int64.succt.latest_slotinletlatest_slot_entry=Topic.Map.emptyinmatchMap.min_bindingslot_entrieswith|None->{twithslot_entries;latest_slot;latest_slot_entry}|Some(first_slot,entry)->ifInt64.(sublatest_slotfirst_slot<of_intt.window_size)then{slot_entries;latest_slot;latest_slot_entry;values_with_counter=t.values_with_counter;window_size=t.window_size;}else{slot_entries=Map.removefirst_slotslot_entries;latest_slot_entry;latest_slot;values_with_counter=drop_old_valuesentry;window_size=t.window_size;}moduleIntrospection=structmoduleMap=Mapletget_slot_entriest=t.slot_entriesendmoduleInternal_for_tests=structletget_valuest=t.values_with_counter|>Message_id.Map.to_seq|>Seq.map(fun(message_id,{value;store_counter=_})->(message_id,value))endendmoduleMake(C:Gossipsub_intf.AUTOMATON_SUBCONFIG)(Time:Gossipsub_intf.TIME):Gossipsub_intf.MESSAGE_CACHEwithmodulePeer=C.PeerandmoduleTopic=C.TopicandmoduleMessage_id=C.Message_idandmoduleMessage=C.MessageandmoduleTime=Time=structmodulePeer=C.PeermoduleTopic=C.TopicmoduleMessage_id=C.Message_idmoduleMessage=C.MessagemoduleTime=TimemoduleSliding_message_id_map=Sliding_message_id_map(C)typemessage_with_access_counter={message:Message.t;access_counters:intPeer.Map.t;}typet={gossip_slots:int;messages:message_with_access_counterSliding_message_id_map.t;first_seen_times:Time.tSliding_message_id_map.t;}letcreate~history_slots~gossip_slots~seen_message_slots=assert(gossip_slots>0);assert(gossip_slots<=history_slots);assert(seen_message_slots>0);{gossip_slots;messages=Sliding_message_id_map.make~window_size:history_slots;first_seen_times=Sliding_message_id_map.make~window_size:seen_message_slots;}letadd_messagemessage_idmessagetopict=letmessages=Sliding_message_id_map.addtopicmessage_id~update_value:(function|None->Some{message;access_counters=Peer.Map.empty}|Somem->Somem)t.messagesinletfirst_seen_times=Sliding_message_id_map.addtopicmessage_id~update_value:(function|None->Some(Time.now())|Sometime->Sometime)t.first_seen_timesin{twithmessages;first_seen_times}letget_message_for_peerpeermessage_idt=letaccess_count=ref0inletupdate_result=Sliding_message_id_map.update_valuemessage_id(fun{message;access_counters}->letaccess_counters=Peer.Map.updatepeer(function|None->access_count:=1;Some!access_count|Somec->access_count:=c+1;Some!access_count)access_countersin{message;access_counters})t.messagesinupdate_result|>Option.map(fun(messages,{message;access_counters=_})->({twithmessages},message,!access_count))letget_message_ids_to_gossiptopict=Sliding_message_id_map.get_latest_message_ids~slots:t.gossip_slotst.messages|>Seq.fold_left(funacc_message_ids(_slot,entries)->matchTopic.Map.findtopicentrieswith|None->acc_message_ids|Somemessage_ids->List.rev_appendmessage_idsacc_message_ids)[]letget_first_seen_timemessage_idt=Sliding_message_id_map.get_valuemessage_idt.first_seen_timesletseen_messagemessage_idt=Option.is_some@@Sliding_message_id_map.get_valuemessage_idt.first_seen_timesletshiftt={twithmessages=Sliding_message_id_map.shiftt.messages;first_seen_times=Sliding_message_id_map.shiftt.first_seen_times;}moduleIntrospection=structmoduleMap=Sliding_message_id_map.Introspection.Mapletget_message_idst=Sliding_message_id_map.Introspection.get_slot_entriest.messagesendmoduleInternal_for_tests=structletget_access_counterst=Sliding_message_id_map.Internal_for_tests.get_valuest.messages|>Seq.map(fun(message_id,{access_counters;_})->(message_id,access_counters))endend