text
stringlengths 0
601k
|
---|
module Flags = struct let extract_words = String . extract_words let extract_comma_space_separated_words = String . extract_comma_space_separated_words let extract_blank_separated_words = String . extract_blank_separated_words let write_lines path s = Io . write_lines path s let write_sexp path s = let sexp = Dune_lang . List ( List . map s ~ f ( : fun s -> Dune_lang . Quoted_string s ) ) in Io . write_file path ( Dune_lang . to_string sexp ) end |
module Find_in_path = struct let path_sep = if Sys . win32 then ' ; ' else ' ' : let get_path ( ) = match Sys . getenv " PATH " with | exception Not_found -> [ ] | s -> String . split s ~ on : path_sep let exe = if Sys . win32 then " . exe " else " " let prog_not_found prog = die " Program % s not found in PATH " prog let best_prog dir prog = let fn = dir ^/ prog ^ " . opt " ^ exe in if Sys . file_exists fn then Some fn else let fn = dir ^/ prog ^ exe in if Sys . file_exists fn then Some fn else None let find_ocaml_prog prog = match List . find_map ( get_path ( ) ) ~ f ( : fun dir -> best_prog dir prog ) with | None -> prog_not_found prog | Some fn -> fn let which prog = List . find_map ( get_path ( ) ) ~ f ( : fun dir -> let fn = dir ^/ prog ^ exe in Option . some_if ( Sys . file_exists fn ) fn ) end |
let logf t fmt = Printf . ksprintf t . log fmt |
let gen_id t = let n = t . counter in t . counter <- n + 1 ; n |
let quote_if_needed = let need_quote = function | ' ' | ' " ' \ -> true | _ -> false in fun s -> if String . is_empty s || String . exists ~ f : need_quote s then Filename . quote s else s |
module Process = struct type result = { exit_code : int ; stdout : string ; stderr : string } let command_line prog args = String . concat ~ sep " : " ( List . map ( prog :: args ) ~ f : quote_if_needed ) let run_process t ? dir ? env prog args = let prog_command_line = command_line prog args in logf t " run : % s " prog_command_line ; let n = gen_id t in let create_process = let args = Array . of_list ( prog :: args ) in match env with | None -> Unix . create_process prog args | Some env -> let env = Array . of_list env in Unix . create_process_env prog args env in let stdout_fn = t . dest_dir ^/ sprintf " stdout -% d " n in let stderr_fn = t . dest_dir ^/ sprintf " stderr -% d " n in let status = let run ( ) = let openfile f = Unix . openfile f [ O_WRONLY ; O_CREAT ; O_TRUNC ; O_SHARE_DELETE ] 0o666 in let stdout = openfile stdout_fn in let stderr = openfile stderr_fn in let stdin , stdin_w = Unix . pipe ( ) in Unix . close stdin_w ; let p = create_process stdin stdout stderr in Unix . close stdin ; Unix . close stdout ; Unix . close stderr ; let _pid , status = Unix . waitpid [ ] p in status in match dir with | None -> run ( ) | Some d -> let old_dir = Sys . getcwd ( ) in Exn . protect ~ f ( : fun ( ) -> Sys . chdir d ; run ( ) ) ~ finally ( : fun ( ) -> Sys . chdir old_dir ) in match status with | Unix . WSIGNALED signal -> die " signal % d killed process : % s " signal prog_command_line | WSTOPPED signal -> die " signal % d stopped process : % s " signal prog_command_line | WEXITED exit_code -> logf t " -> process exited with code % d " exit_code ; let stdout = Io . read_file stdout_fn in let stderr = Io . read_file stderr_fn in logf t " -> stdout " ; : List . iter ( String . split_lines stdout ) ~ f ( : logf t " | % s " ) ; logf t " -> stderr " ; : List . iter ( String . split_lines stderr ) ~ f ( : logf t " | % s " ) ; { exit_code ; stdout ; stderr } let command_args cmd args = String . concat ~ sep " : " ( cmd :: List . map args ~ f : quote_if_needed ) let run_command t ? dir ( ? env = [ ] ) cmd = logf t " run : % s " cmd ; let n = gen_id t in let stdout_fn = t . dest_dir ^/ sprintf " stdout -% d " n in let stderr_fn = t . dest_dir ^/ sprintf " stderr -% d " n in let in_dir = match dir with | None -> " " | Some dir -> sprintf " cd % s && " ( Filename . quote dir ) in let with_env = match env with | [ ] -> " " | _ -> " env " ^ String . concat ~ sep " : " env in let exit_code = Printf . ksprintf Sys . command " % s % s % s > % s 2 > % s " in_dir with_env cmd ( Filename . quote stdout_fn ) ( Filename . quote stderr_fn ) in let stdout = Io . read_file stdout_fn in let stderr = Io . read_file stderr_fn in logf t " -> process exited with code % d " exit_code ; logf t " -> stdout " ; : List . iter ( String . split_lines stdout ) ~ f ( : logf t " | % s " ) ; logf t " -> stderr " ; : List . iter ( String . split_lines stderr ) ~ f ( : logf t " | % s " ) ; { exit_code ; stdout ; stderr } let run_command_capture_exn t ? dir ? env cmd = let { exit_code ; stdout ; stderr } = run_command t ? dir ? env cmd in if exit_code <> 0 then die " command exited with code % d : % s " exit_code cmd else if not ( String . is_empty stderr ) then die " command has non - empty stderr : % s " cmd else stdout let run_command_ok t ? dir ? env cmd = ( run_command t ? dir ? env cmd ) . exit_code = 0 let run t ? dir ? env prog args = run_command t ? dir ? env ( command_line prog args ) let run_capture_exn t ? dir ? env prog args = run_command_capture_exn t ? dir ? env ( command_line prog args ) let run_ok t ? dir ? env prog args = run_command_ok t ? dir ? env ( command_line prog args ) end |
let ocaml_config_var t var = Ocaml_config . Vars . find t . ocamlc_config var |
let ocaml_config_var_exn t var = match Ocaml_config . Vars . find t . ocamlc_config var with | None -> die " variable % S not found in the output of ` % s ` " var t . ocamlc_config_cmd | Some s -> s |
type config = { ocamlc : string ; vars : Ocaml_config . Vars . t } |
let dune_is_too_old ~ min : v = die " You seem to be running dune < % s . This version of dune - configurator \ requires at least dune % s . " v v |
let read_dot_dune_configurator_file ~ build_dir = let file = Filename . concat build_dir " . dune / configurator . v2 " in if not ( Sys . file_exists file ) then dune_is_too_old ~ min " : 2 . 6 " ; let open Sexp in let unable_to_parse err = die " Unable to parse % S . . @% s . " @ file err in let sexp = match Io . with_file_in file ~ f : Sexp . input with | Ok s -> s | Error e -> unable_to_parse e in match sexp with | Atom _ -> unable_to_parse " unexpected atom " | List xs -> let field name = match List . find_map xs ~ f ( : function | List [ Atom name ' ; f ] when name = name ' -> Some f | _ -> None ) with | None -> die " unable to find field % S " name | Some f -> f in let ocamlc = match field " ocamlc " with | Atom o -> o | _ -> die " invalid ocamlc field " in let vars = let bindings = match field " ocaml_config_vars " with | List bindings -> List . map bindings ~ f ( : function | List [ Atom k ; Atom v ] -> ( k , v ) | _ -> die " invalid output " ) | _ -> die " invalid output " in Ocaml_config . Vars . of_list_exn bindings in { ocamlc ; vars } |
let fill_in_fields_that_depends_on_ocamlc_config t = let get = ocaml_config_var_exn t in let get_flags var = get var |> String . trim |> Flags . extract_blank_separated_words in let c_compiler , c_libraries = match Ocaml_config . Vars . find t . ocamlc_config " c_compiler " with | Some c_comp -> ( c_comp ^ " " ^ get " ocamlc_cflags " , get_flags " native_c_libraries " ) | None -> ( get " bytecomp_c_compiler " , get_flags " bytecomp_c_libraries " ) in { t with ext_obj = get " ext_obj " ; c_compiler ; stdlib_dir = get " standard_library " ; ccomp_type = get " ccomp_type " ; c_libraries } |
let create_from_inside_dune ~ dest_dir ~ log ~ build_dir ~ name = let dest_dir = match dest_dir with | Some dir -> dir | None -> Temp . create_temp_dir ~ prefix " : ocaml - configurator " ~ suffix " " : in let { ocamlc ; vars = ocamlc_config } = read_dot_dune_configurator_file ~ build_dir in let ocamlc_config_cmd = Process . command_line ocamlc [ " - config " ] in fill_in_fields_that_depends_on_ocamlc_config { name ; ocamlc ; log ; dest_dir ; counter = 0 ; ocamlc_config ; ocamlc_config_cmd ; ext_obj = " " ; c_compiler = " " ; stdlib_dir = " " ; ccomp_type = " " ; c_libraries = [ ] } |
let create ? dest_dir ? ocamlc ( ? log = ignore ) name = match ( ocamlc , Option . try_with ( fun ( ) -> Sys . getenv " INSIDE_DUNE " ) ) with | None , Some build_dir when build_dir <> " 1 " -> create_from_inside_dune ~ dest_dir ~ log ~ build_dir ~ name | _ -> let dest_dir = match dest_dir with | Some dir -> dir | None -> Temp . create_temp_dir ~ prefix " : ocaml - configurator " ~ suffix " " : in let ocamlc = match ocamlc with | Some fn -> fn | None -> Find_in_path . find_ocaml_prog " ocamlc " in let ocamlc_config_cmd = Process . command_line ocamlc [ " - config " ] in let t = { name ; ocamlc ; log ; dest_dir ; counter = 0 ; ext_obj = " " ; c_compiler = " " ; stdlib_dir = " " ; ccomp_type = " " ; c_libraries = [ ] ; ocamlc_config = Ocaml_config . Vars . of_list_exn [ ] ; ocamlc_config_cmd } in let ocamlc_config = let ocamlc_config_output = Process . run_command_capture_exn t ~ dir : dest_dir ocamlc_config_cmd |> String . split_lines in match Ocaml_config . Vars . of_lines ocamlc_config_output with | Ok x -> x | Error msg -> die " Failed to parse the output of ' % s ' :@\ n % s " ocamlc_config_cmd msg in fill_in_fields_that_depends_on_ocamlc_config { t with ocamlc_config } |
let need_to_compile_and_link_separately t = match t . ccomp_type with | " msvc " -> true | _ -> false |
let compile_and_link_c_prog t ( ? c_flags = [ ] ) ( ? link_flags = [ ] ) code = let dir = t . dest_dir ^/ sprintf " c - test -% d " ( gen_id t ) in Unix . mkdir dir 0o777 ; let base = dir ^/ " test " in let c_fname = base ^ " . c " in let obj_fname = base ^ t . ext_obj in let exe_fname = base ^ " . exe " in Io . write_file c_fname code ; logf t " compiling c program " ; : List . iter ( String . split_lines code ) ~ f ( : logf t " | % s " ) ; let run_ok args = Process . run_command_ok t ~ dir ( Process . command_args t . c_compiler args ) in let ok = if need_to_compile_and_link_separately t then run_ok ( c_flags @ [ " - I " ; t . stdlib_dir ; " - c " ; c_fname ] ) && run_ok ( ( " - o " :: exe_fname :: obj_fname :: t . c_libraries ) @ link_flags ) else run_ok ( List . concat [ c_flags ; [ " - I " ; t . stdlib_dir ; " - o " ; exe_fname ; c_fname ] ; t . c_libraries ; link_flags ] ) in if ok then Ok ( ) else Error ( ) |
let compile_c_prog t ( ? c_flags = [ ] ) code = let dir = t . dest_dir ^/ sprintf " c - test -% d " ( gen_id t ) in Unix . mkdir dir 0o777 ; let base = dir ^/ " test " in let c_fname = base ^ " . c " in let obj_fname = base ^ t . ext_obj in Io . write_file c_fname code ; logf t " compiling c program " ; : List . iter ( String . split_lines code ) ~ f ( : logf t " | % s " ) ; let ok = Process . run_command_ok t ~ dir ( Process . command_args t . c_compiler ( c_flags @ " - I " :: t . stdlib_dir :: " - o " :: obj_fname :: " - c " :: c_fname :: t . c_libraries ) ) in if ok then Ok obj_fname else Error ( ) |
let c_test t ? c_flags ? link_flags code = match compile_and_link_c_prog t ? c_flags ? link_flags code with | Ok _ -> true | Error _ -> false |
module C_define = struct module Type = struct type t = | Switch | Int | String let name = function | Switch -> " bool " | Int -> " int " | String -> " string " end module Value = struct type t = | Switch of bool | Int of int | String of string end let extract_program ? prelude includes vars = let has_type t = List . exists vars ~ f ( : fun ( _ , t ' ) -> t = t ' ) in let buf = Buffer . create 1024 in let pr fmt = Printf . bprintf buf ( fmt ^^ " \ n " ) in List . iter includes ~ f ( : pr " # include <% s " ) ; > pr " " ; Option . iter prelude ~ f ( : pr " % s " ) ; if has_type Type . Int then pr { | } ; | List . iteri vars ~ f ( : fun i ( name , t ) -> match t with | Type . Int -> let c_arr_i = let b = Buffer . create 8 in let is = string_of_int i in for i = 0 to String . length is - 1 do Printf . bprintf b " ' % c ' , " is . [ i ] done ; Buffer . contents b in pr { | ' B ' , ' E ' , ' G ' , ' I ' , ' N ' , ' ' , - % s ' ' , - DUNE_SIGN ( ( % s ) ) , DUNE_D9 ( ( % s ) ) , ' ' , - ' E ' , ' N ' , ' D ' } ; } | i c_arr_i name name | String -> pr { | const char * s % i = " BEGIN -% i " - % s " - END " ; } | i i name | Switch -> pr { | # else # endif } | name i i i i ) ; Buffer . contents buf let extract_values obj_file vars = let values = Io . with_lexbuf_from_file obj_file ~ f ( : Extract_obj . extract [ ] ) |> List . fold_left ~ init : Int . Map . empty ~ f ( : fun acc ( key , v ) -> Int . Map . update acc key ~ f ( : function | None -> Some [ v ] | Some vs -> Some ( v :: vs ) ) ) in List . mapi vars ~ f ( : fun i ( name , t ) -> let raw_vals = match Int . Map . find values i with | Some v -> v | None -> die " Unable to get value for % s " name in let parse_val_or_exn f = let f x = match f x with | Some s -> s | None -> die " Unable to read variable % S of type % s . Invalid value % S in % s \ found " name ( Type . name t ) x obj_file in let vs = List . map ~ f ( : fun x -> ( x , f x ) ) raw_vals |> List . sort_uniq ~ cmp ( : fun ( _ , x ) ( _ , y ) -> compare x y ) in match vs with | [ ] -> assert false | [ ( _ , v ) ] -> v | vs -> let vs = List . map ~ f : fst vs in die " Duplicate values for % s :\ n % s " name ( vs |> List . map ~ f ( : sprintf " - % s " ) |> String . concat ~ sep " :\ n " ) in let value = match t with | Type . Switch -> Value . Switch ( parse_val_or_exn Bool . of_string ) | Int -> Value . Int ( parse_val_or_exn Int . of_string ) | String -> String ( parse_val_or_exn Option . some ) in ( name , value ) ) let import t ? prelude ? c_flags ~ includes vars = let program = extract_program ? prelude ( " stdio . h " :: includes ) vars in match compile_c_prog t ? c_flags program with | Error _ -> die " failed to compile program " | Ok obj -> extract_values obj vars let gen_header_file t ~ fname ? protection_var vars = let protection_var = match protection_var with | Some v -> v | None -> String . map ( t . name ^ " _ " ^ Filename . basename fname ) ~ f ( : function | ' a ' . . ' z ' as c -> Char . uppercase_ascii c | ( ' A ' . . ' Z ' | ' 0 ' . . ' 9 ' ) as c -> c | _ -> ' _ ' ) in let vars = List . sort vars ~ cmp ( : fun ( a , _ ) ( b , _ ) -> compare a b ) in let lines = List . map vars ~ f ( : fun ( name , value ) -> match ( value : Value . t ) with | Switch false -> sprintf " # undef % s " name | Switch true -> sprintf " # define % s " name | Int n -> sprintf " # define % s ( % d ) " name n | String s -> sprintf " # define % s % S " name s ) in let lines = List . concat [ [ sprintf " # ifndef % s " protection_var ; sprintf " # define % s " protection_var ] ; lines ; [ " # endif " ] ] in logf t " writing header file % s " fname ; List . iter lines ~ f ( : logf t " | % s " ) ; let tmp_fname = fname ^ " . tmp " in Io . write_lines tmp_fname lines ; Sys . rename tmp_fname fname end |
let which t prog = logf t " which : % s " prog ; let x = Find_in_path . which prog in logf t " -> % s " ( match x with | None -> " not found " | Some fn -> " found : " ^ quote_if_needed fn ) ; x |
module Pkg_config = struct type nonrec t = { pkg_config : string ; configurator : t } let get c = Option . map ( which c " pkg - config " ) ~ f ( : fun pkg_config -> { pkg_config ; configurator = c } ) type package_conf = { libs : string list ; cflags : string list } let gen_query t ~ package ~ expr = let c = t . configurator in let dir = c . dest_dir in let expr = match expr with | Some e -> e | None -> if String . exists package ~ f ( : function | ' ' = | ' ' > | ' ' < -> true | _ -> false ) then warn " Package name % S contains invalid characters . Use \ Pkg_config . query_expr to construct proper queries " package ; package in let env = match ocaml_config_var c " system " with | Some " macosx " -> let open Option . O in which c " brew " >>= fun brew -> let new_pkg_config_path = let prefix = String . trim ( Process . run_capture_exn c ~ dir brew [ " -- prefix " ] ) in let p = sprintf " % s / opt /% s / lib / pkgconfig " ( quote_if_needed prefix ) package in Option . some_if ( match Sys . is_directory p with | s -> s | exception Sys_error _ -> false ) p in new_pkg_config_path >>| fun new_pkg_config_path -> let _PKG_CONFIG_PATH = " PKG_CONFIG_PATH " in let pkg_config_path = match Sys . getenv _PKG_CONFIG_PATH with | s -> s ^ " " : | exception Not_found -> " " in [ sprintf " % s =% s % s " _PKG_CONFIG_PATH pkg_config_path new_pkg_config_path ] | _ -> None in let pc_flags = " -- print - errors " in let { Process . exit_code ; stderr ; _ } = Process . run_process c ~ dir ? env t . pkg_config [ pc_flags ; expr ] in if exit_code = 0 then let run what = match String . trim ( Process . run_capture_exn c ~ dir ? env t . pkg_config [ what ; package ] ) with | " " -> [ ] | s -> String . extract_blank_separated_words s in Ok { libs = run " -- libs " ; cflags = run " -- cflags " } else Error stderr let query t ~ package = Result . to_option @@ gen_query t ~ package ~ expr : None let query_expr t ~ package ~ expr = Result . to_option @@ gen_query t ~ package ~ expr ( : Some expr ) let query_expr_err t ~ package ~ expr = gen_query t ~ package ~ expr ( : Some expr ) end |
let main ( ? args = [ ] ) ~ name f = let build_dir = match Sys . getenv " INSIDE_DUNE " with | exception Not_found -> die " Configurator scripts must be run with Dune . To manually run a script , \ use $ dune exec . " | " 1 " -> dune_is_too_old ~ min " : 2 . 3 " | s -> s in let verbose = ref false in let dest_dir = ref None in let args = Arg . align ( [ ( " - verbose " , Arg . Set verbose , " be verbose " ) ; ( " - dest - dir " , Arg . String ( fun s -> dest_dir := Some s ) , " DIR save temporary files to this directory " ) ] @ args ) in let anon s = raise ( Arg . Bad ( sprintf " don ' t know what to do with % s " s ) ) in let usage = sprintf " % s [ OPTIONS ] " ( Filename . basename Sys . executable_name ) in Arg . parse args anon usage ; let log_db = ref [ ] in let log s = log_db := s :: ! log_db in try let t = create_from_inside_dune ~ dest_dir :! dest_dir ~ log ( : if ! verbose then prerr_endline else log ) ~ build_dir ~ name in f t with exn -> ( let bt = Printexc . get_raw_backtrace ( ) in List . iter ( List . rev ! log_db ) ~ f ( : eprintf " % s \ n " ) ; match exn with | Fatal_error msg -> eprintf " Error : % s \ n " %! msg ; exit 1 | _ -> Exn . raise_with_backtrace exn bt ) |
type addr = [ ` OpenSSL of Ipaddr_sexp . t * int * Ssl . Config . t | ` TCP of Ipaddr_sexp . t * int | ` Unix_domain_socket of string ] |
let connect ? interrupt dst = match dst with | ` TCP ( ip , port ) -> let endp = Host_and_port . create ~ host ( : Ipaddr . to_string ip ) ~ port in Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_host_and_port endp ) >>= fun ( _ , rd , wr ) -> return ( rd , wr ) | ` OpenSSL ( ip , port , cfg ) -> let endp = Host_and_port . create ~ host ( : Ipaddr . to_string ip ) ~ port in Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_host_and_port endp ) >>= fun ( _ , rd , wr ) -> Ssl . connect ~ cfg rd wr | ` Unix_domain_socket file -> Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_file file ) >>= fun ( _ , rd , wr ) -> return ( rd , wr ) |
let with_connection ? interrupt dst f = match dst with | ` TCP ( ip , port ) -> let endp = Host_and_port . create ~ host ( : Ipaddr . to_string ip ) ~ port in Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_host_and_port endp ) ( fun _ rd wr -> f rd wr ) | ` OpenSSL ( ip , port , cfg ) -> let endp = Host_and_port . create ~ host ( : Ipaddr . to_string ip ) ~ port in Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_host_and_port endp ) ( fun _ rd wr -> Ssl . connect ~ cfg rd wr >>= fun ( rd , wr ) -> Monitor . protect ( fun ( ) -> f rd wr ) ~ finally ( : fun ( ) -> Deferred . all_unit [ Reader . close rd ; Writer . close wr ] ) ) | ` Unix_domain_socket file -> Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_file file ) ( fun _ rd wr -> f rd wr ) |
type trust_chain = [ ` Ca_file of string | ` Ca_path of string | ` Search_file_first_then_path of [ ` File of string ] * [ ` Path of string ] ] |
type openssl = [ ` OpenSSL of [ ` Crt_file_path of string ] * [ ` Key_file_path of string ] ] |
type requires_async_ssl = [ openssl | ` OpenSSL_with_trust_chain of openssl * trust_chain ] |
type server = [ ` TCP | requires_async_ssl ] [ @@ deriving sexp ] |
let serve ? max_connections ? backlog ? buffer_age_limit ~ on_handler_error mode where_to_listen handle_request = let handle_client handle_request sock rd wr = match mode with | ` TCP -> handle_request sock rd wr | # requires_async_ssl as async_ssl -> let crt_file , key_file , ca_file , ca_path = match async_ssl with | ` OpenSSL ( ` Crt_file_path crt_file , ` Key_file_path key_file ) -> ( crt_file , key_file , None , None ) | ` OpenSSL_with_trust_chain ( ` OpenSSL ( ` Crt_file_path crt , ` Key_file_path key ) , trust_chain ) -> let ca_file , ca_path = match trust_chain with | ` Ca_file ca_file -> ( Some ca_file , None ) | ` Ca_path ca_path -> ( None , Some ca_path ) | ` Search_file_first_then_path ( ` File ca_file , ` Path ca_path ) -> ( Some ca_file , Some ca_path ) in ( crt , key , ca_file , ca_path ) in let cfg = Ssl . Config . create ? ca_file ? ca_path ~ crt_file ~ key_file ( ) in Ssl . listen cfg rd wr >>= fun ( rd , wr ) -> Monitor . protect ( fun ( ) -> handle_request sock rd wr ) ~ finally ( : fun ( ) -> Deferred . all_unit [ Reader . close rd ; Writer . close wr ] ) in Tcp . Server . create ? max_connections ? backlog ? buffer_age_limit ~ on_handler_error where_to_listen ( handle_client handle_request ) |
type ssl_version = Ssl . version [ @@ deriving sexp ] |
type ssl_opt = Ssl . opt [ @@ deriving sexp ] |
type ssl_conn = Ssl . connection [ @@ deriving sexp_of ] |
type allowed_ciphers = [ ` Only of string list | ` Openssl_default | ` Secure ] |
type verify_mode = Ssl . verify_mode [ @@ deriving sexp_of ] |
type session = Ssl . session [ @@ deriving sexp_of ] |
module Ssl = struct module Config = Ssl . Config end |
type _ addr = | OpenSSL : Socket . Address . Inet . t * Ssl . Config . t -> Socket . Address . Inet . t addr | Inet : Socket . Address . Inet . t -> Socket . Address . Inet . t addr | Unix : Socket . Address . Unix . t -> Socket . Address . Unix . t addr |
type _ tcp_sock = | Inet_sock : ( [ ` Active ] , Socket . Address . Inet . t ) Socket . t -> Socket . Address . Inet . t tcp_sock | Unix_sock : ( [ ` Active ] , Socket . Address . Unix . t ) Socket . t -> Socket . Address . Unix . t tcp_sock |
let ssl_schemes = [ " https " ; " wss " ] |
let mem_scheme s = List . mem ssl_schemes ~ equal : String . equal s |
let resolve_uri ( ? options = [ ] ) uri = let host = Option . value_exn ~ here [ :% here ] ~ message " : no host in URL " ( Uri . host uri ) in let service = match ( Uri . port uri , Uri_services . tcp_port_of_uri uri ) with | Some p , _ -> Some ( string_of_int p ) | None , Some p -> Some ( string_of_int p ) | _ -> None in let options = Unix . Addr_info . AI_FAMILY PF_INET :: options in Unix . Addr_info . get ~ host ? service options >>= function | [ ] -> failwithf " unable to resolve % s " ( Uri . to_string uri ) ( ) | { ai_addr ; _ } :: _ -> ( match ( Uri . scheme uri , ai_addr ) with | _ , ADDR_UNIX _ -> invalid_arg " uri must resolve to inet address " | Some s , ADDR_INET ( h , p ) when mem_scheme s -> return ( OpenSSL ( ` Inet ( h , p ) , Ssl . Config . create ( ) ) ) | _ , ADDR_INET ( h , p ) -> return ( Inet ( ` Inet ( h , p ) ) ) ) |
let connect ( type a ) ? interrupt ( addr : a addr ) : ( a tcp_sock * Reader . t * Writer . t ) Deferred . t = match addr with | Inet addr -> Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_inet_address addr ) >>| fun ( s , r , w ) -> ( Inet_sock s , r , w ) | OpenSSL ( addr , cfg ) -> Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_inet_address addr ) >>= fun ( s , rd , wr ) -> Ssl . connect ~ cfg rd wr >>| fun ( rd , wr ) -> ( Inet_sock s , rd , wr ) | Unix addr -> Tcp . connect ? interrupt ( Tcp . Where_to_connect . of_unix_address addr ) >>| fun ( s , r , w ) -> ( Unix_sock s , r , w ) |
let with_connection ( type a ) ? interrupt ( addr : a addr ) ( f : a tcp_sock -> Reader . t -> Writer . t -> ' a Deferred . t ) = match addr with | Inet addr -> Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_inet_address addr ) ( fun s rd wr -> f ( Inet_sock s ) rd wr ) | OpenSSL ( addr , cfg ) -> Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_inet_address addr ) ( fun s rd wr -> Ssl . connect ~ cfg rd wr >>= fun ( rd , wr ) -> Monitor . protect ( fun ( ) -> f ( Inet_sock s ) rd wr ) ~ finally ( : fun ( ) -> Deferred . all_unit [ Reader . close rd ; Writer . close wr ] ) ) | Unix addr -> Tcp . with_connection ? interrupt ( Tcp . Where_to_connect . of_unix_address addr ) ( fun s rd wr -> f ( Unix_sock s ) rd wr ) |
let connect_uri ? options ? interrupt uri = resolve_uri ? options uri >>= fun addr -> connect ? interrupt addr |
let with_connection_uri ? options ? interrupt uri f = resolve_uri ? options uri >>= fun addr -> with_connection ? interrupt addr f |
type trust_chain = [ ` Ca_file of string | ` Ca_path of string | ` Search_file_first_then_path of [ ` File of string ] * [ ` Path of string ] ] |
type openssl = [ ` OpenSSL of [ ` Crt_file_path of string ] * [ ` Key_file_path of string ] ] |
type requires_async_ssl = [ openssl | ` OpenSSL_with_trust_chain of openssl * trust_chain ] |
type server = [ ` TCP | requires_async_ssl ] [ @@ deriving sexp ] |
let serve ? max_connections ? backlog ? buffer_age_limit ~ on_handler_error mode where_to_listen handle_request = let handle_client handle_request sock rd wr = match mode with | ` TCP -> handle_request sock rd wr | # requires_async_ssl as async_ssl -> let crt_file , key_file , ca_file , ca_path = match async_ssl with | ` OpenSSL ( ` Crt_file_path crt_file , ` Key_file_path key_file ) -> ( crt_file , key_file , None , None ) | ` OpenSSL_with_trust_chain ( ` OpenSSL ( ` Crt_file_path crt , ` Key_file_path key ) , trust_chain ) -> let ca_file , ca_path = match trust_chain with | ` Ca_file ca_file -> ( Some ca_file , None ) | ` Ca_path ca_path -> ( None , Some ca_path ) | ` Search_file_first_then_path ( ` File ca_file , ` Path ca_path ) -> ( Some ca_file , Some ca_path ) in ( crt , key , ca_file , ca_path ) in let cfg = Ssl . Config . create ? ca_file ? ca_path ~ crt_file ~ key_file ( ) in Ssl . listen cfg rd wr >>= fun ( rd , wr ) -> Monitor . protect ( fun ( ) -> handle_request sock rd wr ) ~ finally ( : fun ( ) -> Deferred . all_unit [ Reader . close rd ; Writer . close wr ] ) in Tcp . Server . create ? max_connections ? backlog ? buffer_age_limit ~ on_handler_error where_to_listen ( handle_client handle_request ) |
type ssl_version = Ssl . version [ @@ deriving sexp ] |
type ssl_opt = Ssl . opt [ @@ deriving sexp ] |
type ssl_conn = Ssl . connection [ @@ deriving sexp_of ] |
type allowed_ciphers = [ ` Only of string list | ` Openssl_default | ` Secure ] |
type verify_mode = Ssl . verify_mode [ @@ deriving sexp_of ] |
type session = Ssl . session [ @@ deriving sexp_of ] |
module Ssl = struct module Config = Ssl . Config end |
module VAE = struct type t = { fc1 : Layer . t ; fc21 : Layer . t ; fc22 : Layer . t ; fc3 : Layer . t ; fc4 : Layer . t } let create vs = { fc1 = Layer . linear vs ~ input_dim : 784 400 ; fc21 = Layer . linear vs ~ input_dim : 400 20 ; fc22 = Layer . linear vs ~ input_dim : 400 20 ; fc3 = Layer . linear vs ~ input_dim : 20 400 ; fc4 = Layer . linear vs ~ input_dim : 400 784 } let encode t xs = let h1 = Layer . forward t . fc1 xs |> Tensor . relu in Layer . forward t . fc21 h1 , Layer . forward t . fc22 h1 let decode t zs = Layer . forward t . fc3 zs |> Tensor . relu |> Layer . forward t . fc4 |> Tensor . sigmoid let forward t xs = let mu , logvar = encode t ( Tensor . view xs ~ size [ : - 1 ; 784 ] ) in let std_ = Tensor . ( exp ( logvar * f 0 . 5 ) ) in let eps = Tensor . randn_like std_ in decode t Tensor . ( mu + ( eps * std_ ) ) , mu , logvar end |
let loss ~ recon_x ~ x ~ mu ~ logvar = let bce = Tensor . bce_loss recon_x ~ targets ( : Tensor . view x ~ size [ : - 1 ; 784 ] ) ~ reduction : Sum in let kld = Tensor . ( f ( - 0 . 5 ) * ( f 1 . 0 + logvar - ( mu * mu ) - exp logvar ) |> sum ) in Tensor . ( + ) bce kld |
let write_samples samples ~ filename = let samples = Tensor . ( samples * f 256 . ) in List . init 8 ~ f ( : fun i -> List . init 8 ~ f ( : fun j -> Tensor . narrow samples ~ dim : 0 ~ start ( ( : 4 * i ) + j ) ~ length : 1 ) |> Tensor . cat ~ dim : 2 ) |> Tensor . cat ~ dim : 3 |> Torch_vision . Image . write_image ~ filename |
let ( ) = let device = Device . cuda_if_available ( ) in let mnist = Mnist_helper . read_files ( ) in let vs = Var_store . create ~ name " : vae " ~ device ( ) in let vae = VAE . create vs in let opt = Optimizer . adam vs ~ learning_rate : 1e - 3 in for epoch_idx = 1 to 20 do let train_loss = ref 0 . in let samples = ref 0 . in Dataset_helper . iter mnist ~ batch_size ~ device ~ f ( : fun _ ~ batch_images ~ batch_labels : _ -> let recon_x , mu , logvar = VAE . forward vae batch_images in let loss = loss ~ recon_x ~ x : batch_images ~ mu ~ logvar in Optimizer . backward_step ~ loss opt ; train_loss := ! train_loss . + Tensor . float_value loss ; samples := ! samples . + ( Tensor . shape batch_images |> List . hd_exn |> Float . of_int ) ) ; Stdio . printf " epoch % 4d loss : % 12 . 6f \ n " %! epoch_idx ( ! train_loss . / ! samples ) ; Tensor . randn [ 64 ; 20 ] ~ device |> VAE . decode vae |> Tensor . to_device ~ device : Cpu |> Tensor . view ~ size [ : - 1 ; 1 ; 28 ; 28 ] |> write_samples ~ filename ( : Printf . sprintf " s_ % d . png " epoch_idx ) done |
module QRCode = struct type t = { source : Uuidm . t ; value : string ; } let create ~ source ~ value = { source ; value ; } let check t s = t . value = s let compare = compare let source t = t . source let value t = t . value end |
module User = struct type _t = { id : string ; source : Uuidm . t ; } type t = [ ` Granted of _t | ` Denied of _t | ` Unknown ] let granted ~ id ~ source = ` Granted { id ; source ; } let denied ~ id ~ source = ` Denied { id ; source ; } end |
module Event : sig type kind = [ ` QRCode of QRCode . t | ` User of User . t | ` Nil ] type qrcode = [ ` QRCode of QRCode . t ] type user = [ ` User of User . t ] type nil = [ ` Nil ] type ' a t val event : ' a t -> ' a val qrcode : QRCode . t -> [ > qrcode ] t val user : User . t -> [ > user ] t val nil : unit -> [ > nil ] t type kind = [ ` QRCode of QRCode . t | ` User of User . t | ` Nil ] type qrcode = [ ` QRCode of QRCode . t ] type user = [ ` User of User . t ] type nil = [ ` Nil ] type ' a t = { event : ' a ; timestamp : float ; } let create event = { event = event ; timestamp = Unix . gettimeofday ( ) ; } let event t = t . event let qrcode qr = create @@ ` QRCode qr let user u = create @@ ` User u let nil ( ) = create ` Nil end |
module UserDB : sig val create : int -> string array * int SMap . t let random_string len = let true_len = len / 8 * 8 + 8 in let b = Bytes . create true_len in for i = 0 to true_len / 8 - 1 do EndianBytes . BigEndian . set_int64 b ( i * 8 ) @@ Random . int64 Int64 . max_int done ; Bytes . ( sub b 0 len |> unsafe_to_string ) let create n = let user_to_qr = Array . make n " " in let rec generate a = function | 0 -> a | n -> let qrcode = random_string 10 in user_to_qr . ( n - 1 ) <- qrcode ; generate ( SMap . add qrcode ( n - 1 ) a ) @@ pred n in user_to_qr , generate SMap . empty n end |
type ' a t = ( ' a , Error . t Preface . Nonempty_list . t ) Preface . Validation . t |
let valid x = Preface . Validation . Valid x |
let invalid x = Preface . Validation . Invalid x |
let error x = invalid ( Preface . Nonempty_list . create x ) |
let pp inner_pp = Preface . ( Validation . pp inner_pp ( Nonempty_list . pp Error . pp ) ) |
let equal inner_eq = Preface . ( Validation . equal inner_eq ( Nonempty_list . equal Error . equal ) ) ; ; |
let to_try = function | Preface . Validation . Valid x -> Ok x | Preface . Validation . Invalid errs -> Error ( Error . List errs ) ; ; |
let from_try = function | Ok x -> Preface . Validation . Valid x | Error err -> Preface . ( Validation . Invalid ( Nonempty_list . create err ) ) ; ; |
module Error_list = Preface . Make . Semigroup . From_alt ( Preface . Nonempty_list . Alt ) ( Error ) |
module Functor = Preface . Validation . Functor ( Error_list ) |
module Applicative = Preface . Validation . Applicative ( Error_list ) |
module Selective = Preface . Validation . Selective ( Error_list ) |
module Monad = Preface . Validation . Monad ( Error_list ) |
module Alt = Preface . Validation . Alt ( Error_list ) |
module Infix = struct type nonrec ' a t = ' a t include ( Alt . Infix : Preface . Specs . Alt . INFIX with type ' a t := ' a t ) include ( Selective . Infix : Preface . Specs . Selective . INFIX with type ' a t := ' a t ) include ( Monad . Infix : Preface . Specs . Monad . INFIX with type ' a t := ' a t ) end |
module Syntax = struct type nonrec ' a t = ' a t include ( Applicative . Syntax : Preface . Specs . Applicative . SYNTAX with type ' a t := ' a t ) include ( Monad . Syntax : Preface . Specs . Monad . SYNTAX with type ' a t := ' a t ) end |
module type Raw = Raw |
type ( ' raw , ' witness ) t = ' raw |
module type S = S with type ( ' a , ' b ) validated := ( ' a , ' b ) t |
module type S_bin_io = S_bin_io with type ( ' a , ' b ) validated := ( ' a , ' b ) t |
module type S_bin_io_compare_hash_sexp = S_bin_io_compare_hash_sexp with type ( ' a , ' b ) validated := ( ' a , ' b ) t |
let raw t = t |
module Make ( Raw : Raw ) = struct type witness type t = Raw . t [ @@ deriving sexp_of ] let validation_failed t error = Error . create " validation failed " ( t , error , Raw . here ) [ % sexp_of : Raw . t * Error . t * Source_code_position . t ] ; ; let create_exn t = match Validate . result ( Raw . validate t ) with | Ok ( ) -> t | Error error -> Error . raise ( validation_failed t error ) ; ; let create t = match Validate . result ( Raw . validate t ) with | Ok ( ) -> Ok t | Error error -> Error ( validation_failed t error ) ; ; let t_of_sexp sexp = create_exn ( Raw . t_of_sexp sexp ) let raw t = t end |
module Add_bin_io ( Raw : sig type t [ @@ deriving bin_io ] include Raw_bin_io with type t := t end ) ( Validated : S with type raw := Raw . t ) = struct include Binable . Of_binable_without_uuid [ @ alert " - legacy " ] ( Raw ) ( struct type t = Raw . t let of_binable raw = if Raw . validate_binio_deserialization then Validated . create_exn raw else raw ; ; let to_binable = Fn . id end ) end |
module Add_compare ( Raw : sig type t [ @@ deriving compare ] include Raw with type t := t end ) ( Validated : S with type raw := Raw . t ) = struct let compare t1 t2 = [ % compare : Raw . t ] ( raw t1 ) ( raw t2 ) end |
module Add_hash ( Raw : sig type t [ @@ deriving hash ] include Raw with type t := t end ) ( Validated : S with type raw := Raw . t ) = struct let hash_fold_t state t = Raw . hash_fold_t state ( Validated . raw t ) let hash t = Raw . hash ( Validated . raw t ) end |
module Add_typerep ( Raw : sig type t [ @@ deriving typerep ] include Raw with type t := t end ) ( Validated : S with type raw := Raw . t ) = struct type t = Raw . t [ @@ deriving typerep ] end |
module Make_binable ( Raw : Raw_bin_io ) = struct module T0 = Make ( Raw ) include T0 include Add_bin_io ( Raw ) ( T0 ) end |
module Make_bin_io_compare_hash_sexp ( Raw : sig type t [ @@ deriving compare , hash ] include Raw_bin_io with type t := t end ) = struct module T = Make_binable ( Raw ) include T include Add_compare ( Raw ) ( T ) include ( Add_hash ( Raw ) ( T ) : sig type t [ @@ deriving hash ] end with type t := t ) end |
type t = Block . t State_hash . With_state_hashes . t * State_hash . t Non_empty_list . t |
let to_yojson ( block_with_hashes , _ ) _ = State_hash . With_state_hashes . to_yojson Block . to_yojson block_with_hashes |
let lift ( b , v ) v = match v with | _ , _ , _ , ( ` Delta_block_chain , Truth . True delta_block_chain_proof ) delta_block_chain_proof , _ , _ , _ -> ( b , delta_block_chain_proof ) delta_block_chain_proof |
let forget ( b , _ ) _ = b |
let remember ( b , delta_block_chain_proof ) delta_block_chain_proof = ( b , ( ( ` Time_received , Truth . True ( ) ) , ( ` Genesis_state , Truth . True ( ) ) , ( ` Proof , Truth . True ( ) ) , ( ` Delta_block_chain , Truth . True delta_block_chain_proof ) delta_block_chain_proof , ( ` Frontier_dependencies , Truth . True ( ) ) , ( ` Staged_ledger_diff , Truth . True ( ) ) , ( ` Protocol_versions , Truth . True ( ) ) ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.