### Httpev: Implement Async HTTP Server with Lwt Source: https://context7.com/ahrefs/devkit/llms.txt Shows how to build an asynchronous HTTP server using Httpev and Lwt. This example includes handlers for '/', '/json', and '/user' paths, demonstrating Lwt-based responses and parameter extraction using the Httpev.Args functor. ```ocaml open Devkit (* Lwt-based HTTP server *) let () = let handler _server req = let open Httpev.Answer in match req.Httpev.path with | "/" -> text "Hello from Lwt server!" | "/json" -> json {|{"status": "ok"}|} | "/user" -> let module Arg = Httpev.Args(struct let req = req end) in let name = Arg.str ~default:"anonymous" "name" in printf "Hello, %s!" name | _ -> not_found "Page not found" in Httpev.server_lwt { Httpev.default with connection = Unix.ADDR_INET (Unix.inet_addr_any, 8080); } handler ``` -------------------------------- ### OCaml Package Installation with Opam Source: https://github.com/ahrefs/devkit/blob/master/README.md This command demonstrates how to install the devkit library using the Opam package manager. It's the standard way to add the library as a dependency for OCaml projects. ```sh opam install devkit ``` -------------------------------- ### OCaml Project Dependency Installation with Opam Source: https://github.com/ahrefs/devkit/blob/master/README.md These commands show how to install OCaml project dependencies using Opam. The first installs dependencies for the current switch, while the second creates a new local switch with dependencies and tests enabled. ```sh opam install . --deps-only opam switch create . --deps-only --no-install opam install . --deps-only --with-test ``` -------------------------------- ### Format Timestamps and Durations using Devkit Time Module in OCaml Source: https://context7.com/ahrefs/devkit/llms.txt Provides examples of using the Devkit Time module for various time-related operations. It covers getting the current time, formatting timestamps into different standards (ISO 8601, RFC 2822, etc.), and formatting durations in human-readable and compact forms. Also shows parsing compact durations and performing time arithmetic. ```ocaml open Devkit (* Get current time *) let now = Time.now () let () = Printf.printf "Current timestamp: %.3f\n" now (* Format timestamps *) let () = Printf.printf "ISO 8601: %s\n" (Time.to_string now); Printf.printf "ISO 8601 GMT: %s\n" (Time.gmt_string now); Printf.printf "ISO 8601 with ms: %s\n" (Time.gmt_string_ms now); Printf.printf "RFC 2822: %s\n" (Time.to_rfc2822 now); Printf.printf "Date only (YYYY-MM-DD): %s\n" (Time.date_w3_gmt_string now); Printf.printf "Compact (YYYYMMDD): %s\n" (Time.date8_gmt_string now); Printf.printf "Basic format: %s\n" (Time.basic_gmt_string now) (* Duration formatting *) let duration = 3661.5 (* 1 hour, 1 minute, 1.5 seconds *) let () = Printf.printf "Full: %s\n" (Time.show_duration duration); (* "1 hour 1 minute 1 second" *) Printf.printf "Compact: %s\n" (Time.compact_duration duration); (* "1h01m01s" *) Printf.printf "Cut to 2: %s\n" (Time.show_duration ~cut:2 duration) (* "1 hour 1 minute" *) (* Parse compact duration *) let seconds = Time.of_compact_duration "2h30m" (* 9000.0 *) let () = Printf.printf "Parsed: %.0f seconds\n" seconds (* Time arithmetic *) let one_hour = Time.hours 1 (* 3600.0 *) let one_day = Time.days 1 (* 86400.0 *) let five_min = Time.minutes 5 (* 300.0 *) (* Convert to units *) let hours = Time.to_hours 7200.0 (* 2 *) let days = Time.to_days 172800.0 (* 2 *) (* Round to boundaries *) let rounded = Time.round_hours now (* Round to hour boundary *) (* Time since *) let startup = Time.now () let () = Unix.sleep 2; Printf.printf "Uptime: %s\n" (Time.ago_str startup) (* Day boundaries *) let start = Time.start_of_day now let finish = Time.end_of_day now ``` -------------------------------- ### String Formatting Helpers (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Provides examples of using Stre module functions to format lists and arrays into string representations, useful for debugging and logging. ```ocaml open Devkit (* Formatting helpers *) let list_str = Stre.list string_of_int [1;2;3] (* "[1;2;3]" *) let arr_str = Stre.array string_of_int [|1;2;3|] (* "[|1;2;3|]" *) ``` -------------------------------- ### Httpev: Use Args Functor for Typed Parameter Access Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates the use of the `Httpev.Args` functor for type-safe access to request parameters. This example shows how to retrieve string, integer, and boolean parameters with default values and includes error handling for bad parameter formats. ```ocaml (* Using the Args functor for typed parameter access *) let handler _server req reply = let module Arg = Httpev.Args(struct let req = req end) in try let name = Arg.str "name" in let age = Arg.int ~default:0 "age" in let active = Arg.bool ~default:true "active" in reply (`Ok, [], Printf.sprintf "Name: %s, Age: %d, Active: %b" name age active) with Httpev.Param.Bad param -> reply (`Bad_request, [], Printf.sprintf "Bad parameter: %s" param) ``` -------------------------------- ### OCaml Distributed Tracing with OpenTelemetry and Lwt Source: https://github.com/ahrefs/devkit/blob/master/README.md This example illustrates setting up distributed tracing using OpenTelemetry with an Lwt backend (cohttp-lwt). It configures ambient context storage and the OpenTelemetry backend, then runs an Lwt application that performs an HTTP request, ensuring trace parentage propagation. ```ocaml open Devkit let run () = let* resp = Web.http_request_lwt `GET "http://icanhazip.com" in (* ... *) let () = Ambient_context.set_storage_provider (Ambient_context_lwt.storage ()) ; Opentelemetry_trace.setup_with_otel_backend (Opentelemetry_client_cohttp_lwt.create_backend ()) @@ fun () -> Lwt_main.run @@ fun () -> run () ``` -------------------------------- ### HTTP Client Operations with Devkit Web Module (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates various HTTP client operations using Devkit's Web module in OCaml. Supports GET, POST, PUT, PATCH, DELETE methods, form and JSON data, custom headers, timeouts, and both blocking and Lwt-based asynchronous requests. Includes URL and HTML encoding/decoding utilities. ```ocaml open Devkit (* Simple GET request - blocking *) let () = match Web.http_request `GET "https://httpbin.org/get" with | `Ok body -> print_endline body | `Error msg -> Printf.eprintf "Error: %s\n" msg (* POST request with form data *) let () = let body = `Form [("name", "value"); ("foo", "bar")] in match Web.http_request ~body `POST "https://httpbin.org/post" with | `Ok response -> print_endline response | `Error msg -> Printf.eprintf "Error: %s\n" msg (* POST with raw JSON body *) let () = let body = `Raw ("application/json", {|{"key": "value"}|}) in match Web.http_request ~body `POST "https://httpbin.org/post" with | `Ok response -> print_endline response | `Error msg -> Printf.eprintf "Error: %s\n" msg (* Request with custom headers and timeout *) let () = match Web.http_request ~timeout:30 ~headers:["Authorization: Bearer token123"; "X-Custom: value"] ~ua:"MyApp/1.0" `GET "https://api.example.com/data" with | `Ok body -> print_endline body | `Error msg -> Printf.eprintf "Error: %s\n" msg (* Lwt-based async request *) let%lwt () = match%lwt Web.http_request_lwt `GET "https://httpbin.org/get" with | `Ok body -> Lwt_io.printl body | `Error msg -> Lwt_io.eprintlf "Error: %s" msg (* URL encoding/decoding utilities *) let encoded = Web.urlencode "hello world" (* "hello+world" *) let decoded = Web.urldecode "hello+world" (* "hello world" *) let raw_encoded = Web.rawurlencode "hello world" (* "hello%20world" *) let html_safe = Web.htmlencode "" ``` -------------------------------- ### Updating Ragel-Generated Code Source: https://github.com/ahrefs/devkit/blob/master/README.md This command updates code generated by Ragel, a state machine compiler. It first ensures Ragel is installed via aptitude and then runs `make -B gen_ragel` to regenerate the necessary files. ```sh aptitude install ragel make -B gen_ragel ``` -------------------------------- ### Utilize Object Reuse Pool for Buffers in OCaml Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates the use of Devkit's Cache.Reuse module to manage an object pool for Buffer.t instances. This pattern improves performance by reusing buffer objects instead of creating new ones. It covers getting a buffer, using it, and releasing it back to the pool. ```ocaml open Devkit (* Object reuse pool *) module BufferPool = Cache.Reuse(struct type t = Buffer.t let create () = Buffer.create 1024 let reset buf = Buffer.clear buf end) let () = let buf = BufferPool.get () in Buffer.add_string buf "Hello"; let result = Buffer.contents buf in BufferPool.release buf; (* Return to pool for reuse *) print_endline result ``` -------------------------------- ### Log: Create and Use Logging Facilities Source: https://context7.com/ahrefs/devkit/llms.txt Shows how to create named logging facilities using `Log.from` and log messages at different levels (info, debug, warn, error). This snippet illustrates basic logging and logging with exceptions, including the option to include backtraces. ```ocaml open Devkit (* Create a logging facility *) let http_log = Log.from "http" db_log = Log.from "database" (* Basic logging at different levels *) let () = http_log#info "Server started on port %d" 8080; http_log#debug "Processing request %s" "/api/users"; http_log#warn "Slow response time: %.2fs" 2.5; http_log#error "Connection failed to %s" "localhost:5432" (* Logging with exceptions *) let process_request () = try failwith "Something went wrong" with exn -> http_log#error ~exn "Request processing failed"; http_log#error ~exn ~backtrace:true "With backtrace" ``` -------------------------------- ### Httpev: Implement Simple HTTP Server with libevent Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates how to create a basic HTTP server using the Httpev module with libevent for synchronous request handling. It defines handlers for different paths like '/', '/json', and '/echo', and configures the server connection and debug mode. ```ocaml open Devkit (* Simple HTTP server with libevent *) let () = let handler _server req reply = match req.Httpev.path with | "/" -> reply (`Ok, [("Content-Type", "text/plain")], "Hello, World!") | "/json" -> let json = {|{"status": "ok", "message": "Hello"}|} in reply (`Ok, [("Content-Type", "application/json")], json) | "/echo" -> let body = req.Httpev.body in reply (`Ok, [("Content-Type", "text/plain")], body) | _ -> reply (`Not_found, [], "Not Found") in Httpev.server { Httpev.default with connection = Unix.ADDR_INET (Unix.inet_addr_loopback, 8080); debug = true; } handler ``` -------------------------------- ### Timer and Memory/Bytes Formatting (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates the usage of the Action.timer for measuring execution time and formatting byte sizes into human-readable strings (KB, MB, GB). It also shows how to parse byte strings. ```ocaml open Devkit (* Timer for measuring execution time *) let timer = new Action.timer let () = timer#mark "start"; Unix.sleep 1; timer#mark "after_sleep"; Printf.printf "Elapsed: %s\n" timer#get_str; Printf.printf "Details: %s\n" timer#show (* Memory/bytes formatting *) let () = Printf.printf "%s\n" (Action.bytes_string 1536); (* "1.5KB" *) Printf.printf "%s\n" (Action.bytes_string (1024 * 1024 * 512)); (* "512MB" *) let bytes = Action.parse_bytes_unit "1.5GB" (* 1610612736 *) ``` -------------------------------- ### String Before/After and Pattern Matching (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates functions for extracting parts of a string before or after a delimiter, and for pattern matching using prefix, suffix, and existence checks. It also covers case-insensitive comparisons and manipulations. ```ocaml open Devkit (* Before/after (safe, no exceptions) *) let domain = Stre.after "user@example.com" "@" (* "example.com" *) let user = Stre.before "user@example.com" "@" (* "user" *) let (left, right) = Stre.divide "key:value" ":" (* ("key", "value") *) (* Pattern matching *) let matches = Stre.starts_with "hello world" "hello" (* true *) let ends = Stre.ends_with "file.txt" ".txt" (* true *) let contains = Stre.exists "hello world" "wor" (* true *) (* Case-insensitive operations *) let ieq = Stre.iequal "Hello" "hello" (* true *) let icontains = Stre.iexists "Hello World" "world" (* true *) let istarts = Stre.istarts_with "Hello" "HEL" (* true *) ``` -------------------------------- ### Benchmarking Utility (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Shows how to use Action.run_bench to benchmark the performance of different code snippets, comparing execution times for string concatenation and sprintf formatting. ```ocaml open Devkit (* Benchmarking *) let () = Action.run_bench 1000 [ "string_concat", (fun () -> "a" ^ "b" ^ "c"); "sprintf", (fun () -> Printf.sprintf "%s%s%s" "a" "b" "c"); ] ``` -------------------------------- ### Daemon Management with Devkit Source: https://context7.com/ahrefs/devkit/llms.txt Utilities for creating and managing Unix daemon processes. Handles command-line arguments, initialization, logging, signal handling, and Lwt-based operation. ```ocaml open Devkit (* Command-line arguments for daemon *) let () = Arg.parse Daemon.args (fun _ -> ()) "Usage: myapp [options]" (* Provides: -loglevel, -logfile, -pidfile, -runas, -fg *) (* Initialize daemon with standard setup *) let () = Daemon.manage (); (* This will: - Check/create pidfile - Daemonize (unless -fg) - Switch user (if -runas) - Setup log file - Install signal handlers - Raise resource limits *) Log.main#info "Daemon started" (* Check if daemon should exit *) let () = while Daemon.should_run () do (* Do work *) Unix.sleep 1 done; Log.main#info "Daemon shutting down" (* Lwt-based exit handling *) let () = Lwt_main.run begin let rec main_loop () = let%lwt () = Lwt_unix.sleep 1.0 in (* Do work *) main_loop () in (* Run until exit signal *) Lwt.pick [ Daemon.wait_exit (); (* Raises ShouldExit on signal *) main_loop () ] end (* Graceful shutdown pattern *) let () = let cleanup () = Log.main#info "Cleaning up..."; (* Close connections, flush buffers, etc. *) in Signal.set_exit (fun () -> cleanup (); Daemon.signal_exit () ); (* Or in Lwt: *) let%lwt () = Daemon.unless_exit (do_work ()) in cleanup () ``` -------------------------------- ### Resource Management with OCaml Control Module Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates resource management using the Control module, focusing on safe file I/O and generic bracket patterns. It covers reading/writing text and binary files, copying files, managing network connections, and handling temporary files. Dependencies include the Devkit library and ExtLib. ```ocaml open Devkit (* Bracket pattern for automatic cleanup *) let read_file path = Control.with_open_in_txt path (fun ch -> really_input_string ch (in_channel_length ch) ) let write_file path content = Control.with_open_out_txt path (fun ch -> output_string ch content ) (* Binary file operations *) let copy_binary src dst = Control.with_open_in_bin src (fun ic -> Control.with_open_out_bin dst (fun oc -> let buf = Bytes.create 4096 in let rec loop () = let n = input ic buf 0 4096 in if n > 0 then begin output oc buf 0 n; loop () end in loop () ) ) (* Generic bracket *) let with_connection host port f = let fd = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Control.bracket fd Unix.close (fun fd -> Unix.connect fd (Unix.ADDR_INET (Unix.inet_addr_of_string host, port)); f fd ) (* IO operations with ExtLib *) let () = Control.with_input_bin "/etc/passwd" (fun io -> let line = IO.read_line io in print_endline line ) (* Temp file operations *) let () = Control.with_open_out_temp_bin (fun (path, ch) -> output_string ch "temporary data"; Printf.printf "Temp file: %s\n" path ) (* File automatically closed, but not deleted *) (* Wrapped output to string *) let json_string = Control.wrapped_outs (fun io -> IO.nwrite io {|{"key": "value"}|} ) ``` -------------------------------- ### File and Periodic Execution Utilities (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates functions for reading lines from files, parsing configuration files (ignoring comments and empty lines), and executing a function periodically at a specified interval. ```ocaml open Devkit (* File utilities *) let lines = Action.file_lines "/etc/hosts" let config = Action.config_lines "config.txt" (* Skips comments and empty lines *) (* Periodic execution *) let periodic_log = Action.period 100 (fun i -> Printf.printf "Called %d times\n" i ) let () = for _ = 1 to 500 do periodic_log () (* Only prints every 100th call *) done ``` -------------------------------- ### Log: Configure Log Levels and Filters Source: https://context7.com/ahrefs/devkit/llms.txt Details how to configure logging levels and filters for the Log module. It demonstrates setting global filters, facility-specific filters using wildcards, and configuring levels from environment variables or directly using `Log.set_loglevels`. ```ocaml (* Set log levels *) let () = Log.set_filter `Warn; (* Global: only warn and above *) Log.set_filter ~name:"http" `Debug; (* http facility: debug and above *) Log.set_filter ~name:"db*" `Info; (* All facilities starting with "db" *) (* Configure from environment variable DEVKIT_LOG *) (* Example: DEVKIT_LOG="debug,http=info,db*=warn" *) let () = Log.read_env_config () (* Set log levels from string *) let () = Log.set_loglevels "info,http=debug,database=warn" ``` -------------------------------- ### String Prefix/Suffix Removal and Replacement (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Shows how to remove specified prefixes and suffixes from strings, and how to perform global replacement of substrings within a string using the Stre module. ```ocaml open Devkit (* Prefix/suffix manipulation *) let no_prefix = Stre.drop_prefix "/api/users" "/api" (* "/users" *) let no_suffix = Stre.drop_suffix "file.txt" ".txt" (* "file" *) (* String replacement *) let replaced = Stre.replace_all ~str:"hello world" ~sub:"world" ~by:"OCaml" ``` -------------------------------- ### Implement LRU Cache with Generational Eviction in OCaml Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates the creation and usage of an LRU cache for strings with generational eviction. It covers adding, retrieving, checking membership, and removing entries, along with accessing cache statistics. Requires the Devkit library. ```ocaml open Devkit (* LRU Cache with generational eviction *) module StringCache = Cache.LRU(struct type t = string let equal = String.equal let hash = Hashtbl.hash end) let cache = StringCache.create 1000 (* max 1000 entries *) let () = (* Add entries *) StringCache.put cache "key1" "value1"; StringCache.put cache "key2" "value2"; (* Get entries (promotes to LFU on hit) *) begin match StringCache.get cache "key1" with | value -> Printf.printf "Found: %s\n" value | exception Not_found -> print_endline "Not found" end; (* Check membership *) if StringCache.mem cache "key1" then print_endline "key1 exists"; (* Remove entry *) StringCache.remove cache "key2"; (* Cache statistics *) Printf.printf "Hits: %d, Misses: %d, Size: %d\n" (StringCache.hit cache) (StringCache.miss cache) (StringCache.size cache) ``` -------------------------------- ### Log: Configure Timestamp and Output Source: https://context7.com/ahrefs/devkit/llms.txt Explains how to configure the logging output for the Log module. This includes setting timestamps to use UTC and redirecting all log output to a specified file descriptor. ```ocaml (* Use UTC timezone for timestamps *) let () = Log.set_utc () (* Redirect log output to file *) let () = let ch = open_out "/var/log/myapp.log" in Log.State.log_ch := ch ``` -------------------------------- ### Common Functional Utilities with Prelude Module Source: https://context7.com/ahrefs/devkit/llms.txt Provides common functional programming utilities and operators automatically included with Devkit. Includes function composition, option helpers, tuple operations, currying, reference operators, list accumulation, lazy forcing, and safe integer parsing. ```ocaml open Devkit (* Function composition *) let string_length_doubled = (( * ) 2) $ String.length let () = Printf.printf "%d\n" (string_length_doubled "hello") (* 10 *) (* Double composition for comparisons *) let compare_lengths = compare $$ String.length let () = let result = compare_lengths "hello" "hi" in Printf.printf "Compare: %d\n" result (* positive, "hello" longer *) (* Identity and flip *) let x = id 42 (* 42 *) let sub_flipped = flip (-) in Printf.printf "%d\n" (sub_flipped 3 10) (* 7, i.e., 10 - 3 *) (* Option helpers *) let opt = some 42 (* Some 42 *) let getter = const 42 in Printf.printf "%d\n" (getter ()) (* 42 *) (* Tuple operations *) let (a, b) = apply2 String.uppercase_ascii ("hello", "world") (* ("HELLO", "WORLD") *) (* Currying *) let add_pair (a, b) = a + b let add_curried = curry add_pair let () = Printf.printf "%d\n" (add_curried 1 2) (* 3 *) (* Reference operators *) let counter = ref 0 let () = counter += 5; (* counter is now 5 *) counter -= 2; (* counter is now 3 *) Printf.printf "Counter: %d\n" !counter (* List accumulation *) let items = ref [] let () = tuck items "first"; tuck items "second"; Printf.printf "%s\n" (String.concat ", " !items) (* "second, first" *) (* Lazy forcing *) let lazy_value = lazy (expensive_computation ()) let result = !!lazy_value (* Same as Lazy.force *) (* Printf to stdout/stderr with newline *) let () = printfn "Hello %s!" "World"; eprintfn "Error: %s" "something went wrong" (* Safe integer parsing *) let n = atoi "count" "42" (* 42 *) (* let _ = atoi "count" "abc" (* raises Failure "count \"abc\" not integer" *) *) ``` -------------------------------- ### String Splitting and Substring Operations (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates various string splitting and substring extraction methods provided by the Stre module, including splitting by characters, spaces, and lines, as well as extracting prefixes, suffixes, and middle parts of strings. It also shows safe slicing with negative indices. ```ocaml open Devkit (* String splitting *) let parts = Stre.nsplitc "a,b,c,d" ',' (* ["a"; "b"; "c"; "d"] *) let words = Stre.split Stre.by_space "hello world" (* ["hello"; "world"] *) let lines = Stre.split Stre.by_lines "line1\nline2\r\nline3" (* Substrings *) let prefix = Stre.upto "hello world" 5 (* "hello" *) let suffix = Stre.from "hello world" 6 (* "world" *) let middle = Stre.from_to "hello world" 2 7 (* "llo w" *) (* Safe slicing (no exceptions) *) let sliced = Stre.slice ~first:2 ~last:(-2) "hello" (* "ll" *) let negative = Stre.slice ~first:(-3) "hello" (* "llo" *) (* String splitting with delimiter *) let (before, after) = Stre.splitc "key=value" '=' (* ("key", "value") *) let (path, ext) = Stre.rsplitc "file.tar.gz" '.' (* ("file.tar", "gz") *) ``` -------------------------------- ### Unix Utilities with Nix Module Source: https://context7.com/ahrefs/devkit/llms.txt Provides Unix system programming utilities including process management, networking, and file operations. Supports daemonization, PID file management, forking, socket address parsing, and executing external commands. ```ocaml open Devkit (* Daemonize process *) let () = Nix.daemonize (); (* Now running as daemon with new session *) (* PID file management *) let () = Nix.check_pidfile "/var/run/myapp.pid"; (* Exit if already running *) Nix.write_pidfile "/var/run/myapp.pid"; at_exit (fun () -> Sys.remove "/var/run/myapp.pid") (* Or managed pidfile (auto-cleanup) *) let () = Nix.manage_pidfile "/var/run/myapp.pid" (* Fork process *) let () = match Nix.fork () with | `Child -> Printf.printf "Child PID: %d\n" (Unix.getpid ()); exit 0 | `Forked pid -> Printf.printf "Forked child with PID: %d\n" pid (* Socket address parsing *) let addr = Nix.sockaddr_of_string "localhost:8080" let addr = Nix.sockaddr_of_string "unix:/var/run/app.sock" let addr = Nix.sockaddr_of_string "*:80" (* Any interface *) let addr = Nix.sockaddr_of_string "8080" (* Loopback *) (* Parse host:port *) let (host, port) = Nix.parse_addr_port_exn "example.com:443" (* Execute external commands *) let output = Nix.read_process "ls -la" (* Capture stdout *) let success = Nix.write_process "sort" "b\na\nc" (* Write to stdin *) (* Sleep (fractional seconds) *) let () = Nix.sleep 0.5 (* Raise resource limits *) let () = Nix.raise_limits () (* RLIMIT_CORE and RLIMIT_NOFILE *) (* XDG directories *) let cache_dir = Lazy.force Nix.xdg_cache_dir let config_dir = Lazy.force Nix.xdg_config_dir (* Show socket addresses *) let () = Printf.printf "Listening on: %s\n" (Nix.show_addr (Unix.ADDR_INET (Unix.inet_addr_any, 8080))) ``` -------------------------------- ### List and Array Utilities (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Showcases various utility functions for manipulating lists and arrays, including finding minimum values, removing duplicates, chunking, random selection, slicing, shuffling, and binary search. ```ocaml open Devkit (* List utilities *) let min_val = Action.list_min [3; 1; 4; 1; 5] (* 1 *) let unique = Action.list_uniq Fun.id [1; 2; 2; 3; 3; 3] (* [1; 2; 3] *) let chunks = Action.chunk 2 [1; 2; 3; 4; 5] (* [[1;2]; [3;4]; [5]] *) let random = Action.list_random [1; 2; 3; 4; 5] (* Some random element *) let sliced = Action.slice 1 3 [0; 1; 2; 3; 4] (* [1; 2; 3] *) (* Array utilities *) let () = let arr = [|1; 2; 3; 4; 5|] in Action.shuffle arr; (* In-place shuffle *) let found = Action.binary_search arr compare 3 in (* true *) Printf.printf "Found 3: %b\n" found ``` -------------------------------- ### Httpev: Access Request Parameters Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates how to access request parameters in Httpev handlers. It shows retrieving string and integer parameters using `Httpev.Param.get` and `Httpev.Param.get_int`, with error handling for missing or invalid parameters. ```ocaml (* Accessing request parameters *) let handler _server req reply = let id = Httpev.Param.get req "id" in let count = Httpev.Param.get_int req "count" in match id, count with | Some id, Some n -> reply (`Ok, [], Printf.sprintf "ID: %s, Count: %d" id n) | _ -> reply (`Bad_request, [], "Missing parameters") ``` -------------------------------- ### Implement Counting and Statistics with Devkit in OCaml Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates how to use Devkit's Cache.Count module for tracking event occurrences and retrieving statistics. It shows adding events and printing the count for a specific event, as well as displaying all statistics. ```ocaml open Devkit (* Counting/statistics *) let stats = Cache.Count.create () let () = Cache.Count.add stats "page_view"; Cache.Count.add stats "page_view"; Cache.Count.add stats "api_call"; Printf.printf "Page views: %d\n" (Cache.Count.count stats "page_view"); print_endline (Cache.Count.show stats Fun.id) ``` -------------------------------- ### Regex Extraction and String Shortening (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates using regular expressions with the Pcre2 library to extract substrings from a given string, and utility for shortening long strings with an indicator of truncated bytes. ```ocaml open Devkit (* Regex extraction *) let rex = Pcre2.regexp {|user=(\w+)|} let user = Stre.extract rex "session: user=john" (* Some "john" *) (* Shorten long strings *) let short = Stre.shorten 20 "This is a very long string that needs truncation" (* "This is a very lo..[+32 bytes]..ion" *) ``` -------------------------------- ### OCaml Local Tracing with Trace-Tef Source: https://github.com/ahrefs/devkit/blob/master/README.md This snippet demonstrates how to configure and use local tracing with the `ocaml-trace` library and `trace-tef` backend to generate JSON trace files. It shows setting up the tracing backend and then executing a function that performs an HTTP request. ```ocaml open Devkit let run () = let resp = Web.http_request `GET "http://icanhazip.com" in (* ... *) let () = Trace_tef.with_setup ~out:(`File "trace.json") () @@ fun () -> run () ``` -------------------------------- ### Parallel Processing with OCaml Forks Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates parallel processing using OCaml's fork-based workers. It showcases creating worker pools, performing tasks, automatic worker management, and fork-based execution with failure recovery. Dependencies include the Devkit library. ```ocaml open Devkit (* Simple parallel processing with worker pool *) module Worker = Parallel.Forks(struct type task = string type result = int end) let () = let workers = Worker.create String.length 4 in (* 4 workers *) let tasks = List.to_seq ["hello"; "world"; "foo"; "bar"; "baz"] |> Enum.of_seq in Worker.perform workers tasks (fun len -> Printf.printf "Result: %d\n" len ); Worker.stop workers (* Run tasks in parallel with automatic worker management *) let () = let tasks = [1; 2; 3; 4; 5] in Parallel.run_workers 4 (fun n -> Printf.printf "Processing %d in PID %d\n" n (Unix.getpid ()); Unix.sleep 1 ) tasks (* Fork-based parallel execution with revive *) let () = let tasks = ["worker1"; "worker2"; "worker3"] in Parallel.run_forks ~revive:Parallel.On_failure (* Restart crashed workers *) ~wait_stop:10 (* Wait 10 seconds before SIGKILL *) (fun name -> Printf.printf "%s started (PID %d)\n" name (Unix.getpid ()); while Daemon.should_run () do Unix.sleep 1 done ) tasks (* Simple invoke: run function in forked process *) let () = let get_result = Parallel.invoke (fun x -> x * x) 5 in (* Parent continues, child computes *) let result = get_result () in (* Wait for result *) Printf.printf "5^2 = %d\n" result (* Lwt-based worker services *) let () = Lwt_main.run begin let%lwt services = Parallel.Services.start 3 (fun i -> Lwt_io.printlf "Worker %d started" i >>= fun () -> let rec loop () = Lwt_unix.sleep 1.0 >>= loop in loop () ) in (* Later: rolling restart *) let%lwt () = Parallel.Services.rolling_restart ~timeout:5.0 services in (* Shutdown *) Parallel.Services.stop ~timeout:10.0 services end ``` -------------------------------- ### Time-Limited Execution (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Demonstrates the Action.timely function, which ensures a given function is executed at most once within a specified time interval, useful for rate limiting. ```ocaml open Devkit (* Time-limited execution *) let rate_limited = Action.timely 1.0 (fun msg -> print_endline msg ) let () = rate_limited "First"; (* Prints *) rate_limited "Second"; (* Skipped, too soon *) Unix.sleep 2; rate_limited "Third" (* Prints *) ``` -------------------------------- ### Create a Time-Limited Cache in OCaml Source: https://context7.com/ahrefs/devkit/llms.txt Shows how to implement a time-limited cache for strings using Devkit's Cache.TimeLimited2 module. This cache automatically expires entries after a specified duration. It demonstrates adding an item and checking its validity. ```ocaml open Devkit (* Time-limited cache *) module TimedSet = Cache.TimeLimited2(String)(Cache.NoLock) let timed_cache = TimedSet.create 60.0 (* 60 second expiry *) let () = TimedSet.add timed_cache "session123"; match TimedSet.get timed_cache "session123" with | Some _ -> print_endline "Session valid" | None -> print_endline "Session expired or not found" ``` -------------------------------- ### Listing External OCaml Dependencies with Opam Source: https://github.com/ahrefs/devkit/blob/master/README.md This command lists the external dependencies required by the devkit package. It uses `opam list -s -e --resolve=devkit` to show the package names and versions of all direct and transitive dependencies. ```sh opam list -s -e --resolve=devkit ``` -------------------------------- ### EWMA (Exponential Weighted Moving Average) (OCaml) Source: https://context7.com/ahrefs/devkit/llms.txt Illustrates the implementation of an Exponential Weighted Moving Average (EWMA) using Action.ewma, which provides functions to store new values and retrieve the current EWMA. ```ocaml open Devkit (* EWMA (Exponential Weighted Moving Average) *) let (store, get) = Action.ewma 0.1 let () = store 10.0; store 12.0; store 11.0; Printf.printf "EWMA: %.2f\n" (get ()) ``` -------------------------------- ### Updating MetaOCaml-Generated Code Source: https://github.com/ahrefs/devkit/blob/master/README.md This command updates code generated by MetaOCaml. It uses `opam exec` to run `make gen_metaocaml` within a specific OCaml switch (4.07.1+BER), ensuring the correct compiler environment is used for generation. ```sh opam exec --switch=4.07.1+BER -- make gen_metaocaml ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.