Source

ibx / lib / ib.ml

Full commit
  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
(* File: ib.ml

   IBX - OCaml implementation of the Interactive Brokers TWS API

   Copyright (C) 2013-  Oliver Gu
   email: gu.oliver@yahoo.com

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*)

(* Parts of this module are inspired by Async's Rpc module. *)

open Core.Std
open Async.Std
open Std_internal
open Tws_prot

include struct
  open Response
  module Next_order_id     = Next_order_id
  module Tws_error         = Tws_error
  module Execution_report  = Execution_report
  module Commission_report = Commission_report
end
module Server_log_level = Query.Server_log_level

module Query_id = struct
  include Unique_id.Int63 (struct end)
  let increase t num = of_int_exn (to_int_exn t + num)
  let val_type = Val_type.create to_string of_string
  let default = of_int_exn (-1)
end

module Header = struct
  type 'a t = {
    tag : 'a;
    version : int;
  } with sexp

  let create ~tag ~version =
    { tag;
      version;
    }

  module R = Recv_tag
  let managed_accounts  = { tag = R.Managed_accounts  ; version = 1 }
  let next_order_id     = { tag = R.Next_order_id     ; version = 1 }
  let tws_error         = { tag = R.Tws_error         ; version = 2 }
  let execution_report  = { tag = R.Execution_report  ; version = 9 }
  let commission_report = { tag = R.Commission_report ; version = 1 }
end

module Ibx_error = struct
  type t =
  | Connection_closed
  | Unexpected_eof
  | Read_error of Sexp.t
  | Parse_error of Sexp.t
  | Tws_error of string
  | Unknown_response_handler of Query_id.t * Recv_tag.t * [ `Version of int ]
  | Unpickler_mismatch of Sexp.t * Recv_tag.t Header.t list
  | Uncaught_exn of Sexp.t
  with sexp
  exception Ibx of t with sexp
  let raise t = raise (Ibx t)
  let to_error t = Error.of_thunk (fun () -> Sexp.to_string_hum (sexp_of_t t))
end

module Ibx_result = struct
  type 'a t = ('a, Ibx_error.t) Result.t with sexp

  let make_try_with try_with (>>|) constructor f =
    try_with f >>| function
    | Ok _ as x -> x
    | Error exn -> Error (constructor (Exn.sexp_of_t exn))

  let try_with_read f = make_try_with
    Monitor.try_with
    (>>|)
    (fun e -> Ibx_error.Read_error e)
    f

  let try_with_unpickle f = make_try_with
    Result.try_with
    (|>)
    (fun e -> Ibx_error.Parse_error e)
    f

  let or_error = function
    | Ok _ as x -> x
    | Error err -> Error (Ibx_error.to_error err)
end

let to_tws p x = Pickler.run p x
let of_tws u x = Ibx_result.try_with_unpickle (fun () -> Unpickler.run_exn u x)

module Client_header = struct
  type t =
    { client_version : int;
      client_id      : Client_id.t;
    } with fields, sexp

  let pickler =
    Pickler.create
      Pickler.Spec.(
        wrap (
          Fields.fold
            ~init:(empty ())
            ~client_version:(fields_value (required int))
            ~client_id:(fields_value (required Client_id.val_type)))
          (fun { client_version; client_id } ->
            `Args $ client_version $ client_id))
end

module Server_header = struct
  type t =
    { server_version  : int;
      connection_time : Time.t;
    } with fields, sexp

  let unpickler =
    Unpickler.create ~name:"Server_header"
      Unpickler.Spec.(
        Fields.fold
          ~init:(empty ())
          ~server_version:(fields_value (required int))
          ~connection_time:(fields_value (required time)))
      (fun server_version connection_time ->
        { server_version; connection_time })
end

module Query = struct
  type t =
    { tag     : Send_tag.t;
      version : int;
      id      : Query_id.t option;
      data    : string;
    } with fields, sexp

  let pickler =
    Pickler.create
      Pickler.Spec.(
        wrap (
          Fields.fold
            ~init:(empty ())
            ~tag:(fields_value (required Send_tag.val_type))
            ~version:(fields_value (required int))
            ~id:(fields_value (skipped_if_none Query_id.val_type))
            ~data:(fields_value tws_data))
          (fun { tag; version; id; data } ->
            `Args $ tag $ version $ id $ data))
end

module Response_data = struct
  type t = ([ `Cancel | `Response of string Queue.t ]) Ibx_result.t with sexp
end

module Response = struct
  type t = {
    tag      : Recv_tag.t;
    version  : int;
    query_id : Query_id.t option;
    data     : Response_data.t;
  } with fields, sexp

  let pickler = lazy (
    Pickler.create ~name:"Response"
      Pickler.Spec.(
        wrap (
          Fields.fold
            ~init:(empty ())
            ~tag:(fields_value (required Recv_tag.val_type))
            ~version:(fields_value (required int))
            ~query_id:(fields_value (skipped_if_none Query_id.val_type))
            ~data:(fields_value tws_data))
          (fun { tag; version; query_id; data } ->
            let tws_data = match data with
              | Error _
              | Ok `Cancel -> assert false
              | Ok (`Response data) ->
                Queue.to_list data
                |> String.concat ~sep:"\000"
                |> Fn.flip (^) "\000"
            in
            `Args $ tag $ version $ query_id $ tws_data)))
end

module type Connection = sig
  type t

  val create
    :  ?enable_logging:bool
    -> extend_error:(Error.t -> unit)
    -> extend_status:(string -> unit)
    -> extend_execution_report:(Execution_report.t -> unit)
    -> extend_commission_report:(Commission_report.t -> unit)
    -> Reader.t
    -> Writer.t
    -> t Deferred.t

  val close  : t -> unit Deferred.t
  val closed : t -> unit Deferred.t
  val is_closed : t -> bool

  val set_server_log_level
    :  t
    -> level:[
    | `System
    | `Error
    | `Warning
    | `Information
    | `Detail
    ]
    -> unit

  module Handshake_result : sig
    type t =
    | Eof
    | Version_failure of int
    | Server_header of [ `Version of int ] * Time.t * Account_code.t
    with sexp
  end

  val try_connect
    :  t
    -> client_version:int
    -> client_id:Client_id.t
    -> Handshake_result.t Or_error.t Deferred.t
end

module Response_handler = struct
  type handler =
    Response.t
    -> [ `Keep
       | `Remove
       | `Replace of handler
       | `Die of Ibx_error.t ] Deferred.t

  type t = {
    tag     : Recv_tag.t;
    version : int;
    run     : handler;
  }

  let create ~header ~run =
    { tag = header.Header.tag;
      version = header.Header.version;
      run;
    }
end

module type Connection_internal = sig
  include Connection

  val dispatch
    :  t
    -> handlers:Response_handler.t list
    -> Query.t
    -> (unit, [ `Closed ]) Result.t

  val cancel_streaming :
    ?query:Query.t
    -> t
    -> recv_header:Recv_tag.t Header.t list
    -> query_id:Query_id.t
    -> (unit, [ `Closed ]) Result.t

  val next_query_id : t -> Query_id.t Deferred.t
end

module Connection : Connection_internal = struct
  type t =
    { writer        : Writer.t;
      reader        : string Pipe.Reader.t;
      open_queries  : (Query_id.t * Recv_tag.t * version, response_handler) Hashtbl.t;
      next_order_id : Order_id.t Ivar.t;
      account_code  : Account_code.t Ivar.t;
      stop          : unit Ivar.t;
      logfun        : logfun option;
      extend_error  : Error.t -> unit;
    }
  and version = int
  and response_handler = Response_handler.handler
  and logfun = [ `Send of Query.t | `Recv of Response.t ] -> unit

  let init_handler t ~header ~unpickler ~action ~f =
    let id = Query_id.default in
    let tag = header.Header.tag in
    let version = header.Header.version in
    Hashtbl.replace t.open_queries ~key:(id, tag, version) ~data:(fun response ->
      match response.Response.data with
      | Error err ->
        return (`Die err)
      | Ok `Cancel ->
        assert false (* Response handler is not cancelable. *)
      | Ok (`Response data) ->
        begin
          match of_tws unpickler data with
          | Error err ->
            return (`Die err)
          | Ok response ->
            f response;
            return action
        end)

  let create
      ?(enable_logging = false)
      ~extend_error
      ~extend_status
      ~extend_execution_report
      ~extend_commission_report
      reader
      writer =
    let null_delim_pred = `Char '\000' in
    let read_one reader =
      Reader.read_until reader null_delim_pred ~keep_delim:false >>| function
      | `Eof -> `Eof
      | `Ok _ as x -> x
      | `Eof_without_delim s ->
        (* We pretend that everything is Ok here and handle the error later. *)
        `Ok s
    in
    let logfun send_recv =
      let tr_null s = String.tr s ~target:'\000' ~replacement:'|' in
      match send_recv with
      | `Send query ->
        let msg = to_tws Query.pickler query in
        Log.Global.debug ">> %s" (tr_null msg)
      | `Recv response ->
        let msg = to_tws (Lazy.force Response.pickler) response in
        Log.Global.debug "<< %s" (tr_null msg)
    in
    let t =
      {
        writer;
        reader        = Reader.read_all reader read_one;
        open_queries  = Hashtbl.Poly.create ~size:25 ();
        next_order_id = Ivar.create ();
        account_code  = Ivar.create ();
        stop          = Ivar.create ();
        logfun        = Option.some_if enable_logging logfun;
        extend_error;
      }
    in
    init_handler t
      ~header:Header.managed_accounts
      ~unpickler:Account_code.unpickler
      ~action:`Remove
      ~f:(Ivar.fill t.account_code);
    init_handler t
      ~header:Header.next_order_id
      ~unpickler:Next_order_id.unpickler
      ~action:`Remove
      ~f:(Ivar.fill t.next_order_id);
    init_handler t
      ~header:Header.tws_error
      ~unpickler:Tws_error.unpickler
      ~action:`Keep
      ~f:(fun e -> extend_status (Tws_error.to_string_hum e));
    init_handler t
      ~header:Header.execution_report
      ~unpickler:Execution_report.unpickler
      ~action:`Keep
      ~f:extend_execution_report;
    init_handler t
      ~header:Header.commission_report
      ~unpickler:Commission_report.unpickler
      ~action:`Keep
      ~f:extend_commission_report;
    return t

  let next_query_id t =
    let new_id = Query_id.create () in
    Ivar.read t.next_order_id
    >>| fun oid -> Query_id.increase new_id (Raw_order.Id.to_int_exn oid)

  let is_closed t = Ivar.is_full t.stop
  let closed t = Ivar.read t.stop

  let close t =
    if not (is_closed t) then begin
      Ivar.fill t.stop ();
      Writer.close t.writer
      >>| fun () ->
      Pipe.close_read t.reader
    end else Deferred.unit

  let send_tws writer pickler msg = Writer.write writer (to_tws pickler msg)

  let send_query ?logfun writer query =
    begin match logfun with
    | None -> ()
    | Some f -> f (`Send query)
    end;
    send_tws writer Query.pickler query

  let really_read reader ~len =
    Pipe.read_exactly reader ~num_values:len >>| function
    | `Eof -> `Eof
    | `Fewer   result -> `Ok result
    | `Exactly result -> `Ok result

  let read_tws reader unpickler ~len =
    really_read reader ~len >>| function
    | `Eof -> Ok `Eof
    | `Ok raw_msg ->
      begin
        match of_tws unpickler raw_msg with
        | Error _ as x -> x
        | Ok x -> Ok (`Ok x)
      end

  let read_version_and_optional_id reader tag =
    if Recv_tag.corresponding_response_has_query_id tag then
      let unpickler =
        Unpickler.create ~name:"Version_id"
          Unpickler.Spec.(
            value (required int) ~name:"version"
            ++ value (required Query_id.val_type) ~name:"id"
          )
          (fun version id -> (version, Some id))
      in
      read_tws reader unpickler ~len:2
    else
      let unpickler =
        Unpickler.create ~name:"Version"
          Unpickler.Spec.(
            value (required int) ~name:"version"
          )
          (fun version -> (version, None))
      in
      read_tws reader unpickler ~len:1

  let read_body reader tag =
    let module R = Recv_tag in
    let unimplemented x = Error.failwiths "unimplemented" x R.sexp_of_t in
    let empty_read = return (`Ok (Queue.create ())) in
    let read ~len = really_read reader ~len in
    Ibx_result.try_with_read (fun () ->
      match tag with
      | R.Tick_price -> read ~len:4
      | R.Tick_size -> read ~len:2
      | R.Order_status -> read ~len:9
      | R.Tws_error -> read ~len:2
      | R.Open_order -> read ~len:93
      | R.Account_update -> read ~len:1
      | R.Portfolio_update -> unimplemented R.Portfolio_update
      | R.Account_update_time -> unimplemented R.Account_update_time
      | R.Next_order_id -> read ~len:1
      | R.Contract_data -> read ~len:26
      | R.Execution_report -> read ~len:23
      | R.Book_update -> read ~len:5
      | R.Book_update_L2 -> read ~len:6
      | R.News_bulletins -> unimplemented R.News_bulletins
      | R.Managed_accounts -> read ~len:1
      | R.Financial_advisor -> unimplemented R.Financial_advisor
      | R.Historical_data ->
        begin
          read ~len:3
          >>= function
          | `Eof -> return `Eof
          | `Ok raw_msg ->
            let array = Queue.to_array raw_msg in
            let last = array.(2) in
            let num_bars = Int.of_string last in
            let num_fields = 9 in
            read ~len:(num_bars * num_fields) >>| function
            | `Eof -> `Eof
            | `Ok bars -> Queue.transfer ~src:bars ~dst:raw_msg; `Ok raw_msg
        end
      | R.Bond_contract_data -> unimplemented R.Bond_contract_data
      | R.Scanner_parameters -> unimplemented R.Scanner_parameters
      | R.Scanner_data -> unimplemented R.Scanner_data
      | R.Tick_option -> read ~len:9
      | R.Tick_generic -> read ~len:2
      | R.Tick_string -> read ~len:2
      | R.Tick_efp -> read ~len:8
      | R.Server_time -> read ~len:1
      | R.Realtime_bar -> read ~len:8
      | R.Fundamental_data -> unimplemented R.Fundamental_data
      | R.Contract_data_end -> empty_read
      | R.Open_order_end -> empty_read
      | R.Account_download_end -> unimplemented R.Account_download_end
      | R.Execution_report_end -> empty_read
      | R.Delta_neutral_validation -> unimplemented R.Delta_neutral_validation
      | R.Snapshot_end -> empty_read
      | R.Commission_report -> read ~len:6
    )

  module Deferred_read_result : sig
    type 'a t = [ `Eof | `Ok of 'a ] Ibx_result.t Deferred.t
    include Monad.S with type 'a t := 'a t
  end = struct
    module M = struct
      type 'a t = [ `Eof | `Ok of 'a ] Ibx_result.t Deferred.t

      let bind t f = t >>= function
        | Error _ as x -> Deferred.return x
        | Ok `Eof as x -> Deferred.return x
        | Ok (`Ok x) -> f x

      let return x = Deferred.return (Ok (`Ok x))
    end
    include M
    include Monad.Make (M)
  end
  let (>>=~) = Deferred_read_result.(>>=)
  let (>>|~) = Deferred_read_result.(>>|)

  let read_response reader =
    read_tws reader Recv_tag.unpickler ~len:1
    >>=~ fun tag ->
    read_version_and_optional_id reader tag
    >>=~ fun (version, id) ->
    read_body reader tag
    >>|~ fun data ->
    { Response.
      tag;
      version;
      query_id = id;
      data = Ok (`Response data);
    }

  let writer t = if Ivar.is_full t.stop then Error `Closed else Ok t.writer

  let set_server_log_level t ~level =
    match writer t with
    | Error `Closed -> ()
    | Ok writer ->
      let log_level = Server_log_level.create ~level in
      let query =
        { Query.
          tag     = Send_tag.Set_server_log_level;
          version = 1;
          id      = None;
          data    = to_tws Server_log_level.pickler log_level;
        }
      in
      send_query ?logfun:t.logfun writer query

  let dispatch t ~handlers query =
    match writer t with
    | Error `Closed as x -> x
    | Ok writer ->
      send_query ?logfun:t.logfun writer query;
      let id = Option.value query.Query.id ~default:Query_id.default in
      List.iter handlers ~f:(fun h ->
        let tag = h.Response_handler.tag in
        let version = h.Response_handler.version in
        let run = h.Response_handler.run in
        Hashtbl.replace t.open_queries ~key:(id, tag, version) ~data:run
      );
      Ok ()

  let cancel_streaming ?query t ~recv_header ~query_id =
    match writer t with
    | Error `Closed as x -> x
    | Ok writer ->
      begin match query with
      | None -> ()
      | Some query -> send_query ?logfun:t.logfun writer query
      end;
      List.iter recv_header ~f:(fun header ->
        let tag = header.Header.tag in
        let version = header.Header.version in
        match Hashtbl.find t.open_queries (query_id, tag, version) with
        | None -> ()
        | Some response_handler ->
          don't_wait_for (Deferred.ignore (
            response_handler
              { Response.
                tag;
                version;
                query_id = Some query_id;
                data = Ok `Cancel;
              }))
      );
      Ok ()

  let handle_response t response =
    let id = Option.value response.Response.query_id ~default:Query_id.default in
    let tag = response.Response.tag in
    let version = response.Response.version in
    let key = (id, tag, version) in
    match Hashtbl.find t.open_queries key with
    | None ->
      return (`Stop (Ibx_error.Unknown_response_handler (id, tag, `Version version)))
    | Some f  ->
      f response >>| fun action ->
      begin
        match action with
        | `Remove ->
          Hashtbl.remove t.open_queries key;
          `Continue
        | `Keep ->
          `Continue
        | `Replace handler ->
          Hashtbl.replace t.open_queries ~key ~data:handler;
          `Continue
        | `Die err ->
          `Stop err
      end

  let handle_incoming t =
    let rec loop () =
      choose
        [ choice (Ivar.read t.stop) (fun () -> `Stop);
          choice (read_response t.reader) (fun x  -> `Read x);
        ] >>> function
        | `Stop -> ()
        | `Read read_result ->
          match Deferred.peek (Ivar.read t.stop) with
          | Some () -> ()
          | None ->
            match read_result with
            | Error err -> Ibx_error.raise err
            | Ok `Eof -> Ibx_error.raise Ibx_error.Unexpected_eof
            | Ok (`Ok response) ->
              begin
                match t.logfun with
                | None -> ()
                | Some f -> f (`Recv response)
              end;
              handle_response t response
              >>> function
              | `Continue -> loop ()
              | `Stop err -> Ibx_error.raise err
    in
    let monitor = Monitor.create ~name:"Connection loop" () in
    Stream.iter
      (Stream.interleave (Stream.of_list (
        [ Monitor.errors (Writer.monitor t.writer)
        ; Monitor.errors monitor
        ])))
      ~f:(fun exn ->
        don't_wait_for (close t);
        let error = match Monitor.extract_exn exn with
          | Ibx_error.Ibx err -> err
          | exn -> Ibx_error.Uncaught_exn (Exn.sexp_of_t exn)
        in
        Hashtbl.iter t.open_queries
          ~f:(fun ~key:(id, tag, version) ~data:response_handler ->
            don't_wait_for (Deferred.ignore (
              response_handler
                { Response.
                  tag;
                  version;
                  query_id = Some id;
                  data = Error error
                })));
        t.extend_error (Ibx_error.to_error error));
    Scheduler.within ~monitor loop

  module Handshake_result = struct
    type t =
    | Eof
    | Version_failure of int
    | Server_header of [ `Version of int ] * Time.t * Account_code.t
    with sexp
  end

  let try_connect t ~client_version ~client_id =
    let client_header = {
      Client_header.
      client_version;
      client_id;
    } in
    begin match writer t with
    | Error `Closed ->
      return (Error Ibx_error.Connection_closed)
    | Ok writer ->
      send_tws writer Client_header.pickler client_header;
      read_tws t.reader Server_header.unpickler ~len:2
      >>= function
      | Error err ->
        don't_wait_for (close t);
        return (Error err)
      | Ok `Eof ->
        don't_wait_for (close t);
        return (Ok Handshake_result.Eof)
      | Ok (`Ok header) ->
        let server_version = header.Server_header.server_version in
        if not (server_version >= Config.server_version) then
          return (Ok (Handshake_result.Version_failure server_version))
        else begin
          handle_incoming t;  (* Start handling incoming messages. *)
          Ivar.read t.account_code
          >>| fun account_code ->
          Ok (Handshake_result.Server_header (
            `Version server_version,
            header.Server_header.connection_time,
            account_code
          ))
        end
    end >>| Ibx_result.or_error
end

module Request = struct
  type ('query, 'response) t =
    { send_header  : Send_tag.t Header.t;
      recv_header  : Recv_tag.t Header.t;
      tws_query    : 'query    Tws_prot.Pickler.t;
      tws_response : 'response Tws_prot.Unpickler.t;
    }

  let create ~send_header ~recv_header ~tws_query ~tws_response =
    { send_header;
      recv_header;
      tws_query;
      tws_response;
    }

  let dispatch t con query =
    let ivar = Ivar.create () in
    let query =
      { Query.
        tag     = t.send_header.Header.tag;
        version = t.send_header.Header.version;
        id      = None;
        data    = to_tws t.tws_query query;
      }
    in
    let handler =
      Response_handler.create ~header:t.recv_header ~run:(fun response ->
        match response.Response.data with
        | Error err as x ->
          (* If this handler died before, the ivar is already filled. *)
          Ivar.fill_if_empty ivar x;
          return (`Die err)
        | Ok `Cancel ->
          assert false (* Non-streaming requests are not cancelable. *)
        | Ok (`Response data) ->
          begin
            match of_tws t.tws_response data with
            | Error err as x ->
              Ivar.fill ivar x;
              return (`Die err)
            | Ok _response as x ->
              Ivar.fill ivar x;
              return `Remove
          end)
    in
    begin
      match Connection.dispatch con ~handlers:[handler] query with
      | Ok () -> ()
      | Error `Closed -> Ivar.fill ivar (Error Ibx_error.Connection_closed)
    end;
    Ivar.read ivar >>| Ibx_result.or_error
end

module Streaming_request = struct
  type ('query, 'response) t =
    { send_header  : Send_tag.t Header.t;
      canc_header  : Send_tag.t Header.t option;
      recv_header  : Recv_tag.t Header.t list;
      skip_header  : Recv_tag.t Header.t list option;
      tws_query    : 'query    Tws_prot.Pickler.t;
      tws_response : 'response Tws_prot.Unpickler.t list;
    }

  module Id = Query_id

  let create ?canc_header ?skip_header
      ~send_header ~recv_header ~tws_query ~tws_response () =
    { send_header;
      canc_header;
      recv_header;
      skip_header;
      tws_query;
      tws_response;
    }

  let dispatch t con query =
    Connection.next_query_id con
    >>= fun query_id ->
    let ivar = Ivar.create () in
    let pipe_r, pipe_w = Pipe.create () in
    let query =
      { Query.
        tag     = t.send_header.Header.tag;
        version = t.send_header.Header.version;
        id      = Some query_id;
        data    = to_tws t.tws_query query;
      }
    in
    let error_handler =
      Response_handler.create ~header:Header.tws_error ~run:(fun response ->
        match response.Response.data with
        | Error err ->
          Pipe.close pipe_w;
          return (`Die err)
        | Ok `Cancel ->
          Pipe.close pipe_w;
          return `Remove
        | Ok (`Response data) ->
          begin
            match of_tws Tws_error.unpickler data with
            | Error err ->
              Pipe.close pipe_w;
              return (`Die err)
            | Ok tws_error ->
              let err_string = Tws_error.to_string_hum tws_error in
              let err = Ibx_error.Tws_error err_string in
              if Ivar.is_empty ivar then begin
                Ivar.fill ivar (Error err);
                return `Remove
              end else
                return (`Die err)
          end)
    in
    let skip_handlers =
      match t.skip_header with
      | None -> []
      | Some skip_headers ->
        List.map skip_headers ~f:(fun header ->
          Response_handler.create ~header ~run:(fun response ->
            match response.Response.data with
            | Error err -> return (`Die err)
            | Ok `Cancel -> return `Remove
            | Ok (`Response _) -> return `Keep))
    in
    let data_handler_result = Result.try_with (fun () ->
      List.map2_exn t.recv_header t.tws_response ~f:(fun header unpickler ->
        Response_handler.create ~header ~run:(fun response ->
          let update pipe_w response =
            match response.Response.data with
            | Error err ->
              Pipe.close pipe_w;
              return (`Die err)
            | Ok `Cancel ->
              Pipe.close pipe_w;
              return `Remove
            | Ok (`Response data) ->
              begin
                match of_tws unpickler data with
                | Error err ->
                  Pipe.close pipe_w;
                  return (`Die err)
                | Ok response ->
                  if not (Pipe.is_closed pipe_w) then begin
                    (* We guard this write call to protect us against
                       incoming messages after a cancelation, causing
                       a write call to a closed pipe. *)
                    don't_wait_for (Pipe.write pipe_w response)
                  end;
                  return `Keep
              end
          in
          match response.Response.data with
          | Error err as x ->
            Pipe.close pipe_w;
            Ivar.fill_if_empty ivar x;
            return (`Die err)
          | Ok `Cancel ->
            Pipe.close pipe_w;
            return `Remove
          | Ok (`Response data) ->
            begin
              match of_tws unpickler data with
              | Error err as x ->
                Pipe.close pipe_w;
                Ivar.fill_if_empty ivar x;
                return (`Die err)
              | Ok response ->
                don't_wait_for (Pipe.write pipe_w response);
                (* We fill the ivar only in the first iteration. *)
                Ivar.fill_if_empty ivar (Ok (pipe_r, query_id));
                return (`Replace (update pipe_w))
            end)))
    in
    begin
      match data_handler_result with
      | Error exn ->
        don't_wait_for (Connection.close con);
        let err = Ibx_error.Unpickler_mismatch (Exn.sexp_of_t exn, t.recv_header) in
        Ivar.fill ivar (Error err)
      | Ok data_handlers ->
        let handlers = error_handler :: (skip_handlers @ data_handlers) in
        match Connection.dispatch con ~handlers query with
        | Ok () -> ()
        | Error `Closed -> Ivar.fill ivar (Error Ibx_error.Connection_closed)
    end;
    Ivar.read ivar >>| Ibx_result.or_error

  let cancel t con query_id =
    let recv_header = Header.tws_error :: t.recv_header in
    let result =
      match t.canc_header with
      | None -> Connection.cancel_streaming con ~recv_header ~query_id
      | Some header ->
        let query =
          { Query.
            tag     = header.Header.tag;
            version = header.Header.version;
            id      = Some query_id;
            data    = "";
          }
        in
        Connection.cancel_streaming con ~recv_header ~query_id ~query
    in
    ignore (result : (unit, [ `Closed ]) Result.t)
end