text
stringlengths 0
601k
|
---|
let find_loop_heads ( module Cfg : CfgForward ) ( file : Cil . file ) : unit NH . t = let loop_heads = NH . create 100 in let global_visited_nodes = NH . create 100 in let rec iter_node path_visited_nodes node = if NS . mem node path_visited_nodes then NH . replace loop_heads node ( ) else if not ( NH . mem global_visited_nodes node ) then begin NH . replace global_visited_nodes node ( ) ; let new_path_visited_nodes = NS . add node path_visited_nodes in List . iter ( fun ( _ , to_node ) -> iter_node new_path_visited_nodes to_node ) ( Cfg . next node ) end in Cil . iterGlobals file ( function | GFun ( fd , _ ) -> let entry_node = FunctionEntry fd in iter_node NS . empty entry_node | _ -> ( ) ) ; loop_heads |
module type File = sig val file : Cil . file end |
module Invariant ( File : File ) ( Cfg : MyCFG . CfgBidir ) = struct let emit_loop_head = GobConfig . get_bool " witness . invariant . loop - head " let emit_after_lock = GobConfig . get_bool " witness . invariant . after - lock " let emit_other = GobConfig . get_bool " witness . invariant . other " let loop_heads = find_loop_heads ( module Cfg ) File . file let is_after_lock to_node = List . exists ( fun ( edges , from_node ) -> List . exists ( fun ( _ , edge ) -> match edge with | Proc ( _ , Lval ( Var fv , NoOffset ) , args ) -> begin match LibraryFunctions . classify fv . vname args with | ` Lock _ -> true | _ -> false end | _ -> false ) edges ) ( Cfg . prev to_node ) let is_invariant_node cfgnode = if NH . mem loop_heads cfgnode then emit_loop_head else if is_after_lock cfgnode then emit_after_lock else emit_other end |
module InvariantExp = struct module ES = SetDomain . Make ( CilType . Exp ) let rec pullOutCommonConjuncts e = let rec to_conjunct_set = function | Cil . BinOp ( LAnd , e1 , e2 , _ ) -> ES . join ( to_conjunct_set e1 ) ( to_conjunct_set e2 ) | e -> ES . singleton e in let combine_conjuncts es = ES . fold ( fun e acc -> match acc with | None -> Some e | Some acce -> Some ( BinOp ( LAnd , acce , e , Cil . intType ) ) ) es None in match e with | Cil . BinOp ( LOr , e1 , e2 , t ) -> let e1s = pullOutCommonConjuncts e1 in let e2s = pullOutCommonConjuncts e2 in let common = ES . inter e1s e2s in let e1s ' = ES . diff e1s e2s in let e2s ' = ES . diff e2s e1s in ( match combine_conjuncts e1s ' , combine_conjuncts e2s ' with | Some e1e , Some e2e -> ES . add ( BinOp ( LOr , e1e , e2e , Cil . intType ) ) common | _ -> common ) | e -> to_conjunct_set e let process_exp inv = let inv ' = InvariantCil . exp_replace_original_name inv in if GobConfig . get_bool " witness . invariant . split - conjunction " then ES . elements ( pullOutCommonConjuncts inv ' ) else [ inv ' ] end |
type parsing_sate = Initial | EntRef of int ; ; |
let internal_break_words b t = |
let is_whitespace = function | ' ' | ' \ t ' | ' \ n ' | ' \ r ' -> true | _ -> false |
let words_of_string s = let len = String . length s in let finish acc = List . rev acc in let rec iter acc = function | ` Skip next_ofs when next_ofs >= len -> finish acc | ` Skip next_ofs -> if is_whitespace s . [ next_ofs ] then iter acc ( ` Skip ( next_ofs + 1 ) ) else iter acc ( ` Collect ( next_ofs , next_ofs + 1 ) ) | ` Collect ( start_ofs , next_ofs ) when next_ofs >= len -> finish ( ( String . sub s start_ofs ( next_ofs - start_ofs ) ) :: acc ) | ` Collect ( start_ofs , next_ofs ) -> if is_whitespace s . [ next_ofs ] then iter ( String . sub s start_ofs ( next_ofs - start_ofs ) :: acc ) ( ` Skip ( next_ofs + 1 ) ) else iter acc ( ` Collect ( start_ofs , ( next_ofs + 1 ) ) ) in iter [ ] ( ` Skip 0 ) |
type t = { count : int ref ; dict : ( string , int ) Hashtbl . t ; outputs : ( Pipeline . label , Bi_outbuf . t ) Hashtbl . t ; } |
let task_init _ = { count = ref 0 ; dict = ( Hashtbl . create ( 1024 * 1024 ) : ( string , int ) Hashtbl . t ) ; outputs = ( Hashtbl . create mAX_LABEL : ( Pipeline . label , Bi_outbuf . t ) Hashtbl . t ) ; } |
let label_of disco word = if disco . Task . grouping = Pipeline . Group_all then 0 else let h = ref 0 in String . iter ( fun c -> h := ! h + Char . code c ) word ; ! h mod mAX_LABEL |
let output_of init disco label = try Hashtbl . find init . outputs label with Not_found -> let o = Bi_outbuf . create_channel_writer ( disco . Task . out_channel ~ label ) in Hashtbl . add init . outputs label o ; o |
let task_done init disco = Hashtbl . iter ( fun k v -> Wc_b . write_wc ( output_of init disco ( label_of disco k ) ) ( k , v ) ; ) init . dict ; Hashtbl . iter ( fun _l o -> Bi_outbuf . flush_channel_writer o ) init . outputs ; disco . Task . log ( Printf . sprintf " Output % d entries ( % d keys ) into % d files . \ n " ( ! init . count ) ( Hashtbl . length init . dict ) ( Hashtbl . length init . outputs ) ) |
module MapTask = struct module T = Task type init = t let task_init = task_init let task_process init disco in_chan = disco . T . log ( Printf . sprintf " Processing % s ( % d bytes ) with label % d on % s . . . \ n " disco . T . input_url disco . T . input_size disco . T . group_label disco . T . hostname ) ; let rec loop ( ) = List . iter ( fun key -> let v = try Hashtbl . find init . dict key with Not_found -> 0 in Hashtbl . replace init . dict key ( v + 1 ) ; incr init . count ) ( words_of_string ( input_line in_chan ) ) ; loop ( ) in try loop ( ) with End_of_file -> ( ) let task_done = task_done end |
module ReduceTask = struct module T = Task type init = t let task_init = task_init let task_process init disco in_chan = disco . T . log ( Printf . sprintf " Processing % s ( % d bytes ) with label % d on % s . . . \ n " disco . T . input_url disco . T . input_size disco . T . group_label disco . T . hostname ) ; let inp = Bi_inbuf . from_channel in_chan in let rec loop ( ) = let ( k , v ) = Wc_b . read_wc inp in let cnt = try Hashtbl . find init . dict k with Not_found -> 0 in Hashtbl . replace init . dict k ( v + cnt ) ; incr init . count ; loop ( ) in try loop ( ) with End_of_file | Bi_inbuf . End_of_input -> ( ) let task_done = task_done end |
let _ = Worker . start [ ( mAP , ( module MapTask : Task . TASK ) ) ; ( sHUFFLE , ( module ReduceTask : Task . TASK ) ) ; ( rEDUCE , ( module ReduceTask : Task . TASK ) ) ] |
module Single = struct module Spec = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type ( ' witness , ' ledger_proof ) ' ledger_proof t = | Transition of Transaction_snark . Statement . Stable . V2 . t * ' witness | Merge of Transaction_snark . Statement . Stable . V2 . t * ' ledger_proof * ' ledger_proof [ @@ deriving sexp , to_yojson ] to_yojson end end ] end type ( ' witness , ' ledger_proof ) ' ledger_proof t = ( ' witness , ' ledger_proof ) ' ledger_proof Stable . Latest . t = | Transition of Transaction_snark . Statement . t * ' witness | Merge of Transaction_snark . Statement . t * ' ledger_proof * ' ledger_proof [ @@ deriving sexp , to_yojson ] to_yojson let statement = function Transition ( s , _ ) _ -> s | Merge ( s , _ , _ ) _ -> s let gen : ' witness Quickcheck . Generator . t -> ' ledger_proof Quickcheck . Generator . t -> ( ' witness , ' ledger_proof ) ' ledger_proof t Quickcheck . Generator . t = fun gen_witness gen_proof -> let open Quickcheck . Generator in let gen_transition = let open Let_syntax in let % bind statement = Transaction_snark . Statement . gen in let % map witness = gen_witness in Transition ( statement , witness ) witness in let gen_merge = let open Let_syntax in let % bind statement = Transaction_snark . Statement . gen in let % map p1 , p2 = tuple2 gen_proof gen_proof in Merge ( statement , p1 , p2 ) p2 in union [ gen_transition ; gen_merge ] end end |
module Spec = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V1 = struct type ' single t = { instances : ' single One_or_two . Stable . V1 . t ; fee : Currency . Fee . Stable . V1 . t } [ @@ deriving fields , sexp , to_yojson ] to_yojson let to_latest single_latest { instances ; fee } = { instances = One_or_two . Stable . V1 . to_latest single_latest instances ; fee } let of_latest single_latest { instances ; fee } = let open Result . Let_syntax in let % map instances = One_or_two . Stable . V1 . of_latest single_latest instances in { instances ; fee } end end ] end type ' single t = ' single Stable . Latest . t = { instances : ' single One_or_two . t ; fee : Currency . Fee . t } [ @@ deriving fields , sexp , to_yojson ] to_yojson end |
module Result = struct [ %% versioned module Stable = struct module V1 = struct type ( ' spec , ' single ) ' single t = { proofs : ' single One_or_two . Stable . V1 . t ; metrics : ( Core . Time . Stable . Span . V1 . t * [ ` Transition | ` Merge ] ) One_or_two . Stable . V1 . t ; spec : ' spec ; prover : Signature_lib . Public_key . Compressed . Stable . V1 . t } [ @@ deriving fields ] fields end end ] end end |
module Book_view = struct module Visibility = struct type t = | Hidden | Very_hidden | Visible [ @@ deriving sexp_of ] let of_string = function | " hidden " -> Hidden | " veryHidden " -> Very_hidden | " visible " -> Visible | str -> failwithf " Expected ST_Visibility but got ' % s ' " str ( ) end type t = { active_tab : uint32 ; autofilter_date_grouping : bool ; first_sheet : uint32 ; minimized : bool ; show_horizontal_scroll : bool ; show_vertical_scroll : bool ; tab_ratio : uint32 ; visibility : Visibility . t ; window_height : uint32 option ; window_width : uint32 option ; x_window : int32 option ; y_window : int32 option } [ @@ deriving fields , sexp_of ] let default = { active_tab = Uint32 . zero ; autofilter_date_grouping = true ; first_sheet = Uint32 . zero ; minimized = false ; show_horizontal_scroll = true ; show_vertical_scroll = true ; tab_ratio = Uint32 . of_int 600 ; visibility = Visibility . Visible ; window_height = None ; window_width = None ; x_window = None ; y_window = None } let of_xml = function | Xml . Element ( " bookView " , attrs , _ ) -> List . fold attrs ~ init : default ~ f ( : fun t -> function | " activeTab " , v -> { t with active_tab = Uint32 . of_string v } | " autoFilterDateGrouping " , v -> { t with autofilter_date_grouping = bool_of_xsd_boolean v } | " firstSheet " , v -> { t with first_sheet = Uint32 . of_string v } | " minimized " , v -> { t with minimized = bool_of_xsd_boolean v } | " showHorizontalScroll " , v -> { t with show_horizontal_scroll = bool_of_xsd_boolean v } | " showVerticalScroll " , v -> { t with show_vertical_scroll = bool_of_xsd_boolean v } | " tabRatio " , v -> { t with tab_ratio = Uint32 . of_string v } | " visibility " , v -> { t with visibility = Visibility . of_string v } | " windowHeight " , v -> { t with window_height = Some ( Uint32 . of_string v ) } | " windowWidth " , v -> { t with window_width = Some ( Uint32 . of_string v ) } | " xWindow " , v -> { t with x_window = Some ( Int32 . of_string v ) } | " yWindow " , v -> { t with y_window = Some ( Int32 . of_string v ) } | _ -> t ) |> Option . some | _ -> None end |
module Sheet = struct module State = struct type t = | Hidden | Very_hidden | Visible [ @@ deriving sexp_of ] let of_string = function | " hidden " -> Hidden | " veryHidden " -> Very_hidden | " visible " -> Visible | str -> failwithf " Expected ST_SheetState but got ' % s ' " str ( ) end type t = { id : string ; name : string ; sheet_id : uint32 ; state : State . t } [ @@ deriving fields , sexp_of ] let of_xml = function | Xml . Element ( " sheet " , attrs , _ ) -> let name = ref None in let sheet_id = ref None in let state = ref State . Visible in let id = ref None in List . iter attrs ~ f ( : function | " name " , v -> name := Some v | " sheetId " , v -> sheet_id := Some ( Uint32 . of_string v ) | " state " , v -> state := State . of_string v | " r : id " , v -> id := Some v | _ -> ( ) ) ; let name = require_attribute " sheet " " name " ! name in let sheet_id = require_attribute " sheet " " sheetId " ! sheet_id in let id = require_attribute " sheet " " r : id " ! id in Some { name ; sheet_id ; state = ! state ; id } | _ -> None end |
type t = { book_views : Book_view . t list ; sheets : Sheet . t list } [ @@ deriving fields , sexp_of ] |
let empty = { book_views = [ ] ; sheets = [ ] } |
let of_xml = expect_element " workbook " ( fun _ -> List . fold ~ init : empty ~ f ( : fun t -> let open Xml in function | Element ( " bookViews " , _ , children ) -> let book_views = List . filter_map children ~ f : Book_view . of_xml in { t with book_views } | Element ( " sheets " , _ , children ) -> let sheets = List . filter_map children ~ f : Sheet . of_xml in { t with sheets } | _ -> t ) ) |
type worker_name = { base : string ; name : string } |
type Error_monad . error += Closed of worker_name |
let ( ) = register_error_kind ` Permanent ~ id " : worker . closed " ~ title " : Worker closed " ~ description : " An operation on a worker could not complete before it was shut down . " ~ pp ( : fun ppf w -> Format . fprintf ppf " Worker % s [ % s ] has been shut down . " w . base w . name ) Data_encoding . ( conv ( fun { base ; name } -> ( base , name ) ) ( fun ( name , base ) -> { base ; name } ) ( obj1 ( req " worker " ( tup2 string string ) ) ) ) ( function Closed w -> Some w | _ -> None ) ( fun w -> Closed w ) |
module type T = sig module Name : Worker_intf . NAME module Event : Worker_intf . EVENT module Request : Worker_intf . REQUEST module Types : Worker_intf . TYPES type ' kind t type ' kind table type ' a queue and bounded and infinite type dropbox type _ buffer_kind = | Queue : infinite queue buffer_kind | Bounded : { size : int } -> bounded queue buffer_kind | Dropbox : { merge : dropbox t -> any_request -> any_request option -> any_request option ; } -> dropbox buffer_kind and any_request = Any_request : _ Request . t -> any_request val create_table : ' kind buffer_kind -> ' kind table module type HANDLERS = sig type self val on_launch : self -> Name . t -> Types . parameters -> Types . state tzresult Lwt . t val on_request : self -> ' a Request . t -> ' a tzresult Lwt . t val on_no_request : self -> unit tzresult Lwt . t val on_close : self -> unit Lwt . t val on_error : self -> Request . view -> Worker_types . request_status -> error list -> unit tzresult Lwt . t val on_completion : self -> ' a Request . t -> ' a -> Worker_types . request_status -> unit Lwt . t end val launch : ' kind table -> ? timeout : Time . System . Span . t -> Name . t -> Types . parameters -> ( module HANDLERS with type self = ' kind t ) -> ' kind t tzresult Lwt . t val shutdown : _ t -> unit Lwt . t module type BOX = sig type t val put_request : t -> ' a Request . t -> unit val put_request_and_wait : t -> ' a Request . t -> ' a tzresult Lwt . t end module type QUEUE = sig type ' a t val push_request_and_wait : ' q t -> ' a Request . t -> ' a tzresult Lwt . t val push_request : ' q t -> ' a Request . t -> unit Lwt . t val pending_requests : ' a t -> ( Time . System . t * Request . view ) list val pending_requests_length : ' a t -> int end module Dropbox : sig include BOX with type t := dropbox t end module Queue : sig include QUEUE with type ' a t := ' a queue t val push_request_now : infinite queue t -> ' a Request . t -> unit end val protect : _ t -> ? on_error ( : error list -> ' b tzresult Lwt . t ) -> ( unit -> ' b tzresult Lwt . t ) -> ' b tzresult Lwt . t val canceler : _ t -> Lwt_canceler . t val trigger_shutdown : _ t -> unit val record_event : _ t -> Event . t -> unit val log_event : _ t -> Event . t -> unit Lwt . t val state : _ t -> Types . state val pending_requests : _ queue t -> ( Time . System . t * Request . view ) list val status : _ t -> Worker_types . worker_status val current_request : _ t -> ( Time . System . t * Time . System . t * Request . view ) option val information : _ t -> Worker_types . worker_information val list : ' a table -> ( Name . t * ' a t ) list val find_opt : ' a table -> Name . t -> ' a t option end |
module Make ( Name : Worker_intf . NAME ) ( Event : Worker_intf . EVENT ) ( Request : Worker_intf . REQUEST ) ( Types : Worker_intf . TYPES ) ( Logger : Worker_intf . LOGGER with module Event = Event and type Request . view = Request . view ) = struct module Name = Name module Event = Event module Request = Request module Types = Types module Logger = Logger module Nametbl = Hashtbl . MakeSeeded ( struct type t = Name . t let hash = Hashtbl . seeded_hash let equal = Name . equal end ) let base_name = String . concat " " - Name . base type message = Message : ' a Request . t * ' a tzresult Lwt . u option -> message type ' a queue and bounded and infinite type dropbox type _ buffer_kind = | Queue : infinite queue buffer_kind | Bounded : { size : int } -> bounded queue buffer_kind | Dropbox : { merge : dropbox t -> any_request -> any_request option -> any_request option ; } -> dropbox buffer_kind and any_request = Any_request : _ Request . t -> any_request and _ buffer = | Queue_buffer : ( Time . System . t * message ) Lwt_pipe . Unbounded . t -> infinite queue buffer | Bounded_buffer : ( Time . System . t * message ) Lwt_pipe . Bounded . t -> bounded queue buffer | Dropbox_buffer : ( Time . System . t * message ) Lwt_dropbox . t -> dropbox buffer and ' kind t = { timeout : Time . System . Span . t option ; parameters : Types . parameters ; mutable worker : unit Lwt . t ; mutable state : Types . state option ; buffer : ' kind buffer ; canceler : Lwt_canceler . t ; name : Name . t ; id : int ; mutable status : Worker_types . worker_status ; mutable current_request : ( Time . System . t * Time . System . t * Request . view ) option ; logEvent : ( module Internal_event . EVENT with type t = Logger . t ) ; table : ' kind table ; } and ' kind table = { buffer_kind : ' kind buffer_kind ; mutable last_id : int ; instances : ' kind t Nametbl . t ; } let queue_item ? u r = ( Systime_os . now ( ) , Message ( r , u ) ) let drop_request w merge message_box request = try match match Lwt_dropbox . peek message_box with | None -> merge w ( Any_request request ) None | Some ( _ , Message ( old , _ ) ) -> Lwt . ignore_result ( Lwt_dropbox . take message_box ) ; merge w ( Any_request request ) ( Some ( Any_request old ) ) with | None -> ( ) | Some ( Any_request neu ) -> Lwt_dropbox . put message_box ( Systime_os . now ( ) , Message ( neu , None ) ) with Lwt_dropbox . Closed -> ( ) let drop_request_and_wait w message_box request = let ( t , u ) = Lwt . wait ( ) in Lwt . catch ( fun ( ) -> Lwt_dropbox . put message_box ( queue_item ~ u request ) ; t ) ( function | Lwt_dropbox . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) | exn -> raise exn ) module type BOX = sig type t val put_request : t -> ' a Request . t -> unit val put_request_and_wait : t -> ' a Request . t -> ' a tzresult Lwt . t end module type QUEUE = sig type ' a t val push_request_and_wait : ' q t -> ' a Request . t -> ' a tzresult Lwt . t val push_request : ' q t -> ' a Request . t -> unit Lwt . t val pending_requests : ' a t -> ( Time . System . t * Request . view ) list val pending_requests_length : ' a t -> int end module Dropbox = struct let put_request ( w : dropbox t ) request = let ( Dropbox { merge } ) = w . table . buffer_kind in let ( Dropbox_buffer message_box ) = w . buffer in drop_request w merge message_box request let put_request_and_wait ( w : dropbox t ) request = let ( Dropbox_buffer message_box ) = w . buffer in drop_request_and_wait w message_box request end module Queue = struct let push_request ( type a ) ( w : a queue t ) request = match w . buffer with | Queue_buffer message_queue -> Lwt_pipe . Unbounded . push message_queue ( queue_item request ) ; Lwt . return_unit | Bounded_buffer message_queue -> Lwt_pipe . Bounded . push message_queue ( queue_item request ) let push_request_now ( w : infinite queue t ) request = let ( Queue_buffer message_queue ) = w . buffer in if Lwt_pipe . Unbounded . is_closed message_queue then ( ) else Lwt_pipe . Unbounded . push message_queue ( queue_item request ) let push_request_and_wait ( type a ) ( w : a queue t ) request = match w . buffer with | Queue_buffer message_queue -> ( try let ( t , u ) = Lwt . wait ( ) in Lwt_pipe . Unbounded . push message_queue ( queue_item ~ u request ) ; t with Lwt_pipe . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) ) | Bounded_buffer message_queue -> let ( t , u ) = Lwt . wait ( ) in Lwt . try_bind ( fun ( ) -> Lwt_pipe . Bounded . push message_queue ( queue_item ~ u request ) ) ( fun ( ) -> t ) ( function | Lwt_pipe . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) | exn -> raise exn ) let pending_requests ( type a ) ( w : a queue t ) = let peeked = try match w . buffer with | Queue_buffer message_queue -> Lwt_pipe . Unbounded . peek_all_now message_queue | Bounded_buffer message_queue -> Lwt_pipe . Bounded . peek_all_now message_queue with Lwt_pipe . Closed -> [ ] in List . map ( function ( t , Message ( req , _ ) ) -> ( t , Request . view req ) ) peeked let pending_requests_length ( type a ) ( w : a queue t ) = let pipe_length ( type a ) ( q : a buffer ) = match q with | Queue_buffer queue -> Lwt_pipe . Unbounded . length queue | Bounded_buffer queue -> Lwt_pipe . Bounded . length queue | Dropbox_buffer _ -> 1 in pipe_length w . buffer end let close ( type a ) ( w : a t ) = let wakeup = function | ( _ , Message ( _ , Some u ) ) -> let name = Format . asprintf " % a " Name . pp w . name in Lwt . wakeup_later u ( error ( Closed { base = base_name ; name } ) ) | ( _ , Message ( _ , None ) ) -> ( ) in let close_queue message_queue = let messages = Lwt_pipe . Bounded . pop_all_now message_queue in List . iter wakeup messages ; Lwt_pipe . Bounded . close message_queue in let close_unbounded_queue message_queue = let messages = Lwt_pipe . Unbounded . pop_all_now message_queue in List . iter wakeup messages ; Lwt_pipe . Unbounded . close message_queue in match w . buffer with | Queue_buffer message_queue -> close_unbounded_queue message_queue | Bounded_buffer message_queue -> close_queue message_queue | Dropbox_buffer message_box -> ( try Option . iter wakeup ( Lwt_dropbox . peek message_box ) with Lwt_dropbox . Closed -> ( ) ) ; Lwt_dropbox . close message_box let pop ( type a ) ( w : a t ) = let open Lwt_syntax in let pop_queue message_queue = match w . timeout with | None -> let * m = Lwt_pipe . Bounded . pop message_queue in return_some m | Some timeout -> Lwt_pipe . Bounded . pop_with_timeout ( Systime_os . sleep timeout ) message_queue in let pop_unbounded_queue message_queue = match w . timeout with | None -> let * m = Lwt_pipe . Unbounded . pop message_queue in return_some m | Some timeout -> Lwt_pipe . Unbounded . pop_with_timeout ( Systime_os . sleep timeout ) message_queue in match w . buffer with | Queue_buffer message_queue -> pop_unbounded_queue message_queue | Bounded_buffer message_queue -> pop_queue message_queue | Dropbox_buffer message_box -> ( match w . timeout with | None -> let * m = Lwt_dropbox . take message_box in return_some m | Some timeout -> Lwt_dropbox . take_with_timeout ( Systime_os . sleep timeout ) message_box ) let trigger_shutdown w = Lwt . ignore_result ( Lwt_canceler . cancel w . canceler ) let canceler { canceler ; _ } = canceler let lwt_emit w ( status : Logger . status ) = let ( module LogEvent ) = w . logEvent in let time = Systime_os . now ( ) in Lwt . bind ( LogEvent . emit ~ section ( : Internal_event . Section . make_sanitized Name . base ) ( fun ( ) -> Time . System . stamp ~ time status ) ) ( function | Ok ( ) -> Lwt . return_unit | Error el -> Format . kasprintf Lwt . fail_with " Worker_event . emit : % a " pp_print_trace el ) let log_event w evt = lwt_emit w ( Logger . WorkerEvent ( evt , Event . level evt ) ) let record_event w evt = Lwt . ignore_result ( log_event w evt ) module type HANDLERS = sig type self val on_launch : self -> Name . t -> Types . parameters -> Types . state tzresult Lwt . t val on_request : self -> ' a Request . t -> ' a tzresult Lwt . t val on_no_request : self -> unit tzresult Lwt . t val on_close : self -> unit Lwt . t val on_error : self -> Request . view -> Worker_types . request_status -> error list -> unit tzresult Lwt . t val on_completion : self -> ' a Request . t -> ' a -> Worker_types . request_status -> unit Lwt . t end let create_table buffer_kind = { buffer_kind ; last_id = 0 ; instances = Nametbl . create ~ random : true 10 } let worker_loop ( type kind ) handlers ( w : kind t ) = let ( module Handlers : HANDLERS with type self = kind t ) = handlers in let do_close errs = let open Lwt_syntax in let t0 = match w . status with | Running t0 -> t0 | Launching _ | Closing _ | Closed _ -> assert false in w . status <- Closing ( t0 , Systime_os . now ( ) ) ; close w ; let * ( ) = Error_monad . cancel_with_exceptions w . canceler in w . status <- Closed ( t0 , Systime_os . now ( ) , errs ) ; let * ( ) = Handlers . on_close w in Nametbl . remove w . table . instances w . name ; w . state <- None ; return_unit in let rec loop ( ) = Lwt . bind Lwt_tzresult_syntax . ( let * popped = protect ~ canceler : w . canceler ( fun ( ) -> Lwt_result . ok @@ pop w ) in match popped with | None -> Handlers . on_no_request w | Some ( pushed , Message ( request , u ) ) -> ( let current_request = Request . view request in let treated_time = Systime_os . now ( ) in w . current_request <- Some ( pushed , treated_time , current_request ) ; match u with | None -> let * res = Handlers . on_request w request in let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in w . current_request <- None ; let status = Worker_types . { pushed ; treated ; completed } in let *! ( ) = Handlers . on_completion w request res status in let *! ( ) = lwt_emit w ( Request ( current_request , status , None ) ) in return_unit | Some u -> let *! res = Handlers . on_request w request in Lwt . wakeup_later u res ; let *? res = res in let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in let status = Worker_types . { pushed ; treated ; completed } in w . current_request <- None ; let *! ( ) = Handlers . on_completion w request res status in let *! ( ) = lwt_emit w ( Request ( current_request , status , None ) ) in return_unit ) ) Lwt_syntax . ( function | Ok ( ) -> loop ( ) | Error ( Canceled :: _ ) | Error ( Exn Lwt . Canceled :: _ ) | Error ( Exn Lwt_pipe . Closed :: _ ) | Error ( Exn Lwt_dropbox . Closed :: _ ) -> let * ( ) = lwt_emit w Terminated in do_close None | Error errs -> ( let * r = match w . current_request with | Some ( pushed , treated_time , request ) -> let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in w . current_request <- None ; Handlers . on_error w request Worker_types . { pushed ; treated ; completed } errs | None -> assert false in match r with | Ok ( ) -> loop ( ) | Error ( Timeout :: _ as errs ) -> let * ( ) = lwt_emit w Terminated in do_close ( Some errs ) | Error errs -> let * ( ) = lwt_emit w ( Crashed errs ) in do_close ( Some errs ) ) ) in loop ( ) let launch : type kind . kind table -> ? timeout : Time . System . Span . t -> Name . t -> Types . parameters -> ( module HANDLERS with type self = kind t ) -> kind t tzresult Lwt . t = fun table ? timeout name parameters ( module Handlers ) -> let name_s = Format . asprintf " % a " Name . pp name in let full_name = if name_s = " " then base_name else Format . asprintf " % s_ % s " base_name name_s in if Nametbl . mem table . instances name then invalid_arg ( Format . asprintf " Worker . launch : duplicate worker % s " full_name ) else let id = table . last_id <- table . last_id + 1 ; table . last_id in let id_name = if name_s = " " then base_name else Format . asprintf " % s_ % d " base_name id in let canceler = Lwt_canceler . create ( ) in let buffer : kind buffer = match table . buffer_kind with | Queue -> Queue_buffer ( Lwt_pipe . Unbounded . create ( ) ) | Bounded { size } -> Bounded_buffer ( Lwt_pipe . Bounded . create ~ max_size : size ~ compute_size ( : fun _ -> 1 ) ( ) ) | Dropbox _ -> Dropbox_buffer ( Lwt_dropbox . create ( ) ) in let w = { parameters ; name ; canceler ; table ; buffer ; state = None ; id ; worker = Lwt . return_unit ; timeout ; current_request = None ; logEvent = ( module Logger . LogEvent ) ; status = Launching ( Systime_os . now ( ) ) ; } in Nametbl . add table . instances name w ; let open Lwt_tzresult_syntax in let started = if id_name = base_name then None else Some name_s in let *! ( ) = lwt_emit w ( Started started ) in let * state = Handlers . on_launch w name parameters in w . status <- Running ( Systime_os . now ( ) ) ; w . state <- Some state ; w . worker <- Lwt_utils . worker full_name ~ on_event : Internal_event . Lwt_worker_event . on_event ~ run ( : fun ( ) -> worker_loop ( module Handlers ) w ) ~ cancel ( : fun ( ) -> Error_monad . cancel_with_exceptions w . canceler ) ; return w let shutdown w = let open Lwt_syntax in let * ( ) = lwt_emit w Triggering_shutdown in let * ( ) = Error_monad . cancel_with_exceptions w . canceler in w . worker let state w = match ( w . state , w . status ) with | ( None , Launching _ ) -> invalid_arg ( Format . asprintf " Worker . state ( % s [ % a ] ) : state called before worker was initialized " base_name Name . pp w . name ) | ( None , ( Closing _ | Closed _ ) ) -> invalid_arg ( Format . asprintf " Worker . state ( % s [ % a ] ) : state called after worker was terminated " base_name Name . pp w . name ) | ( None , _ ) -> assert false | ( Some state , _ ) -> state let pending_requests q = Queue . pending_requests q let status { status ; _ } = status let current_request { current_request ; _ } = current_request let information ( type a ) ( w : a t ) = { Worker_types . instances_number = Nametbl . length w . table . instances ; wstatus = w . status ; queue_length = ( match w . buffer with | Queue_buffer pipe -> Lwt_pipe . Unbounded . length pipe | Bounded_buffer pipe -> Lwt_pipe . Bounded . length pipe | Dropbox_buffer _ -> 1 ) ; } let list { instances ; _ } = Nametbl . fold ( fun n w acc -> ( n , w ) :: acc ) instances [ ] let find_opt { instances ; _ } = Nametbl . find instances let protect { canceler ; _ } ? on_error f = protect ? on_error ~ canceler f let ( ) = Internal_event . register_section ( Internal_event . Section . make_sanitized Name . base ) end |
let build_rpc_directory state = let dir : unit RPC_directory . t ref = ref RPC_directory . empty in let register0 s f = dir := RPC_directory . register ! dir s ( fun ( ) p q -> f p q ) in let register1 s f = dir := RPC_directory . register ! dir s ( fun ( ( ) , a ) p q -> f a p q ) in let register2 s f = dir := RPC_directory . register ! dir s ( fun ( ( ( ) , a ) , b ) p q -> f a b p q ) in register0 Worker_services . Prevalidators . S . list ( fun ( ) ( ) -> let workers = Prevalidator . running_workers ( ) in let statuses = List . map ( fun ( chain_id , _ , t ) -> ( chain_id , Prevalidator . status t , Prevalidator . information t , Prevalidator . pipeline_length t ) ) workers in return statuses ) ; register1 Worker_services . Prevalidators . S . state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let workers = Prevalidator . running_workers ( ) in let ( _ , _ , t ) = WithExceptions . Option . to_exn ~ none : Not_found @@ List . find ( fun ( c , _ , _ ) -> Chain_id . equal c chain_id ) workers in let status = Prevalidator . status t in let pending_requests = Prevalidator . pending_requests t in let current_request = Prevalidator . current_request t in return { Worker_types . status ; pending_requests ; current_request } ) ; register0 Worker_services . Block_validator . S . state ( fun ( ) ( ) -> let w = Block_validator . running_worker ( ) in return { Worker_types . status = Block_validator . status w ; pending_requests = Block_validator . pending_requests w ; current_request = Block_validator . current_request w ; } ) ; register1 Worker_services . Peer_validators . S . list ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> return ( List . filter_map ( fun ( ( id , peer_id ) , w ) -> if Chain_id . equal id chain_id then Some ( peer_id , Peer_validator . status w , Peer_validator . information w , Peer_validator . pipeline_length w ) else None ) ( Peer_validator . running_workers ( ) ) ) ) ; register2 Worker_services . Peer_validators . S . state ( fun chain peer_id ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let equal ( acid , apid ) ( bcid , bpid ) = Chain_id . equal acid bcid && P2p_peer . Id . equal apid bpid in let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal ( chain_id , peer_id ) ( Peer_validator . running_workers ( ) ) in return { Worker_types . status = Peer_validator . status w ; pending_requests = [ ] ; current_request = Peer_validator . current_request w ; } ) ; register0 Worker_services . Chain_validators . S . list ( fun ( ) ( ) -> return ( List . map ( fun ( id , w ) -> ( id , Chain_validator . status w , Chain_validator . information w , Chain_validator . pending_requests_length w ) ) ( Chain_validator . running_workers ( ) ) ) ) ; register1 Worker_services . Chain_validators . S . state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal : Chain_id . equal chain_id ( Chain_validator . running_workers ( ) ) in return { Worker_types . status = Chain_validator . status w ; pending_requests = Chain_validator . pending_requests w ; current_request = Chain_validator . current_request w ; } ) ; register1 Worker_services . Chain_validators . S . ddb_state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal : Chain_id . equal chain_id ( Chain_validator . running_workers ( ) ) in return ( Chain_validator . ddb_information w ) ) ; ! dir |
module type NAME = sig val base : string list type t val encoding : t Data_encoding . t val pp : Format . formatter -> t -> unit val equal : t -> t -> bool end |
module type VIEW = sig type view val encoding : view Data_encoding . t val pp : Format . formatter -> view -> unit end |
module type EVENT = sig type t include VIEW with type view := t val level : t -> Internal_event . level end |
module type REQUEST = sig type ' a t include VIEW val view : ' a t -> view end |
module type TYPES = sig type state type parameters end |
module type LOGGER = sig module Event : EVENT module Request : VIEW type status = | WorkerEvent of ( Event . t * Internal_event . level ) | Request of ( Request . view * Worker_types . request_status * error list option ) | Terminated | Timeout | Crashed of error list | Started of string option | Triggering_shutdown | Duplicate of string type t = status Time . System . stamped module LogEvent : Internal_event . EVENT with type t = t end |
module type STATIC = sig val worker_name : string end |
module Make ( Event : Worker_intf . EVENT ) ( Request : Worker_intf . VIEW ) ( Static : STATIC ) : Worker_intf . LOGGER with module Event = Event and module Request = Request = struct module Event = Event module Request = Request type status = | WorkerEvent of ( Event . t * Internal_event . level ) | Request of ( Request . view * Worker_types . request_status * error list option ) | Terminated | Timeout | Crashed of error list | Started of string option | Triggering_shutdown | Duplicate of string type t = status Time . System . stamped let status_encoding = let open Data_encoding in Time . System . stamped_encoding @@ union [ case ( Tag 0 ) ~ title " : Event " ( obj2 ( req " event " @@ dynamic_size Event . encoding ) ( req " level " Internal_event . Level . encoding ) ) ( function WorkerEvent ( e , l ) -> Some ( e , l ) | _ -> None ) ( fun ( e , l ) -> WorkerEvent ( e , l ) ) ; case ( Tag 1 ) ~ title " : Request " ( obj3 ( req " request_view " @@ dynamic_size Request . encoding ) ( req " request_status " Worker_types . request_status_encoding ) ( req " errors " ( option ( list error_encoding ) ) ) ) ( function Request ( v , s , e ) -> Some ( v , s , e ) | _ -> None ) ( fun ( v , s , e ) -> Request ( v , s , e ) ) ; case ( Tag 2 ) ~ title " : Terminated " Data_encoding . empty ( function Terminated -> Some ( ) | _ -> None ) ( fun ( ) -> Terminated ) ; case ( Tag 3 ) ~ title " : Timeout " Data_encoding . empty ( function Timeout -> Some ( ) | _ -> None ) ( fun ( ) -> Timeout ) ; case ( Tag 4 ) ~ title " : Crashed " ( list error_encoding ) ( function Crashed errs -> Some errs | _ -> None ) ( fun errs -> Crashed errs ) ; case ( Tag 5 ) ~ title " : Started " ( option string ) ( function Started n -> Some n | _ -> None ) ( fun n -> Started n ) ; case ( Tag 6 ) ~ title " : Triggering_shutdown " Data_encoding . empty ( function Triggering_shutdown -> Some ( ) | _ -> None ) ( fun ( ) -> Triggering_shutdown ) ; case ( Tag 7 ) ~ title " : Duplicate " string ( function Duplicate n -> Some n | _ -> None ) ( fun n -> Duplicate n ) ; ] let pp base_name ppf = function | WorkerEvent ( evt , _ ) -> Format . fprintf ppf " % a " Event . pp evt | Request ( view , { pushed ; treated ; completed } , None ) -> Format . fprintf ppf " [ @< v 0 >% a , @ % a ] " @ Request . pp view Worker_types . pp_status { pushed ; treated ; completed } | Request ( view , { pushed ; treated ; completed } , Some errors ) -> Format . fprintf ppf " [ @< v 0 >% a , @ % a , % a ] " @ Request . pp view Worker_types . pp_status { pushed ; treated ; completed } ( Format . pp_print_list Error_monad . pp ) errors | Terminated -> Format . fprintf ppf " [ @ Worker terminated [ % s ] ] " @ base_name | Timeout -> Format . fprintf ppf " [ @ Worker terminated with timeout [ % s ] ] " @ base_name | Crashed errs -> Format . fprintf ppf " [ @< v 0 > Worker crashed [ % s ] , :@% a ] " @ base_name ( Format . pp_print_list Error_monad . pp ) errs | Started None -> Format . fprintf ppf " Worker started " | Started ( Some n ) -> Format . fprintf ppf " Worker started for % s " n | Triggering_shutdown -> Format . fprintf ppf " Triggering shutdown " | Duplicate name -> let full_name = if name = " " then base_name else Format . asprintf " % s_ % s " base_name name in Format . fprintf ppf " Worker . launch : duplicate worker % s " full_name module Definition : Internal_event . EVENT_DEFINITION with type t = t = struct let section = None let name = Static . worker_name type nonrec t = t let encoding = let open Data_encoding in let v0_encoding = status_encoding in With_version . ( encoding ~ name ( first_version v0_encoding ) ) let pp ~ short : _ ppf ( status : t ) = Format . fprintf ppf " % a " ( pp Static . worker_name ) status . data let doc = " Worker status . " let level ( status : t ) = match status . data with | WorkerEvent ( _ , level ) -> level | Request _ -> Internal_event . Debug | Timeout -> Internal_event . Notice | Terminated | Started _ -> Internal_event . Info | Crashed _ -> Internal_event . Error | Triggering_shutdown -> Internal_event . Debug | Duplicate _ -> Internal_event . Error end module LogEvent : Internal_event . EVENT with type t = t = Internal_event . Make ( Definition ) end |
type context = { worker : Worker . t ; timeout : int ; timeout_fn : unit -> unit ; waiting : ( ( Jv . t , exn ) exn Result . t Lwt_mvar . t * int ) int Queue . t ; } |
let demux context msg = Lwt . async ( fun ( ) -> match Queue . take_opt context . waiting with | None -> Lwt . return ( ) | Some ( mv , outstanding_execution ) outstanding_execution -> Brr . G . stop_timer outstanding_execution ; let msg : Jv . t = Message . Ev . data ( Brr . Ev . as_type msg ) msg in Lwt_mvar . put mv ( Ok msg ) msg ) msg |
let start worker timeout timeout_fn = let context = { worker ; timeout ; timeout_fn ; waiting = Queue . create ( ) } in let ( ) = Brr . Ev . listen Message . Ev . message ( demux context ) context ( Worker . as_target worker ) worker in context |
let rpc context call = let open Lwt in let jv = Conv . jv_of_rpc_call call in let mv = Lwt_mvar . create_empty ( ) in let outstanding_execution = Brr . G . set_timeout ~ ms : 10000 ( fun ( ) -> Lwt . async ( fun ( ) -> Lwt_mvar . put mv ( Error Timeout ) Timeout ) Timeout ; context . timeout_fn ( ) ) in Queue . push ( mv , outstanding_execution ) outstanding_execution context . waiting ; Worker . post context . worker jv ; Lwt_mvar . take mv >>= fun r -> match r with | Ok jv -> let response = Conv . rpc_response_of_jv jv in Lwt . return response | Error exn -> Lwt . fail exn |
module Prevalidators = struct module S = struct let list = RPC_service . get_service ~ description " : Lists the Prevalidator workers and their status . " ~ query : RPC_query . empty ~ output : ( list ( obj4 ( req " chain_id " Chain_id . encoding ) ( req " status " ( Worker_types . worker_status_encoding RPC_error . encoding ) ) ( req " information " ( Worker_types . worker_information_encoding RPC_error . encoding ) ) ( req " pipelines " int16 ) ) ) RPC_path . ( root / " workers " / " prevalidators " ) let state = RPC_service . get_service ~ description " : Introspect the state of prevalidator workers . " ~ query : RPC_query . empty ~ output : ( Worker_types . full_status_encoding Prevalidator_worker_state . Request . encoding RPC_error . encoding ) RPC_path . ( root / " workers " / " prevalidators " /: Chain_services . chain_arg ) end open RPC_context let list ctxt = make_call S . list ctxt ( ) ( ) ( ) let state ctxt h = make_call1 S . state ctxt h ( ) ( ) end |
module Block_validator = struct module S = struct let state = RPC_service . get_service ~ description " : Introspect the state of the block_validator worker . " ~ query : RPC_query . empty ~ output : ( Worker_types . full_status_encoding Block_validator_worker_state . Request . encoding RPC_error . encoding ) RPC_path . ( root / " workers " / " block_validator " ) end open RPC_context let state ctxt = make_call S . state ctxt ( ) ( ) ( ) end |
module Peer_validators = struct module S = struct let list = RPC_service . get_service ~ description " : Lists the peer validator workers and their status . " ~ query : RPC_query . empty ~ output : ( list ( obj4 ( req " peer_id " P2p_peer . Id . encoding ) ( req " status " ( Worker_types . worker_status_encoding RPC_error . encoding ) ) ( req " information " ( Worker_types . worker_information_encoding RPC_error . encoding ) ) ( req " pipelines " Peer_validator_worker_state . pipeline_length_encoding ) ) ) RPC_path . ( root / " workers " / " chain_validators " /: Chain_services . chain_arg / " peers_validators " ) let state = RPC_service . get_service ~ description " : Introspect the state of a peer validator worker . " ~ query : RPC_query . empty ~ output : ( Worker_types . full_status_encoding Peer_validator_worker_state . Request . encoding RPC_error . encoding ) RPC_path . ( root / " workers " / " chain_validators " /: Chain_services . chain_arg / " peers_validators " /: P2p_peer . Id . rpc_arg ) end open RPC_context let list ctxt n = make_call1 S . list ctxt n ( ) ( ) let state ctxt n h = make_call2 S . state ctxt n h ( ) ( ) end |
module Chain_validators = struct module S = struct let list = RPC_service . get_service ~ description " : Lists the chain validator workers and their status . " ~ query : RPC_query . empty ~ output : ( list ( obj4 ( req " chain_id " Chain_id . encoding ) ( req " status " ( Worker_types . worker_status_encoding RPC_error . encoding ) ) ( req " information " ( Worker_types . worker_information_encoding RPC_error . encoding ) ) ( req " pipelines " int16 ) ) ) RPC_path . ( root / " workers " / " chain_validators " ) let state = RPC_service . get_service ~ description " : Introspect the state of a chain validator worker . " ~ query : RPC_query . empty ~ output : ( Worker_types . full_status_encoding Chain_validator_worker_state . Request . encoding RPC_error . encoding ) RPC_path . ( root / " workers " / " chain_validators " /: Chain_services . chain_arg ) let ddb_state = RPC_service . get_service ~ description : " Introspect the state of the DDB attached to a chain validator \ worker . " ~ query : RPC_query . empty ~ output : Chain_validator_worker_state . Distributed_db_state . encoding RPC_path . ( root / " workers " / " chain_validators " /: Chain_services . chain_arg / " ddb " ) end open RPC_context let list ctxt = make_call S . list ctxt ( ) ( ) ( ) let state ctxt h = make_call1 S . state ctxt h ( ) ( ) let ddb_state ctxt h = make_call1 S . ddb_state ctxt h ( ) ( ) end |
module type Base_intf = sig type t type create_args type input type output val create : create_args -> t val close : t -> unit Deferred . t end |
module type Worker_intf = sig include Base_intf val perform : t -> input -> output Deferred . t end |
module type S = sig include Base_intf val is_working : t -> bool val dispatch : t -> input -> output Deferred . t end |
module Make ( Worker : Worker_intf ) Worker_intf : S with type create_args := Worker . create_args and type input := Worker . input and type output := Worker . output = struct type t = { mutable thread : Worker . output Deferred . t option ; worker : Worker . t } let create args = { thread = None ; worker = Worker . create args } let is_working t = Option . value_map t . thread ~ default : false ~ f : Deferred . is_determined let assert_not_working t = if is_working t then failwith " cannot dispatch to busy worker " let dispatch t work = assert_not_working t ; let thread = Worker . perform t . worker work in t . thread <- Some thread ; let % map x = thread in t . thread <- None ; x let close t = assert_not_working t ; Worker . close t . worker end |
type worker_status = | Launching of Time . System . t | Running of Time . System . t | Closing of Time . System . t * Time . System . t | Closed of Time . System . t * Time . System . t * error list option |
let worker_status_encoding error_encoding = let open Data_encoding in union [ case ( Tag 0 ) ~ title " : Launching " ( obj2 ( req " phase " ( constant " launching " ) ) ( req " since " Time . System . encoding ) ) ( function Launching t -> Some ( ( ) , t ) | _ -> None ) ( fun ( ( ) , t ) -> Launching t ) ; case ( Tag 1 ) ~ title " : Running " ( obj2 ( req " phase " ( constant " running " ) ) ( req " since " Time . System . encoding ) ) ( function Running t -> Some ( ( ) , t ) | _ -> None ) ( fun ( ( ) , t ) -> Running t ) ; case ( Tag 2 ) ~ title " : Closing " ( obj3 ( req " phase " ( constant " closing " ) ) ( req " birth " Time . System . encoding ) ( req " since " Time . System . encoding ) ) ( function Closing ( t0 , t ) -> Some ( ( ) , t0 , t ) | _ -> None ) ( fun ( ( ) , t0 , t ) -> Closing ( t0 , t ) ) ; case ( Tag 3 ) ~ title " : Closed " ( obj3 ( req " phase " ( constant " closed " ) ) ( req " birth " Time . System . encoding ) ( req " since " Time . System . encoding ) ) ( function Closed ( t0 , t , None ) -> Some ( ( ) , t0 , t ) | _ -> None ) ( fun ( ( ) , t0 , t ) -> Closed ( t0 , t , None ) ) ; case ( Tag 4 ) ~ title " : Crashed " ( obj4 ( req " phase " ( constant " crashed " ) ) ( req " birth " Time . System . encoding ) ( req " since " Time . System . encoding ) ( req " errors " error_encoding ) ) ( function | Closed ( t0 , t , Some errs ) -> Some ( ( ) , t0 , t , errs ) | _ -> None ) ( fun ( ( ) , t0 , t , errs ) -> Closed ( t0 , t , Some errs ) ) ; ] |
type worker_information = { instances_number : int ; wstatus : worker_status ; queue_length : int ; } |
let worker_information_encoding error_encoding = Data_encoding . ( conv ( fun { instances_number ; wstatus ; queue_length } -> ( instances_number , wstatus , queue_length ) ) ( fun ( instances_number , wstatus , queue_length ) -> { instances_number ; wstatus ; queue_length } ) ( obj3 ( req " instances " int31 ) ( req " status " ( worker_status_encoding error_encoding ) ) ( req " queue_length " int31 ) ) ) |
type request_status = { pushed : Time . System . t ; treated : Time . System . Span . t ; completed : Time . System . Span . t ; } |
let request_status_encoding = let open Data_encoding in conv ( fun { pushed ; treated ; completed } -> ( pushed , treated , completed ) ) ( fun ( pushed , treated , completed ) -> { pushed ; treated ; completed } ) ( obj3 ( req " pushed " Time . System . encoding ) ( req " treated " Time . System . Span . encoding ) ( req " completed " Time . System . Span . encoding ) ) |
type ' req full_status = { status : worker_status ; pending_requests : ( Time . System . t * ' req ) list ; current_request : ( Time . System . t * Time . System . t * ' req ) option ; } |
let full_status_encoding req_encoding error_encoding = let open Data_encoding in let requests_encoding = list ( obj2 ( req " pushed " Time . System . encoding ) ( req " request " ( dynamic_size req_encoding ) ) ) in let current_request_encoding = obj3 ( req " pushed " Time . System . encoding ) ( req " treated " Time . System . encoding ) ( req " request " req_encoding ) in conv ( fun { status ; pending_requests ; current_request } -> ( status , pending_requests , current_request ) ) ( fun ( status , pending_requests , current_request ) -> { status ; pending_requests ; current_request } ) ( obj3 ( req " status " ( worker_status_encoding error_encoding ) ) ( req " pending_requests " requests_encoding ) ( opt " current_request " current_request_encoding ) ) |
let pp_status ppf { pushed ; treated ; completed } = Format . fprintf ppf " Request pushed on % a , treated in % a , completed in % a " Time . System . pp_hum pushed Ptime . Span . pp treated Ptime . Span . pp completed |
type path = | FS_path of string | Cache_id of string | Cd of path * string list |
let cd dir sel = match dir with | Cd ( indir , insel ) -> Cd ( indir , insel @ sel ) | FS_path _ | Cache_id _ -> Cd ( dir , sel ) |
module Docker_image = struct type t = { account : string ; name : string ; tag : string option ; registry : string option ; } end |
module Singularity_image = struct type t = { account : string ; name : string ; tag : string option ; registry : string option ; } end |
type container_image = | Docker_image of Docker_image . t | Singularity_image of Singularity_image . t |
let docker_image ? tag ? registry ~ account ~ name ( ) = Docker_image { account = account ; name = name ; tag = tag ; registry = registry ; } |
type _ t = | Pure : { id : string ; value : ' a } -> ' a t | App : { id : string ; f : ( ' a -> ' b ) t ; x : ' a t ; } -> ' b t | Both : { id : string ; fst : ' a t ; snd : ' b t ; } -> ( ' a ' * b ) t | List : { id : string ; elts : ' a t list ; } -> ' a list t | Eval_path : { id : string ; workflow : path t } -> string t | Spawn : { id : string ; elts : ' a list t ; f : ' a t -> ' b t ; deps : any list ; } -> ' b list t | List_nth : { id : string ; elts : ' a list t ; index : int ; } -> ' a t | Input : { id : string ; path : string ; version : int option } -> path t | Select : { id : string ; dir : path t ; sel : string list ; } -> path t | Plugin : ( ' a plugin , any ) step -> ' a t | Shell : ( shell_command , any ) step -> path t | Glob : { id : string ; pattern : string option ; type_selection : [ ` File | ` Directory ] option ; dir : path t ; } -> path list t | Trywith : { id : string ; w : ' a t ; failsafe : ' a t ; } -> ' a t | Ifelse : { id : string ; cond : bool t ; _then_ : ' a t ; _else_ : ' a t ; } -> ' a t id : string ; descr : string ; task : ' a ; np : int ; mem : int t option ; version : int option ; deps : ' b list ; } | Value_plugin : ( unit -> ' a ) t -> ' a plugin | Path_plugin : ( string -> unit ) t -> path plugin cmd : token Command . t ; images : container_image list ; } | Path_token of path t | Path_list_token of { elts : path list t ; sep : string ; quote : char option ; } | String_token of string t |
let digest x = Digest . to_hex ( Digest . string ( Marshal . ( to_string x [ No_sharing ] ) ) ) |
let id : type s . s t -> string = function | Input { id ; _ } -> id | Select { id ; _ } -> id | Plugin { id ; _ } -> id | Pure { id ; _ } -> id | App { id ; _ } -> id | Spawn { id ; _ } -> id | Both { id ; _ } -> id | Eval_path { id ; _ } -> id | Shell { id ; _ } -> id | List { id ; _ } -> id | List_nth { id ; _ } -> id | Glob { id ; _ } -> id | Trywith { id ; _ } -> id | Ifelse { id ; _ } -> id |
let any x = Any x |
let compare_token x y = match x , y with | Path_token wx , Path_token wy -> String . compare ( id wx ) ( id wy ) | Path_token _ , _ -> - 1 | Path_list_token x , Path_list_token y -> ( match String . compare ( id x . elts ) ( id y . elts ) with | 0 -> compare ( x . sep , x . quote ) ( y . sep , y . quote ) | i -> i ) | Path_list_token _ , _ -> - 1 | String_token wx , String_token wy -> String . compare ( id wx ) ( id wy ) | String_token _ , _ -> 1 |
module Any = struct module T = struct type t = any let id ( Any w ) = id w let compare x y = String . compare ( id x ) ( id y ) let equal x y = String . equal ( id x ) ( id y ) let hash x = Hashtbl . hash ( id x ) end module Set = Set . Make ( T ) module Table = Hashtbl . Make ( T ) module Map = Map . Make ( T ) include T let deps ( Any w ) = match w with | Pure _ -> [ ] | App app -> [ Any app . f ; Any app . x ] | Both p -> [ Any p . fst ; Any p . snd ] | List l -> List . map any l . elts | Eval_path { workflow ; _ } -> [ Any workflow ] | Spawn s -> s . deps | List_nth l -> [ Any l . elts ] | Input _ -> [ ] | Select sel -> [ any sel . dir ] | Plugin v -> v . deps | Shell s -> s . deps | Glob g -> [ Any g . dir ] | Trywith tw -> [ Any tw . w ; Any tw . failsafe ] | Ifelse ie -> [ Any ie . cond ; Any ie . _then_ ; Any ie . _else_ ] let descr ( Any w ) = match w with | Shell s -> Some s . descr | Plugin s -> Some s . descr | Input i -> Some i . path | Select s -> Some ( List . fold_left Filename . concat " " s . sel ) | _ -> None let rec fold_aux w ~ seen ~ init ~ f = if Set . mem w seen then init , seen else let acc , seen = List . fold_left ( fun ( acc , seen ) w -> fold_aux w ~ seen ~ init : acc ~ f ) ( init , seen ) ( deps w ) in f acc w , Set . add w seen let fold w ~ init ~ f = fold_aux w ~ seen : Set . empty ~ init ~ f |> fst end |
let input ? version path = let id = digest ( ` Input , path , version ) in Input { id ; path ; version } |
let select dir sel = let dir , sel = match dir with | Select { dir ; sel = root ; _ } -> dir , root @ sel | Input _ | Plugin _ | Shell _ -> dir , sel | _ -> assert false in let id = digest ( " select " , id dir , sel ) in Select { id ; dir ; sel } |
let pure ~ id value = Pure { id ; value } |
let data value = pure ~ id ( : digest value ) value |
let app f x = let id = digest ( ` App , id f , id x ) in App { id ; f ; x } |
let ( $ ) = app |
let both fst snd = let id = digest ( ` Both , id fst , id snd ) in Both { id ; fst ; snd } |
let add_mem_dep mem deps = match mem with | None -> deps | Some mem -> any mem :: deps |
let plugin ( ? descr = " " ) ( ? np = 1 ) ? mem ? version workflow = let id = digest ( ` Value , id workflow , version ) in Plugin { id ; descr ; np ; mem ; version ; task = Value_plugin workflow ; deps = add_mem_dep mem [ any workflow ] } |
let path_plugin ( ? descr = " " ) ( ? np = 1 ) ? mem ? version workflow = let id = digest ( ` Value , id workflow , version ) in Plugin { id ; descr ; np ; mem ; version ; task = Path_plugin workflow ; deps = add_mem_dep mem [ any workflow ] } |
let path w = Eval_path { id = digest ( ` Eval_path , id w ) ; workflow = w } |
let digestible_cmd = Command . map ~ f ( : function | Path_token w -> id w | Path_list_token { elts ; sep ; quote } -> digest ( id elts , sep , quote ) | String_token w -> id w ) |
let shell ( ? descr = " " ) ? mem ( ? np = 1 ) ? version ( ? img = [ ] ) cmds = let cmd = Command . And_list cmds in let shell_cmd = { cmd ; images = img ; } in let id = digest ( " shell " , version , digestible_cmd cmd ) in let deps = add_mem_dep mem ( Command . deps cmd ~ compare : compare_token |> List . map ( function | Path_token w -> any w | Path_list_token { elts ; _ } -> any elts | String_token s -> any s ) ) in Shell { descr ; task = shell_cmd ; np ; mem ; version ; id ; deps } |
let list elts = let id = digest ( " list " , List . map id elts ) in List { id ; elts } |
let rec independent_workflows_aux cache w ~ from : u = if Any . equal w u then Any . Map . add w ( true , Any . Set . empty ) cache else if Any . Map . mem w cache then cache else ( let deps = Any . deps w in let f acc w = independent_workflows_aux acc w ~ from : u in let cache = List . fold_left f cache deps in let children = List . map ( fun k -> Any . Map . find k cache ) deps in if List . exists fst children then let union = List . fold_left ( fun acc ( _ , s ) -> Any . Set . union acc s ) Any . Set . empty children in Any . Map . add w ( true , union ) cache else Any . Map . add w ( false , Any . Set . singleton w ) cache ) |
let independent_workflows w ~ from : u = let cache = independent_workflows_aux Any . Map . empty w ~ from : u in Any . Map . find w cache |> snd |> Any . Set . elements |
let spawn elts ~ f = let hd = pure ~ id " : __should_never_be_executed__ " List . hd in let u = app hd elts in let f_u = f u in let id = digest ( ` Spawn , id elts , id f_u ) in let deps = any elts :: independent_workflows ( any f_u ) ~ from ( : any u ) in Spawn { id ; elts ; f ; deps } |
let list_nth w i = let id = digest ( ` List_nth , id w , i ) in List_nth { id ; elts = w ; index = i } |
let glob ? pattern ? type_selection dir = let id = digest ( ` Glob , id dir , pattern , type_selection ) in Glob { id ; dir ; pattern ; type_selection } |
let trywith w failsafe = let id = digest ( ` Trywith , id w , id failsafe ) in Trywith { id ; w ; failsafe } |
let ifelse cond _then_ _else_ = let id = digest ( ` Ifelse , id cond , id _then_ , id _else_ ) in Ifelse { id ; cond ; _then_ ; _else_ } |
module Remove = struct let file ~ run_with path = let open KEDSL in workflow_node nothing ~ name ( : sprintf " rm -% s " ( Filename . basename path ) ) ~ ensures ( ` : Is_verified ( ` Command_returns ( Command . shell ~ host : Machine . ( as_host run_with ) ( sprintf " ls % s " path ) , 2 ) ) ) ~ make ( : Machine . quick_run_program run_with Program . ( exec [ " rm " ; " - f " ; path ] ) ) ~ tags [ : Target_tags . clean_up ] let directory ~ run_with path = let open KEDSL in workflow_node nothing ~ name ( : sprintf " rmdir -% s " ( Filename . basename path ) ) ~ ensures ( ` : Is_verified ( ` Command_returns ( Command . shell ~ host : Machine . ( as_host run_with ) ( sprintf " ls % s " path ) , 2 ) ) ) ~ make ( : Machine . quick_run_program run_with Program . ( exec [ " rm " ; " - rf " ; path ] ) ) ~ tags [ : Target_tags . clean_up ] let path_on_host ~ host path = let open KEDSL in workflow_node nothing ~ name ( : sprintf " rm -% s " ( Filename . basename path ) ) ~ make ( : daemonize ~ using ` : Python_daemon ~ host Program . ( exec [ " rm " ; " - rf " ; path ] ) ) end |
module Gunzip = struct let concat ( ~ run_with : Machine . t ) bunch_of_dot_gzs ~ result_path = let open KEDSL in let program = Program . ( exec [ " mkdir " ; " - p " ; Filename . dirname result_path ] && shf " gunzip - c % s > % s " ( List . map bunch_of_dot_gzs ~ f ( : fun o -> Filename . quote o # product # path ) |> String . concat ~ sep " : " ) result_path ) in let name = sprintf " gunzipcat -% s " ( Filename . basename result_path ) in workflow_node ( single_file result_path ~ host : Machine . ( as_host run_with ) ) ~ name ~ make ( : Machine . run_stream_processor ~ name run_with program ) ~ edges ( : on_failure_activate Remove . ( file ~ run_with result_path ) :: List . map ~ f : depends_on bunch_of_dot_gzs ) end |
module Cat = struct let concat ( ~ run_with : Machine . t ) bunch_of_files ~ result_path = let open KEDSL in let program = Program . ( exec [ " mkdir " ; " - p " ; Filename . dirname result_path ] && shf " cat % s > % s " ( List . map bunch_of_files ~ f ( : fun o -> Filename . quote o # product # path ) |> String . concat ~ sep " : " ) result_path ) in let name = sprintf " concat - all -% s " ( Filename . basename result_path ) in workflow_node ( single_file result_path ~ host : Machine . ( as_host run_with ) ) ~ name ~ edges ( : on_failure_activate Remove . ( file ~ run_with result_path ) :: List . map ~ f : depends_on bunch_of_files ) ~ make ( : Machine . run_stream_processor run_with ~ name program ) let cat_folder ~ host ( ~ run_program : Machine . Make_fun . t ) ( ? depends_on [ ] ) = ~ files_gzipped ~ folder ~ destination = let deps = depends_on in let open KEDSL in let name = " cat - folder " - ^ Filename . quote folder in let edges = on_failure_activate ( Remove . path_on_host ~ host destination ) :: List . map ~ f : depends_on deps in if files_gzipped then ( workflow_node ( single_file destination ~ host ) ~ edges ~ name ~ make ( : run_program ~ name Program . ( shf " gunzip - c % s /* > % s " ( Filename . quote folder ) ( Filename . quote destination ) ) ) ) else ( workflow_node ( single_file destination ~ host ) ~ edges ~ name ~ make ( : run_program ~ name Program . ( shf " cat % s /* > % s " ( Filename . quote folder ) ( Filename . quote destination ) ) ) ) end |
module Download = struct let wget_program ? output_filename url = KEDSL . Program . exec [ " wget " ; " - O " ; Option . value output_filename ~ default : Filename . ( basename url ) ; url ] let wget_to_folder ~ host ( ~ run_program : Machine . Make_fun . t ) ~ test_file ~ destination url = let open KEDSL in let name = " wget " - ^ Filename . basename destination in let test_target = destination // test_file in workflow_node ( single_file test_target ~ host ) ~ name ~ make ( : run_program ~ name ~ requirements ( : Machine . Make_fun . downloading [ ] ) Program . ( exec [ " mkdir " ; " - p " ; destination ] && shf " wget % s - P % s " ( Filename . quote url ) ( Filename . quote destination ) ) ) ~ edges [ : on_failure_activate ( Remove . path_on_host ~ host destination ) ; ] let wget ~ host ( ~ run_program : Machine . Make_fun . t ) url destination = let open KEDSL in let name = " wget " - ^ Filename . basename destination in workflow_node ( single_file destination ~ host ) ~ name ~ make ( : run_program ~ name ~ requirements ( : Machine . Make_fun . downloading [ ] ) Program . ( exec [ " mkdir " ; " - p " ; Filename . dirname destination ] && shf " wget % s - O % s " ( Filename . quote url ) ( Filename . quote destination ) ) ) ~ edges [ : on_failure_activate ( Remove . path_on_host ~ host destination ) ; ] let wget_gunzip ~ host ( ~ run_program : Machine . Make_fun . t ) ~ destination url = let open KEDSL in let is_gz = Filename . check_suffix url " . gz " in if is_gz then ( let name = " gunzip " - ^ Filename . basename ( destination ^ " . gz " ) in let wgot = wget ~ host ~ run_program url ( destination ^ " . gz " ) in workflow_node ( single_file destination ~ host ) ~ edges [ : depends_on ( wgot ) ; on_failure_activate ( Remove . path_on_host ~ host destination ) ; ] ~ name ~ make ( : run_program ~ name ~ requirements ( : Machine . Make_fun . stream_processor [ ] ) Program . ( shf " gunzip - c % s > % s " ( Filename . quote wgot # product # path ) ( Filename . quote destination ) ) ) ) else ( wget ~ host ~ run_program url destination ) let wget_bunzip2 ~ host ( ~ run_program : Machine . Make_fun . t ) ~ destination url = let open KEDSL in let is_bz2 = Filename . check_suffix url " . bz2 " in if is_bz2 then ( let name = " bunzip2 " - ^ Filename . basename ( destination ^ " . bz2 " ) in let wgot = wget ~ host ~ run_program url ( destination ^ " . bz2 " ) in workflow_node ( single_file destination ~ host ) ~ edges [ : depends_on ( wgot ) ; on_failure_activate ( Remove . path_on_host ~ host destination ) ; ] ~ name ~ make ( : run_program ~ name ~ requirements ( : Machine . Make_fun . stream_processor [ ] ) Program . ( shf " bunzip2 - c % s > % s " ( Filename . quote wgot # product # path ) ( Filename . quote destination ) ) ) ) else ( wget ~ host ~ run_program url destination ) let wget_untar ~ host ( ~ run_program : Machine . Make_fun . t ) ~ destination_folder ~ tar_contains url = let open KEDSL in let zip_flags = let is_gz = Filename . check_suffix url " . gz " in let is_bzip = Filename . check_suffix url " . bz2 " in if is_gz then " z " else if is_bzip then " j " else " " in let tar_filename = ( destination_folder // " archive . tar " ) in let name = " untar " - ^ tar_filename in let wgot = wget ~ host ~ run_program url tar_filename in let file_in_tar = ( destination_folder // tar_contains ) in workflow_node ( single_file file_in_tar ~ host ) ~ edges [ : depends_on ( wgot ) ; on_failure_activate ( Remove . path_on_host ~ host destination_folder ) ; ] ~ name ~ make ( : run_program ~ name ~ requirements ( : Machine . Make_fun . stream_processor [ ] ) Program . ( exec [ " mkdir " ; " - p " ; destination_folder ] && shf " tar - x % s - f % s - C % s " zip_flags ( Filename . quote wgot # product # path ) ( Filename . quote destination_folder ) ) ) type tool_file_location = [ | ` Scp of string | ` Wget of string | ` Fail of string ] let get_tool_file ~ identifier ( ~ run_program : Machine . Make_fun . t ) ~ host ~ install_path loc = let open KEDSL in let rm_path = Remove . path_on_host in let jar_name = match loc with | ` Fail s -> sprintf " cannot - get -% s . file " identifier | ` Scp s -> Filename . basename s | ` Wget s -> Filename . basename s in let local_box_path = install_path // jar_name in workflow_node ( single_file local_box_path ~ host ) ~ name ( : sprintf " get -% s " jar_name ) ~ edges [ : on_failure_activate ( rm_path ~ host local_box_path ) ] ~ make ( : run_program ~ requirements [ : ` Internet_access ; ` Self_identification [ identifier ^ " - instalation " ; jar_name ] ; ] Program . ( shf " mkdir - p % s " install_path && begin match loc with | ` Fail msg -> shf " echo ' Cannot download file for % s : % s ' " identifier msg && sh " exit 4 " | ` Scp s -> shf " scp % s % s " ( Filename . quote s ) ( Filename . quote local_box_path ) | ` Wget s -> shf " wget % s - O % s " ( Filename . quote s ) ( Filename . quote local_box_path ) end ) ) let gsutil_cp ( ~ run_program : Machine . Make_fun . t ) ~ host ~ url ~ local_path = let open KEDSL in workflow_node ( single_file ~ host local_path ) ~ name ( : sprintf " GSUtil - CP : % s " ( Filename . basename local_path ) ) ~ edges [ : on_failure_activate ( Remove . path_on_host ~ host local_path ) ] ~ make ( : run_program ~ requirements [ : ` Internet_access ; ` Self_identification [ " gsutil - cp " ; url ] ; ] Program . ( shf " mkdir - p % s " ( Filename . dirname local_path ) && exec [ " gsutil " ; " cp " ; url ; local_path ] ) ) end |
module Vcftools = struct let vcf_process_n_to_1_no_machine ~ host ~ vcftools ( ~ run_program : Machine . Make_fun . t ) ( ? more_edges = [ ] ) ~ vcfs ~ make_product ~ final_vcf command_prefix = let open KEDSL in let name = sprintf " % s -% s " command_prefix ( Filename . basename final_vcf ) in let make = run_program ~ name Program . ( Machine . Tool . ( init vcftools ) && shf " % s % s > % s " command_prefix ( String . concat ~ sep " : " ( List . map vcfs ~ f ( : fun t -> Filename . quote t # product # path ) ) ) final_vcf ) in workflow_node ~ name ( make_product final_vcf ) ~ make ~ edges ( : on_failure_activate ( Remove . path_on_host ~ host final_vcf ) :: depends_on Machine . Tool . ( ensure vcftools ) :: List . map ~ f : depends_on vcfs @ more_edges ) let vcf_concat_no_machine ~ host ~ vcftools ( ~ run_program : Machine . Make_fun . t ) ? more_edges ~ make_product vcfs ~ final_vcf = vcf_process_n_to_1_no_machine ~ make_product ~ host ~ vcftools ~ run_program ? more_edges ~ vcfs ~ final_vcf " vcf - concat " let vcf_sort_no_machine ~ host ~ vcftools ( ~ run_program : Machine . Make_fun . t ) ? more_edges ~ make_product ~ src ~ dest ( ) = let run_program = Machine . Make_fun . with_requirements run_program [ ` Memory ` Big ] in vcf_process_n_to_1_no_machine ~ make_product ~ host ~ vcftools ~ run_program ? more_edges ~ vcfs [ : src ] ~ final_vcf : dest " vcf - sort - c " end |
module Variable_tool_paths = struct let single_file ~ run_with ~ tool path = let open KEDSL in let condition = let init = Machine . Tool . init tool in let host = Machine . as_host ~ with_shell " : bash " run_with in let condition_cmd = Ketrew_pure . Program . to_single_shell_command Program . ( init && shf " test - e % s " path ) in KEDSL . Command . shell ~ host condition_cmd in object method is_done = Some ( ` Command_returns ( condition , 0 ) ) end end |
module type Work_list = sig type elt type t val empty : t val is_empty : t -> bool val push : Remanent_parameters_sig . parameters -> Exception . method_handler -> elt -> t -> Exception . method_handler * t val pop : Remanent_parameters_sig . parameters -> Exception . method_handler -> t -> Exception . method_handler * ( elt option * t ) val fold_left : ( ' a -> elt -> ' a ) -> ' a -> t -> ' a val print_wl : Remanent_parameters_sig . parameters -> t -> unit end |
module WlMake ( Ord : OrderedType with type t = int ) = ( struct module WSetMap = Map_wrapper . Make ( SetMap . Make ( Ord ) ) module WSet = WSetMap . Set type elt = Ord . t type t = elt list * elt list * WSet . t let empty = [ ] , [ ] , WSet . empty let is_empty x = let _ , _ , pool = x in WSet . is_empty pool let push parameter error e x = let in_list , out_list , pool = x in if WSet . mem e pool then error , x else let error ' , add_elt = WSet . add parameter error e pool in let error = Exception . check_point Exception . warn parameter error error ' __POS__ Exit in error , ( ( e :: in_list ) , out_list , add_elt ) let fold_left f acc x = let in_list , out_list , _ = x in List . fold_left f ( List . fold_left f acc out_list ) ( List . rev in_list ) let print_wl parameters wl = let _ = print_newline ( ) in ) * let _ , _ , set = wl in WSet . iter ( fun i -> Loggers . fprintf ( Remanent_parameters . get_logger parameters ) " % i " i ) set ; Loggers . fprintf ( Remanent_parameters . get_logger parameters ) " \ n " let rec pop parameter error x = let in_list , out_list , pool = x in if is_empty x then error , ( None , x ) else begin match out_list with | [ ] -> pop parameter error ( [ ] , ( List . rev in_list ) , pool ) | h :: tl -> let error , remove_elt = WSet . remove parameter error h pool in error , ( ( Some h ) , ( in_list , tl , remove_elt ) ) end end ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.