package nsq
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source
Page
Library
Module
Module type
Parameter
Class
Class type
Source
Source file nsq.ml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003open Base open Lwt let client_version = "0.5.3" let default_nsqd_port = 4150 let default_lookupd_port = 4161 let network_buffer_size = 16 * 1024 let lookupd_error_threshold = 5 module Seconds = struct type t = float [@@deriving yojson] let of_float f = f let value s = s end let recalculate_rdy_interval = Seconds.of_float 60.0 let default_backoff = Seconds.of_float 5.0 let max_backoff = Seconds.of_float 600.0 module Milliseconds = struct type t = int64 [@@deriving yojson] let of_int64 i = i let value i = i let of_seconds s = Seconds.value s *. 1000.0 |> Int64.of_float |> of_int64 end let default_requeue_delay = Milliseconds.of_int64 5000L module MessageID = struct type t = MessageID of bytes let of_bytes b = MessageID b let to_string = function MessageID id -> Bytes.to_string id end let ephemeral s = s ^ "#ephemeral" module Topic = struct type t = Topic of string | TopicEphemeral of string let to_string = function Topic s -> s | TopicEphemeral s -> ephemeral s let%expect_test "to_string" = List.iter ~f:(fun h -> to_string h |> Stdio.print_endline) [ Topic "topic"; TopicEphemeral "topic" ]; [%expect {| topic topic#ephemeral |}] end module Channel = struct type t = Channel of string | ChannelEphemeral of string let to_string = function Channel s -> s | ChannelEphemeral s -> ephemeral s let%expect_test "to_string" = List.iter ~f:(fun h -> to_string h |> Stdio.print_endline) [ Channel "chan"; ChannelEphemeral "chan" ]; [%expect {| chan chan#ephemeral |}] end module FrameType = struct type t = FrameResponse | FrameError | FrameMessage | FrameUnknown of int32 let of_int32 = function | 0l -> FrameResponse | 1l -> FrameError | 2l -> FrameMessage | i -> FrameUnknown i end type raw_frame = { frame_type : int32; data : Bytes.t } type raw_message = { timestamp : int64; attempts : Unsigned.UInt16.t; id : MessageID.t; body : Bytes.t; } module Address = struct type t = Host of string | HostPort of string * int [@@deriving sexp_of, compare, hash, equal] let host s = Host s let host_port a p = HostPort (a, p) let to_string a = match a with Host a -> a | HostPort (a, p) -> Printf.sprintf "%s:%d" a p let%expect_test "to_string" = List.iter ~f:(fun h -> to_string h |> Stdio.print_endline) [ Host "example.com"; HostPort ("example.com", 123) ]; [%expect {| example.com example.com:123 |}] end module IdentifyConfig = struct (* This will be encoded to JSON and sent with the IDENTIFY command *) type t = { heartbeat_interval : Milliseconds.t; client_id : string; hostname : string; user_agent : string; output_buffer_size : int; (* buffer size on bytes the server should use *) output_buffer_timeout : Milliseconds.t; sample_rate : int; } [@@deriving yojson { strict = false }] end type command = | IDENTIFY of IdentifyConfig.t | MAGIC | SUB of Topic.t * Channel.t | PUB of Topic.t * Bytes.t | MPUB of Topic.t * Bytes.t list | REQ of MessageID.t * Milliseconds.t | FIN of MessageID.t | RDY of int | NOP let try_with_string f = match Result.try_with f with | Ok _ as x -> x | Error e -> Error (Exn.to_string e) module ServerMessage = struct type t = | ResponseOk | Heartbeat | ErrorInvalid of string | ErrorBadTopic of string | ErrorBadChannel of string | ErrorFINFailed of string | ErrorREQFailed of string | ErrorTOUCHFailed of string | Message of raw_message let to_string = function | ResponseOk -> "OK" | Heartbeat -> "Heartbeat" | ErrorInvalid s -> Printf.sprintf "ErrorInvalid: %s" s | ErrorBadTopic s -> Printf.sprintf "ErrorBadTopic: %s" s | ErrorBadChannel s -> Printf.sprintf "ErrorBadChannel: %s" s | ErrorFINFailed s -> Printf.sprintf "ErrorFINFailed: %s" s | ErrorREQFailed s -> Printf.sprintf "ErrorREQFailed: %s" s | ErrorTOUCHFailed s -> Printf.sprintf "ErrTouchFailed: %s" s | Message m -> Printf.sprintf "Message with ID %s" (MessageID.to_string m.id) let parse_response_body body = let body = Bytes.to_string body in match body with | "OK" -> Ok ResponseOk | "_heartbeat_" -> Ok Heartbeat | _ -> Error (Printf.sprintf "Unknown response: %s" body) let parse_message_body_exn body = let timestamp = EndianBytes.BigEndian.get_int64 body 0 in let attempts = EndianBytes.BigEndian.get_uint16 body 8 |> Unsigned.UInt16.of_int in let length = Bytes.length body in let id = MessageID.of_bytes (Bytes.sub ~pos:10 ~len:16 body) in let body = Bytes.sub ~pos:26 ~len:(length - 26) body in Message { timestamp; attempts; id; body } let parse_message_body body = try_with_string (fun () -> parse_message_body_exn body) let parse_error_body body = let open Result in match String.split ~on:' ' (Bytes.to_string body) with | [ code; detail ] -> ( match code with | "E_INVALID" -> return (ErrorInvalid detail) | "E_BAD_TOPIC" -> return (ErrorBadTopic detail) | "E_BAD_CHANNEL" -> return (ErrorBadChannel detail) | "E_FIN_FAILED" -> return (ErrorFINFailed detail) | "E_REQ_FAILED" -> return (ErrorREQFailed detail) | "E_TOUCH_FAILED" -> return (ErrorTOUCHFailed detail) | _ -> fail (Printf.sprintf "Unknown error code: %s. %s" code detail) ) | _ -> fail (Printf.sprintf "Malformed error code: %s" (Bytes.to_string body)) let of_raw_frame raw = match FrameType.of_int32 raw.frame_type with | FrameResponse -> parse_response_body raw.data | FrameMessage -> parse_message_body raw.data | FrameError -> parse_error_body raw.data | FrameUnknown i -> Result.Error (Printf.sprintf "Unknown frame type: %li" i) end module Lookup = struct type producer = { remote_address : string; hostname : string; broadcast_address : string; tcp_port : int; http_port : int; version : string; } [@@deriving yojson { strict = false }] type response = { channels : string list; producers : producer list } [@@deriving yojson { strict = false }] let response_of_string s = let open Result in try_with_string (fun () -> Yojson.Safe.from_string s) >>= response_of_yojson let producer_addresses lr = List.map ~f:(fun p -> Address.host_port p.broadcast_address p.tcp_port) lr.producers end let log_and_return prefix r = match r with | Ok _ as ok -> return ok | Error s as error -> Logs_lwt.err (fun l -> l "%s: %s" prefix s) >>= fun () -> return error let query_nsqlookupd ~topic a = let host, port = match a with | Address.Host h -> (h, default_lookupd_port) | Address.HostPort (h, p) -> (h, p) in let topic_string = Topic.to_string topic in let uri = Uri.make ~scheme:"http" ~host ~port ~path:"lookup" ~query:[ ("topic", [ topic_string ]) ] () in let open Cohttp in catch (fun () -> Cohttp_lwt_unix.Client.get uri >>= fun (resp, body) -> match Response.status resp with | `OK -> Cohttp_lwt.Body.to_string body >>= fun body -> log_and_return "Error parsing lookup response" (Lookup.response_of_string body) | status -> return_error (Printf.sprintf "Expected %s, got %s" (Code.string_of_status `OK) (Code.string_of_status status))) (fun e -> let s = Exn.to_string e in log_and_return "Querying lookupd" (Error s)) let bytes_of_pub topic data = let buf = Bytes.create 4 in EndianBytes.BigEndian.set_int32 buf 0 (Int32.of_int_exn (Bytes.length data)); Printf.sprintf "PUB %s\n%s%s" (Topic.to_string topic) (Bytes.to_string buf) (Bytes.to_string data) |> Bytes.of_string let%expect_test "bytes_of_pub" = let topic = Topic.Topic "TestTopic" in let data = Bytes.of_string "Hello World" in bytes_of_pub topic data |> Hex.of_bytes |> Hex.hexdump ~print_chars:false; [%expect {| 00000000: 5055 4220 5465 7374 546f 7069 630a 0000 00000001: 000b 4865 6c6c 6f20 576f 726c 64 |}] (** MPUB <topic_name>\n [ 4-byte body size ] [ 4-byte num messages ] [ 4-byte message #1 size ][ N-byte binary data ] ... (repeated <num_messages> times) <topic_name> - a valid string (optionally having #ephemeral suffix) *) let bytes_of_mpub topic bodies = let body_count = List.length bodies in let data_size = List.fold_left ~f:(fun a b -> a + Bytes.length b) ~init:0 bodies in let buf = Bytes.create (4 + 4 + (4 * body_count) + data_size) in EndianBytes.BigEndian.set_int32 buf 0 (Int32.of_int_exn data_size); EndianBytes.BigEndian.set_int32 buf 4 (Int32.of_int_exn body_count); let index = ref 8 in List.iter ~f:(fun b -> EndianBytes.BigEndian.set_int32 buf !index (Int32.of_int_exn (Bytes.length b)); index := !index + 4; Bytes.blit ~src:b ~src_pos:0 ~dst:buf ~dst_pos:!index ~len:(Bytes.length b); index := !index + Bytes.length b) bodies; Printf.sprintf "MPUB %s\n%s" (Topic.to_string topic) (Bytes.to_string buf) |> Bytes.of_string let%expect_test "bytes_of_mpub" = let topic = Topic.Topic "TestTopic" in let bodies = [ Bytes.of_string "Hello world"; Bytes.of_string "Hello again" ] in bytes_of_mpub topic bodies |> Hex.of_bytes |> Hex.hexdump ~print_chars:false; [%expect {| 00000000: 4d50 5542 2054 6573 7454 6f70 6963 0a00 00000001: 0000 1600 0000 0200 0000 0b48 656c 6c6f 00000002: 2077 6f72 6c64 0000 000b 4865 6c6c 6f20 00000003: 6167 6169 6e |}] (** IDENTIFY\n [ 4-byte size in bytes ][ N-byte JSON data ] *) let bytes_of_identify c = let buf = Bytes.create 4 in let data = IdentifyConfig.to_yojson c |> Yojson.Safe.to_string in let length = String.length data in EndianBytes.BigEndian.set_int32 buf 0 (Int32.of_int_exn length); Printf.sprintf "IDENTIFY\n%s%s" (Bytes.to_string buf) data |> Bytes.of_string let bytes_of_command = function | MAGIC -> Bytes.of_string " V2" | IDENTIFY c -> bytes_of_identify c | NOP -> Bytes.of_string "NOP\n" | RDY i -> Printf.sprintf "RDY %i\n" i |> Bytes.of_string | FIN id -> Printf.sprintf "FIN %s\n" (MessageID.to_string id) |> Bytes.of_string | SUB (t, c) -> Printf.sprintf "SUB %s %s\n" (Topic.to_string t) (Channel.to_string c) |> Bytes.of_string | REQ (id, delay) -> Printf.sprintf "REQ %s %Li\n" (MessageID.to_string id) (Milliseconds.value delay) |> Bytes.of_string | PUB (t, data) -> bytes_of_pub t data | MPUB (t, data) -> bytes_of_mpub t data let%expect_test "bytes_of_command" = let commands = [ MAGIC; NOP; RDY 10; FIN (MessageID.of_bytes (Bytes.of_string "ABC")); REQ (MessageID.of_bytes (Bytes.of_string "ABC"), 100L); ] in List.iter ~f:(fun c -> bytes_of_command c |> Hex.of_bytes |> Hex.hexdump ~print_chars:false) commands; [%expect {| 00000000: 2020 5632 00000000: 4e4f 500a 00000000: 5244 5920 3130 0a 00000000: 4649 4e20 4142 430a 00000000: 5245 5120 4142 4320 3130 300a |}] (* Timeout will only apply if > 0.0 *) let maybe_timeout ~timeout f = let timeout = Seconds.value timeout in if Float.(timeout <= 0.0) then f () else Lwt_unix.with_timeout timeout f let send ~timeout ~conn command = let oc = snd conn in let data = bytes_of_command command |> Bytes.to_string in maybe_timeout ~timeout (fun () -> Lwt_io.write oc data) let catch_result promise = try_bind promise (fun x -> return_ok x) (fun e -> return_error (Exn.to_string e)) let catch_result1 f x = catch_result (fun () -> f x) let connect host timeout = let host, port = match host with | Address.Host h -> (h, default_nsqd_port) | Address.HostPort (h, p) -> (h, p) in Lwt_unix.gethostbyname host >>= fun info -> let host = Array.random_element_exn info.h_addr_list in let addr = Unix.ADDR_INET (host, port) in maybe_timeout ~timeout (fun () -> Lwt_io.open_connection ~in_buffer:(Lwt_bytes.create network_buffer_size) ~out_buffer:(Lwt_bytes.create network_buffer_size) addr) let frame_from_bytes bytes = let frame_type = EndianBytes.BigEndian.get_int32 bytes 0 in let to_read = Bytes.length bytes - 4 in let data = Bytes.sub ~pos:4 ~len:to_read bytes in { frame_type; data } let read_raw_frame ~timeout (ic, _) = Lwt_io.BE.read_int32 ic >>= fun size -> let size = Int32.to_int_exn size in let bytes = Bytes.create size in maybe_timeout ~timeout (fun () -> Lwt_io.read_into_exactly ic bytes 0 size) >>= fun () -> return (frame_from_bytes bytes) let send_expect_ok ~read_timeout ~write_timeout ~conn cmd = send ~timeout:write_timeout ~conn cmd >>= fun () -> read_raw_frame ~timeout:read_timeout conn >>= fun raw -> match ServerMessage.of_raw_frame raw with | Ok ResponseOk -> return_unit | Ok sm -> fail_with (Printf.sprintf "Expected OK, got %s" (ServerMessage.to_string sm)) | Error e -> fail_with (Printf.sprintf "Expected OK, got %s" e) let subscribe ~read_timeout ~write_timeout ~conn topic channel = send_expect_ok ~read_timeout ~write_timeout ~conn (SUB (topic, channel)) let identify ~read_timeout ~write_timeout ~conn ic = send_expect_ok ~read_timeout ~write_timeout ~conn (IDENTIFY ic) module Consumer = struct module Config = struct type