parvel / parvel.ml

The default branch has multiple heads

   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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
module type COUNTER
 =
  sig
    type ref_t;
    type t;
    value create : unit -> ref_t;
    value next : ref_t -> t;
    value compare : t -> t -> int;
  end
;


module Counter : COUNTER =
  struct
    type t = int;
    type ref_t = ref int;
    value create () = ref (-1);
    value next r = ( incr r; r.contents );
    value compare a b = Pervasives.compare (a : int) (b : int);
  end
;


(*
value p_counter = Counter.create ()
  and g_counter = Counter.create ()
;
*)


value pid_local_counter = Counter.create ()
;


(*
(* Всё, что зависит от конкретной реализации ввода-вывода,
   закатываем в функтор: *)

module Make : Parvel_types.F = functor (IO : Parvel_types.MonadIO) ->
  struct
*)

    module IO = Parvel_IO;

    (* локальный pid в пределах процесса *)
    type lpid = Counter.t
    ;

    type host_key = string;

    type host_id = Counter.t;

    (* а это -- пока за пределы процесса не вышли *)
    type gpid = { hid : host_id ; lpid : lpid }
    ;

    type addr =
      [= `Lpid of lpid
      |  `Gpid of gpid
      |  `Mcast of list addr
      ]
    ;

(* ?  или  value (host_self : host_id) = -1  ?
    type vpid = [ LPid of lpid | GPid of gpid ]
    ;
*)
    (* пока чтобы компилировалось: *)
    type pid = lpid;


    type tyname = string
    ;

    type tyver = int
    ;

    type typeinfou =
      < tyname : tyname
      ; tyver : tyver
      >
    ;

    type ty_error =
      < expected : tyname
      ; received : tyname
      >
    ;

    exception Ty_error of ty_error
    ;

    exception Deserialize_error of tyname and string
    ;

    value deserialize_error tyname msg =
      Deserialize_error tyname msg
    ;

    type ty_ver_error =
      < tyname : tyname
      ; expected : int
      ; got : int
      >
    ;
    
    exception Ty_ver of ty_ver_error;

    type call_resp_error =
      [= `Exn_string of string
      ]
    ;

    type call_resp 'o =
      [ CR_Ok of 'o
      | CR_Error of call_resp_error
      ]
    ;

    exception ECall of call_resp_error;

    type dest_kind =
      [ DLocal of IO.sink unit and IO.source unit
      | DRemote
          of int
          and Cdt.type_name
          and (string -> unit)
          and (unit -> string)
      ]
    ;

    type dest 'o =
      { dest_ref : ref (option (call_resp 'o))
      ; dest_kind : dest_kind
      }
    ;

    type call 'i 'o = ('i * dest 'o)
    ;

    type process_exit_status =
      [ PE_Normal
      | PE_Error of process_exit_error
      ]
    and process_exit_error =
      [= `Exn of exn
      |  `Exn_string of string
      ]
    ;

    type process_command_req =
      [= `Shutdown
      |  `Exited of (pid * process_exit_status)
      ]
    ;

    type process_message_req 'i =
      [ Msg of 'i
      | Cmd of process_command_req
      ]
    ;

    type process_status =
      [ PSAlive of list (pid -> process_exit_status -> IO.m unit)
      | PSExited of process_exit_status
      ]
    ;

    (* тип, описывающий "процесс" -- нечто, что видят другие и знают
       его тип, но не имеют доступа ко внутренностями.  (следовательно,
       тип абстрактный, так как читать тоже не нужно давать в идеале.)
     *)
    type process 'i =
      { p_pid : lpid
      ; p_send_msg : process_message_req 'i -> IO.m unit
      ; p_status : mutable process_status
      }
    ;

    type addrt 'o =
      { (* aty : typeinfot 'o
      ;*)

        asend : process_message_req 'o -> IO.m unit  (* cheating! *)

      }
    ;

    type server 'i 'o = process (call 'i 'o);

    type context =
      { c_send_cmd : process_command_req -> IO.m unit
      ; c_mq_set_block_limit : int -> unit
      ; c_mq_set_fail_limit : int -> unit
      ; c_finalizers : mutable list (unit -> unit)
      }
    ;

    (* диспетчер сообщений -- то, что содержит пользовательский код
     *)

    type dispatcher 'a 'b = 'a -> IO.m 'b
    and process_dispatcher 'i =
      dispatcher (process_message_req 'i) (process_result 'i)
    and process_result 'i =
      [ Exit of process_exit_status
      | Continue of process_dispatcher 'i
      ]
    ;

    type server_dispatcher 'i 'o =
      dispatcher 'i (call_resp 'o)
    ;

    type factory 'i 'o = context -> IO.m (dispatcher 'i 'o)
    ;

    type process_factory 'i =
      factory (process_message_req 'i) (process_result 'i)
    ;

    type server_factory 'i 'o =
      factory 'i (call_resp 'o)
    ;


    (*********************************************************)

    (* runtime type infos: *)

    module Ti
     =
      struct

        open Cd_All; open Cdt;
        open Printf;
        open Cd_Ser;

        (* in Cd_Ser:
        value ti_int = (ti_int :> ti int);
        value ti_string = (ti_string :> ti string);
        value ti_unit = (ti_unit :> ti unit);
        *)

        value ti_call_resp_error
         : ti call_resp_error
         = ((
           new ti_sum_type
             ~type_name:"call_resp_error"
             ~constr:
               [| ti_ctr_variant1 "`Exn_string" ti_string &
                  fun s -> `Exn_string s
                |]
             & fun
             [ `Exn_string s -> ti_variant "`Exn_string"
                 [| ubox ti_string s |] ]
           ) :> ti _)
        ;


        value ti_call_resp
         : ti 'o -> ti (call_resp 'o)
         = fun ti_o ->
             let t =
             ((
             new ti_sum_type
               ~type_name:(sprintf "call_resp (%s)" ti_o#type_name)
               ~constr:
                 [| ti_ctr_variant1 "CR_Ok" ti_o &
                    fun a -> CR_Ok a
                  ; ti_ctr_variant1 "CR_Error" ti_call_resp_error &
                    fun a -> CR_Error a
                 |]
               & fun
               [ CR_Ok a -> ti_variant "CR_Ok"
                   [| ubox ti_o a |]
               | CR_Error a -> ti_variant "CR_Error"
                   [| ubox ti_call_resp_error a |]
               ]
             ) :> ti _)
             in
             ( ti_add_ser_deser t
             ; t
             )
        ;

        value ti_dest_put = ti_abs ti_string ti_unit
        ;

        value ti_dest_get = ti_abs ti_unit ti_string
        ;


        value ti_dest_kind =
           ((
           new ti_sum_type
             ~type_name:"dest_kind"
             ~constr:
               [| ti_ctr_variant4 "DRemote"
                  ti_int ti_string ti_dest_put ti_dest_get
                  & fun a b c d -> DRemote a b c d
                |]
             & fun
               [ DRemote a b c d -> ti_variant "DRemote"
                   [| ubox ti_int a ; ubox ti_string b
                    ; ubox ti_dest_put c ; ubox ti_dest_get d
                    |]
               | DLocal a b -> ti_variant "DLocal"
                   [| ubox (new IO.ti ti_unit ()) a
                    ; ubox (new IO.ti ti_unit ()) b
                    |]
               ]
           ) :> ti _)
        ;


        value dest_ubox_get
         : ti (call_resp 'a) -> ref (option (call_resp 'a)) -> (unit -> string)
         = fun ti_cr_a r ->
               (fun () ->
                  match r.val with
                  [ None -> failwith "dest: not filled"
                  | Some a -> ti_ser ti_cr_a a
                  ]
               )
        ;


        value ti_dest
         : ti 'o -> #ti (dest 'o)
         =
         fun ti_o ->
             let tn_dest = "dest" in
             let ti_cr_o = ((ti_call_resp ti_o) :> ti _) in
             let ti_ref_opt_o = new Ref.ti (new Option.ti ti_cr_o ()) () in
             let ti_dest = new ti_record
               ~type_name:(sprintf "dest (%s)" ti_o#type_name)
               ~constr:
                 ( [| (ti_ref_opt_o :> uti) ; (ti_dest_kind :> uti) |]
                 , [| "val" |]
                 , fun
                   [ [| r ; k |] ->
                       { dest_ref = uget_exn ti_ref_opt_o r
                       ; dest_kind = uget_exn ti_dest_kind k
                       }
                   | _ -> assert False
                   ]
                 )
               & fun [ { dest_ref ; dest_kind } ->
                         [| ti_field "dest_ref" ti_ref_opt_o dest_ref
                          ; ti_field "dest_kind" ti_dest_kind dest_kind
                          |]
                 ]
             in
             let ti_dest = (ti_dest :> ti _) in
             ( uti_add_meth ti_dest "ser" &
                 ubox
                   (ti_abs ti_dest ti_string)
                   (fun d ->
                      match d.dest_kind with
                      [ DRemote i tn_o _ _  ->
                          marshal_ser tn_dest (i, tn_o)
                      | DLocal _ _ ->
                          failwith "can't serialize DLocal %s" &
                            ti_dest#type_name
                      ]
                   )
             ; uti_add_meth ti_dest "deser" &
                 ubox
                   (ti_abs ti_string ti_dest)
                   (fun s ->
                      let (i, tn_o) = marshal_deser tn_dest s in
                      if tn_o <> ti_o#type_name
                      then failwith "dest deser: received type_name=%S, \
                                     local type_name=%S"
                                    tn_o ti_o#type_name
                      else
                      let r = ref None in
                      { dest_ref = r
                      ; dest_kind = DRemote
                          i
                          tn_o
                          (fun _s -> failwith
                             "can't put anything into deserialized 'dest'")
                          (dest_ubox_get ti_cr_o r)
                      }
                   )
             ; uti_add_meth ti_dest "is_dest" & ubox ti_unit ()
             ; ti_dest
             )
        ;



      end
    ;
    include Ti;


    (*********************************************************)


    value ty_ver_error ~tyname ~expected ~got =
      Ty_ver (
        object
          method tyname = tyname;
          method expected = expected;
          method got = got; 
        end
      )
    ;

    value ( >>= ) m f = IO.bind f m;

    value return_unit = IO.return ()
    ;

    value gather_to_string len func =
      let str = String.make len '\x00' in
      let rec loop ofs left =
        if left = 0
        then
          IO.return str
        else
          func str ofs left >>= fun has_read ->
          let () = assert (0 < has_read && has_read <= left) in
          loop (ofs + has_read) (left - has_read)
      in
        loop 0 len
    ;

    class virtual typeinfot ['a] =
      object (self)
        method virtual tyname : tyname;
        method virtual tyver : tyver;
        method virtual to_string : 'a -> string;
        method to_output
          (f_output : Substring.t -> IO.m unit)
          (v : 'a)
          : IO.m unit
         =
          f_output (Substring.of_string (self#to_string v))
        ;

        method from_input
          (tyver : tyver)
          len
          (f_input : Substring.t -> IO.m unit)
          : IO.m 'a
         =
          if tyver <> self#tyver
          then
            IO.error (ty_ver_error
              ~tyname:self#tyname ~expected:self#tyver ~got:tyver)
          else
            let str = String.make len '\x00' in
            f_input (Substring.of_string str) >>= fun () ->
            try
              IO.return (self#from_string tyver str)
            with
            [ e -> IO.error e ]
        ;

        (* raises exception on failure, returns deserialized
           value and the rest of the string on success. *)
        method virtual from_substring
          : tyver -> Substring.t -> ('a * Substring.t);

        method from_string tyver str =
          let (v, _rest) = self#from_substring tyver
            (Substring.of_string str) in
          v
        ;
      end
    ;

    class marshal ['a] ?(closures=False) ~name ~ver =
      let flags =
        if closures then [Marshal.Closures] else []
      in
      object (self)
        inherit typeinfot ['a];
        method tyname = name;
        method tyver = ver;
        method to_string (v : 'a) = Marshal.to_string v flags;
        method from_substring got_tyver s =
          if got_tyver <> self#tyver
          then
            raise (ty_ver_error
              ~tyname:self#tyname
              ~expected:self#tyver
              ~got:got_tyver)
          else
            let len = s.Substring.len in
            if len < Marshal.header_size
            then
              raise (deserialize_error self#tyname
                "marshal: less than header_size bytes")
            else
              let str = s.Substring.str in
              let ofs = s.Substring.ofs in
              let total_size = Marshal.total_size str ofs in
              if len < total_size
              then
                raise (deserialize_error self#tyname
                  "marshal: less than total_size bytes")
              else
                let v = ((Marshal.from_string str ofs) : 'a) in
                let rest = Substring.cut_first s total_size in
                (v, rest)
        ;
      end
    ;


    value process_pid p = p.p_pid
    ;

    value () = Printexc.register_printer
      (fun
       [ ECall (`Exn_string str) -> Some ("parvel call exception: " ^ str)
       | _ -> None
       ]
      )
    ;

    value io_of_call_resp = fun
      [ `Ok o -> IO.return o
      | `Error e -> IO.error (ECall e)
      ]
    ;

    value (dest_put : dest 'o -> call_resp 'o -> unit)
    d v =
      match d.dest_ref.val with
      [ Some _ -> failwith "dest_put: already put"
      | None ->
          ( d.dest_ref.val := Some v
          ; match d.dest_kind with
            [ DLocal sink _source -> IO.put_sink sink ()
            | DRemote _ _ _ _ -> ()
            ]
          )
      ]
    ;

    value (dest_pre_map : ('a -> 'b) -> dest 'b -> dest 'a) m d =
      let dest_ref = ref None in
      { dest_ref
      ; dest_kind =
          match d.dest_kind with
          [ DLocal old_sink _old_source ->
              let (mid_source, mid_sink) = IO.pipe1 () in
              let _ : IO.m unit =
                IO.wait_source mid_source >>= fun () ->
                let () = d.dest_ref.val :=
                  match dest_ref.val with
                  [ None -> failwith "dest_pre_map: sink without filling ref"
                  | Some (CR_Ok v) -> Some (CR_Ok (m v))
                  | Some (CR_Error e) -> Some (CR_Error e)
                  ]
                in
                IO.return (IO.put_sink old_sink ())
              and new_source = IO.error (Failure "dest_pre_map: don't wait")
              in
              DLocal mid_sink new_source
          | DRemote _ _ _ _ -> failwith
              "dest_pre_map on DRemote: not implemented"
          ]
      }
    ;

    value _notimpl msg = failwith
      (Printf.sprintf "function %S: not implemented" msg);

    value string_of_process_exit_error = fun
      [ `Exn e -> Printexc.to_string e
      | `Exn_string s -> s
      ]
    ;

    value string_of_process_exit_status = fun
      [ PE_Normal -> "normal exit"
      | PE_Error e -> string_of_process_exit_error e
      ]
    ;


    value map_addrt f a =
      { asend = fun 
         [ Msg x -> a.asend (Msg (f x))
         | (Cmd _) as m -> a.asend m
         ]
      }
    ;

    value mq_set_block_limit c n = c.c_mq_set_block_limit n;
    value mq_set_fail_limit c n = c.c_mq_set_fail_limit n;

    value send_ctx_cmd ctx cmd = ctx.c_send_cmd cmd
    ;

    value send
     : process 'i -> process_message_req 'i -> IO.m unit
     = fun proc msg ->
         proc.p_send_msg msg
    ;

    value addrt_of_proc proc =
      { asend = proc.p_send_msg
      }
    ;

    value (sendt : addrt 'o -> process_message_req 'o -> IO.m unit)
     addrt msg =
      addrt.asend msg
    ;

    value rec io_iter f lst =
      match lst with
      [ [] -> IO.return ()
      | [h :: t] -> f h >>= fun () -> io_iter f t
      ]
    ;

    (***************************)

    value (noinit : dispatcher 'i 'o -> factory 'i 'o) disp =
      fun (_ : context) -> IO.return disp
    ;



    value notify_monitor ~my_pid ~process_exit_status f =
      IO.run_and_ignore_result (f my_pid process_exit_status)
    ;

    value rec (process_loop
      : context ->
        (process 'a) ->
        (IO.Mq.t (process_message_req 'a)) ->
        (_ -> IO.m (process_result 'a)) ->
        _
    )
    context me mq disp =
      IO.catch
        (fun () ->
           ( (* IO.printf "s.c.: waiting\n%!" >>= fun () -> *)
            IO.Mq.take mq >>= fun msg ->
             (* IO.printf "s.c.: taken\n%!" >>= fun () -> *)
            (disp msg : IO.m (process_result _)) >>= fun res ->
            IO.return res
           )
        )
        (fun e -> IO.return (Exit (PE_Error (`Exn e)))
        )
      >>= fun
      [ Exit pe ->
          let () =
            let my_pid = me.p_pid in
            match me.p_status with
            [ PSAlive monitors ->
                ( List.iter
                    (fun fin -> try fin () with [ _ -> () ]
                    )
                    context.c_finalizers
                ; List.iter
                    (notify_monitor ~my_pid ~process_exit_status:pe)
                    monitors
                )
            | PSExited _ ->
                assert False
            ]
          in
            IO.return ()
      | Continue k -> process_loop context me mq k
      ]
    ;

    value exit_normal_ = Exit PE_Normal
    ;

    value process_exit () = IO.return exit_normal_
    ;

    value process_exit_error e = IO.return (Exit (PE_Error e))
    ;

    value process_exit_exn e = IO.return (Exit (PE_Error (`Exn e)))
    ;

    value process_continue k = IO.return (Continue k)
    ;

    value process_exit_by_status = fun ps -> IO.return (Exit ps)
      (* fun
      [ PE_Normal -> process_exit ()
      | PE_Error err -> process_exit_error err
      ] *)
    ;

    value (create_process_inner :
      process_factory 'a ->
      ~mq:(IO.Mq.t _) ->
      IO.m (process 'a)
    )
    factory ~mq =
(*
      let self_ref = ref None in
      let lazy_me = lazy
        (match self_ref.val with [None -> assert False | Some me -> me ])
      in
*)
      let process : process _ =
        { p_send_msg = fun msg -> IO.Mq.put mq msg
        ; p_status = PSAlive []
        ; p_pid = Counter.next pid_local_counter
        }
      in
      let context =
        { c_send_cmd = fun cmd -> IO.Mq.put mq (Cmd cmd)
        ; c_mq_set_block_limit = fun n -> IO.Mq.set_block_limit mq n
        ; c_mq_set_fail_limit = fun n -> IO.Mq.set_fail_limit mq n
        ; c_finalizers = []
        }
      in
      ( (* self_ref.val := Some process *) ()
      ; IO.run_and_ignore_result
          (factory context >>= fun disp ->
           process_loop context process mq disp
          )
      ; IO.return process
      ) 
    ;

    value add_finalizer
     : context -> (unit -> unit) -> unit
     = fun c f ->
         c.c_finalizers := [f :: c.c_finalizers]
    ;


    value (create_process :
      process_factory 'a ->
      IO.m (process 'a)
    )
    disp =
      create_process_inner
        disp
        ~mq:(IO.Mq.create ())
    ;


    value monitor
     : context -> process 'a -> unit
     = fun my_context some_process ->
      let notify_me =
        fun pid pe ->
          send_ctx_cmd my_context (`Exited (pid, pe))
      in
      match some_process.p_status with
      [ PSAlive old ->
          (* if find dupes / remove monitor will be required,
             add [notify_me] to [my_context] and use physical comparision *)
          some_process.p_status := PSAlive [ notify_me :: old ]
      | PSExited st ->
          notify_monitor
            ~my_pid:some_process.p_pid
            ~process_exit_status:st
            notify_me
      ]
    ;


    value string_of_exn = Printexc.to_string
    ;


    value server_return r = IO.return (CR_Ok r)
    ;

    value server_error e = IO.return (CR_Error e)
    ;


    value (create_server_inner :
      server_factory 'i 'o ->
      ~mq:(IO.Mq.t _) ->
      IO.m (server 'i 'o)
      )
    server_factory ~mq =
      let (process_factory : process_factory _) ctx =
        server_factory ctx >>= fun server_disp ->
        IO.return server_loop
        where rec (server_loop : process_dispatcher _) msg =
            (* IO.printf "server_loop: msg\n%!" >>= fun () -> *)
            match msg with
            [ Msg (arg, dest) ->
                IO.catch
                  (fun () -> server_disp arg)
                  (fun e -> IO.return
                     (CR_Error (`Exn_string (string_of_exn e)))
                  )
                >>= fun call_resp ->
                (* IO.printf "server_loop: got reply\n%!" >>= fun () -> *)
                let () = dest_put dest call_resp in
                (* IO.printf "server_loop: put reply\n%!" >>= fun () -> *)
                process_continue server_loop
            | Cmd `Shutdown ->
                process_exit ()
            | Cmd (`Exited _) ->
                process_continue server_loop
            ]
      in
        create_process_inner ~mq process_factory
    ;


    value create_server server_factory =
      create_server_inner
        server_factory
        ~mq:(IO.Mq.create ())
    ;

    value dest_local
     : unit -> dest 'o
     = fun () ->
         let (source, sink) = IO.pipe1 () in
         { dest_ref = ref None
         ; dest_kind = DLocal sink source
         }
    ;


    value dest_remote_counter = ref 0
    ;

    value dest_remote
     : ! 'a . #Cdt.ti 'a -> dest 'a
     =
      fun ti_a ->
        let ti_cr_a = ti_call_resp ti_a in
        let r = ref None in
        ( incr dest_remote_counter
        ; { dest_ref = r
          ; dest_kind =
              DRemote
                dest_remote_counter.val
                ti_a#type_name
                (fun s ->
                   r.val := Some (Cd_Ser.ti_deser ti_cr_a s)
                )
                (dest_ubox_get ti_cr_a r)
          }
        )
    ;


    (* временное: *)
    value dest
     : #Cdt.ti 'o -> dest 'o
     = fun _ti ->
         dest_local ()
    ;


    value dest_get
     : dest 'o -> IO.m (call_resp 'o)
     = fun d ->
         (
         match d.dest_kind with
         [ DLocal _sink source ->
             IO.wait_source source >>= fun () ->
             IO.return "DLocal"
         | DRemote _ _ _ _ -> IO.return "DRemote"
         ]
         ) >>= fun dk ->
         match d.dest_ref.val with
         [ None -> IO.error (
               Failure (Printf.sprintf "dest_get: no data (%s)" dk)
             )
         | Some cr -> IO.return cr
         ]
    ;

    value dest_get_val
     : dest 'o -> IO.m 'o
     = fun d ->
         dest_get d >>= fun
         [ CR_Ok v -> IO.return v
         | CR_Error (`Exn_string s) -> IO.error (Failure
               (Printf.sprintf "Parvel.dest_get_val: error: %s" s)
             )
         ]
    ;

    (* синхронный вызов *)
    value (call : server 'i 'o -> 'i -> IO.m (call_resp 'o)) server arg =
      let dest = dest_local () in
      send server (Msg (arg, dest)) >>= fun () ->
      dest_get dest
    ;

    value (call_io : server 'i 'o -> 'i -> IO.m 'o) server arg =
      call server arg >>= fun
      [ CR_Ok r -> IO.return r
      | CR_Error e -> IO.error (ECall e)
      ]
    ;

    (* ответы на сообщения будут производиться через передаваемый
      в функцию контекст, где будут функции send для простых процессов
      и reply для call-подобных. *)

    module Map
     :
      sig
        type map 'k 'v;
        value empty : ('k -> 'k -> int) -> map 'k 'v;
        value add : 'k -> 'v -> map 'k 'v -> map 'k 'v;
        value find_opt : map 'k 'v -> 'k -> option 'v;
        value keys : map 'k 'v -> list 'k;
        value fold : ('k -> 'v -> 'a -> 'a) -> map 'k 'v -> 'a -> 'a;
        value remove : 'k -> map 'k 'v -> map 'k 'v;
      end
     =
      struct
        type map 'k 'v = (('k -> 'k -> int) * list ('k * 'v));
        value empty key_cmp = (key_cmp, []);
        value add k v (cmp, m) = (cmp, [(k, v) :: m]);
        value find_opt (cmp, m) k =
          inner m
          where rec inner m =
            match m with
            [ [] -> None
            | [(hk, hv) :: t] ->
                if cmp k hk = 0 then Some hv else inner t
            ]
        ;
        value keys (_cmp, m) = List.map fst m;
        value fold func (_cmp, m) init =
          List.fold_left
            (fun acc (k, v) ->
               func k v acc
            )
            init
            m
        ;
        value remove the_k (cmp, m) =
          (cmp, List.filter (fun (k, _v) -> (cmp the_k k) <> 0) m)
        ;
      end
    ;

    value filter_keys_over_mapfold mapfold =
      fun pred m ->
        mapfold
          (fun k v a ->
             if pred k v
             then [k :: a]
             else a
          )
          m
          []
    ;

    value map_filter_keys pred m =
      filter_keys_over_mapfold Map.fold pred m
    ;

    (* switch-диспетчер *)

    type switch_req 'k 'i 'o =
      [= `Add_worker of ('k * server 'i 'o)
      |  `Call of ('k * 'i)
      |  `Get_keys
      ]
    ;


    type switch_resp_call 'o =
      [ SRC_Res of 'o
      | SRC_No_worker_for_key
      | SRC_Call_error of call_resp_error
      ]
    ;

    type switch_resp 'k 'i 'o =
      [ SR_Res of 'o
      | SR_No_worker_for_key
      | SR_Worker_added
      | SR_Keys of list 'k
      ]
    ;

    type switch 'k 'i 'o =
      server (switch_req 'k 'i 'o) (switch_resp 'k 'i 'o)
    ;

    value (create_switch :
      ?key_cmp : ('k -> 'k -> int) ->
      unit ->
      IO.m (switch 'k 'i 'o))
      ?(key_cmp = Pervasives.compare)
      () =
        let workers = ref (Map.empty key_cmp) in
        create_process
          (fun ctx ->
             IO.return loop
             where rec (loop : process_dispatcher _) = fun
             [ Msg (`Add_worker (k, w), dest) ->
                 ( workers.val := Map.add k w workers.val
                 ; monitor ctx w
                 ; dest_put dest (CR_Ok SR_Worker_added)
                 ; process_continue loop
                 )
             | Msg (`Call (k, i), dest) ->
                 match Map.find_opt workers.val k with
                 [ None ->
                     ( dest_put dest (CR_Ok SR_No_worker_for_key)
                     ; process_continue loop
                     )
                 | Some w ->
                     let new_dest = dest_pre_map (fun r -> (SR_Res r)) dest in
                     send w (Msg (i, new_dest)) >>= fun () ->
                     process_continue loop
                 ]
             | Msg (`Get_keys, dest) ->
                 ( dest_put dest (CR_Ok (SR_Keys (Map.keys workers.val)))
                 ; process_continue loop
                 )
             | Cmd `Shutdown ->
                 (* где-то тут надо как бы разослать привет детишкам.
                    однако подумать: если дети сами регистрируются,
                    может сами и к ктулху отправятся?
                    с третьей стороны, подумать, что как-то да надо
                    намекнуть детям, что свитч вышел.
                  *)
                 process_exit ()
             | Cmd (`Exited (the_pid, status)) ->
                 (match status with
                  [ PE_Normal ->
                      IO.printf "Parvel.switch: normal worker's exit.  wtf?\n"
                  | PE_Error _ ->
                      IO.return ()
                  ]
                 ) >>=
                 fun () ->
                 let exited_keys = map_filter_keys
                   (fun _key process -> process.p_pid = the_pid)
                   workers.val
                 in
                 let () =
                   workers.val :=
                     List.fold_left
                       (fun workers exited_key ->
                          Map.remove exited_key workers
                       )
                       workers.val
                       exited_keys
                 in
                 process_continue loop
             ]
          )
    ;

    exception Switch_error of string
    ;

    value (add_worker : switch 'k 'i 'o ->
      'k -> server 'i 'o -> IO.m unit)
      sw k worker =
        call_io sw (`Add_worker k worker) >>= fun
        [ SR_Worker_added -> IO.return ()
        | SR_No_worker_for_key | SR_Res _ | SR_Keys _ ->
            IO.error (Switch_error "add_worker: unexpected result")
        ]
    ;

    value (call_switch : switch 'k 'i 'o ->
      'k -> 'i -> IO.m (switch_resp_call 'o)
    )
      sw k i =
        call sw (`Call k i) >>= fun
        [ CR_Ok (SR_Res r) -> IO.return (SRC_Res r)
        | CR_Ok SR_No_worker_for_key -> IO.return SRC_No_worker_for_key
        | CR_Ok (SR_Worker_added | SR_Keys _) -> IO.error
            (Switch_error "call_switch: unexpected result")
        | CR_Error e -> IO.return (SRC_Call_error e)
        ]
    ;

    value (call_switch_io : switch 'k 'i 'o ->
      'k -> 'i -> IO.m 'o
    )
      sw k i =
        call_switch sw k i >>= fun
        [ SRC_Res r -> IO.return r
        | SRC_Call_error e -> IO.error (ECall e)
        | SRC_No_worker_for_key -> IO.error (Switch_error
             "call_switch: no worker for key")
        ]
    ;


    value (switch_keys : switch 'k 'i 'o -> IO.m (list 'k)) sw =
      call_io sw `Get_keys >>= fun
      [ SR_Keys ks -> IO.return ks
      | SR_Res _ | SR_No_worker_for_key | SR_Worker_added ->
          IO.error (Switch_error
            "switch_keys: unexpected result")
      ]
    ;


    (* servers with state *)

    value (add_state_to_server :
      server_factory ('i * 's) ('o * 's) ->
      's ->
      server_factory 'i 'o
    )
    in_factory state =
      let out_factory ctx =
        in_factory ctx >>= fun in_disp ->
        IO.return out_disp
        where out_disp : server_dispatcher 'i 'o =
          let state = ref state in
          fun msg ->
            let old_state = state.val in
            in_disp (msg, old_state) >>= fun
            [ CR_Ok (res, new_state) ->
                ( if old_state != new_state
                  then state.val := new_state
                  else ()
                ; IO.return (CR_Ok res)
                )
            | CR_Error e -> IO.return (CR_Error e)
            ]
      in
        out_factory
    ;


    (*******************************************************)

    (* process_limit: no more than N processes at time,
       with respawning.
     *)

    (*
       Расклад для процесса, порождённого на основании пользовательской
       "фабрики", рождающей процессы, берущие сообщение с типом 'i.

       На выходе --- результирующий процесс, цель которого -- принимать
       сообщения с типом 'i, порождать пользовательские процессы, и следить,
       чтобы:
         1. их было не больше N
         2. не жралась бесконтрольно память на внутренние нужды
         3. в случае наличия сообщений в очереди они как-то да
            обрабатывались, в идеале -- ровно N процессами
         4. в будущем можно было бы прибивать ненужные, долго
            простаивающие процессы.


       Логика работы результирующего процесса:

         Состояние:
           - общая очередь сообщений для пользовательских процессов
           - M = текущее количество пользовательских процессов

         На вход поступает сообщение с типом 'i:
         Msg 'i ->

           - если M < N
             то
               - узнать у общей очереди, сможет ли кто-нибудь
                 читать из неё сейчас

               - отправить сообщение в общую очередь неблокирующим образом

               - если нет читающих, то послать монитору сообщение Рожай
                 неблокирующим образом, новое состояние: M := M + 1

             иначе (M >= N)

               - поставить сообщение в очередь блокирующим образом --
                 подождать, пока это сообщение не подхватит кто-то из
                 пользовательских процессов


       Логика работы монитора:

         На вход поступают сообщения с типом [Рожай] и некрологи:

         Msg Рожай ->

           - родить ещё один пользовательский процесс, читающий из общей
             очереди, начать мониторить его (тут как-то продумать, чтобы
             это атомарным образом сделать, наверное)

         Cmd (`Exited _) ->

           - то же самое, что при Msg Рожай


       Итого:

         1. Каждое входящее сообщение будет поставлено в общую очередь
            для пользовательских процессов,

         2. Монитор будет поддерживать столько пользовательских процессов
            запущенными, сколько раз получил от главного процесса
            сообщение Рожай.
    *)


    value cmd_shutdown = Cmd `Shutdown;

    value (process_limit :
      ?nmax:int ->
      ?dbg:(string -> unit) ->
      (factory 'i 'o) ->
      factory 'i 'o
    )
    ?(nmax=42) ?dbg in_fact =

      let dbg msg =
        match dbg with
        [ None -> ()
        | Some f -> f msg
        ]
      in

      fun _out_context ->

        let common_mq = IO.Mq.create () in

        let msg_spawn = Msg `Spawn in

        let monitor_factory mcontext =
          let do_spawn () =
            create_process_inner
              in_fact ~mq:common_mq >>= fun process ->
              let () = monitor mcontext process in
              let () = dbg "mon: spawned" in
              IO.return ()
          in
          IO.return (monitor_disp ~count:0 ~fin:False)
          where rec monitor_disp ~count ~fin = fun
            [ Msg `Spawn ->
                let () = dbg "mon: `Spawn" in
                do_spawn () >>= fun () ->
                process_continue (monitor_disp ~count:(count + 1) ~fin)

            | Cmd (`Exited _) ->
                if not fin
                then
                  let () = dbg "mon: `Exited (fin=False)" in
                  do_spawn () >>= fun () ->
                  process_continue (monitor_disp ~count ~fin)
                else
                  let new_count = count - 1 in
                  let () = dbg (Printf.sprintf
                    "mon: `Exited (fin=True, new_count=%i)" new_count) in
                  if new_count <= 0
                  then
                    process_exit ()
                  else
                    process_continue (monitor_disp ~count:new_count ~fin)

            | Cmd `Shutdown ->
                let () = dbg "mon: `Shutdown" in
                (loop count >>= fun () ->
                 process_continue (monitor_disp ~count ~fin:True)
                )
                where rec loop left =
                  if left = 0
                  then IO.return ()
                  else
                    IO.Mq.put common_mq cmd_shutdown >>= fun () ->
                    loop (left - 1)
            ]
        in

        create_process monitor_factory >>= fun monitor ->
  
        IO.return (out_disp ~count:0)
        where rec out_disp ~count = fun
        [ (Msg _) as msg ->
            let () = dbg "lim: Msg" in

            if count < nmax
            then
              let () = dbg "lim:   count < nmax" in
              let any_reader = IO.Mq.idle_reader_exists common_mq in
              IO.Mq.put common_mq msg >>= fun () ->
              (if not any_reader
               then
                 let () = dbg "lim:     no readers" in
                 send monitor msg_spawn >>= fun () ->
                 IO.return (count + 1)
               else
                 let () = dbg "lim:     have reader" in
                 IO.return count
              ) >>= fun new_count ->
              process_continue (out_disp ~count:new_count)
            else
              (* count >= nmax *)
              let () = dbg "lim:   count >= nmax" in

              IO.Mq.put_blocking common_mq msg >>= fun () ->
              process_continue (out_disp ~count)

        | Cmd (`Exited _) ->
            (* мы никого не мониторим *)
            let () = dbg "lim: `Exited" in
            process_continue (out_disp ~count)

        | Cmd `Shutdown ->
            let () = dbg "lim: `Shutdown" in
            send monitor cmd_shutdown >>= fun () ->
            process_exit ()
        ]
    ;

    (*************************************************************)


    value (io_res : (unit -> IO.m 'a)
                 -> IO.m [= `Ok of 'a | `Error of exn ]
          ) func =
      IO.catch
        (fun () -> func () >>= fun r -> IO.return (`Ok r))
        (fun e -> IO.return (`Error e))
    ;


    (* [pipe 'i 'o] is constructor that takes [addrt 'o] to write
       "output" messages to this typed address, and returns
       IO-wrapped [process 'i] that receives process messages
       of type ['i], does anything that processes usually do,
       and writes to specified [addrt 'o].
     *)

    type pipe 'i 'o = addrt 'o -> IO.m (process 'i)
    ;


    (* stream transform: many to many *)

    value stream_transform
      (fact : factory ('i * 's) ((list 'o) * 's))
      (state : 's)
     :
      pipe 'i 'o
     =
      fun addr ->
      create_process (
      fun context ->
        fact context >>= fun disp ->
        let rec st_loop ~state msg =
          let cont ~state = process_continue (st_loop ~state) in
          match msg with
          [ Msg m ->
              io_res (fun () -> disp (m, state)) >>= fun
              [ `Ok (outlist, state) ->
                  io_iter (fun m -> sendt addr (Msg m)) outlist >>= fun () ->
                  cont ~state
              | `Error e -> process_exit_error (`Exn e)
              ]
          | Cmd `Shutdown -> process_exit ()
          | Cmd (`Exited _) -> cont ~state
          ]
        in
          IO.return (st_loop ~state)
      )
    ;


    (*************************************************************)

    (* combine_pairs: combines messages tagged by `Fst and `Snd variants
       pairwise, in the order of their arrival.
       [`Exit_filling_snd x] is like sending [`Snd x] until all [`Fst _]
       will be processed, then exitting the process.
     *)

    value (combine_pairs :
      ('a -> 'b -> IO.m unit) ->
      process_factory
      [= `Fst of 'a
      |  `Snd of 'b
      |  `Exit_filling_snd of 'b
      ]
    )
    func =
      fun _context ->
        let q1 = Queue.create ()
        and q2 = Queue.create () in
        let rec loop = fun
        [ Msg (`Fst a) -> (Queue.push a q1; after_push ())
        | Msg (`Snd b) -> (Queue.push b q2; after_push ())
        | Msg (`Exit_filling_snd b) -> exit_filling_snd b
        | Cmd `Shutdown -> process_exit ()
        | Cmd (`Exited _) -> process_continue loop
        ]
        and exit_filling_snd b =
          if Queue.is_empty q1
          then
            process_exit ()
          else
            let a = Queue.take q1 in
            func a b >>= fun () ->
            exit_filling_snd b
        and after_push () =
          (if (Queue.is_empty q1) || (Queue.is_empty q2)
           then
             return_unit
           else
             let a = Queue.take q1
             and b = Queue.take q2 in
             func a b
          ) >>= fun () ->
          process_continue loop
        in
          IO.return loop
    ;


    (* [server_of_pipe_seq] creates a server from pipe, assuming
       that sequential messages sent by pipe are replies to sequential
       requests sent to pipe.
     *)

    value (server_of_pipe_seq : pipe 'i 'o -> IO.m (server 'i 'o)) pipe =

      create_process (fun context ->

        create_process
          (combine_pairs (fun a b -> IO.return (dest_put a b)))
        >>= fun combiner ->

        let combiner_addrt = addrt_of_proc combiner in

        let resp_addr = map_addrt (fun x -> `Snd (CR_Ok x)) combiner_addrt in
        let dests_addr = map_addrt (fun x -> `Fst x) combiner_addrt in

        pipe resp_addr >>= fun in_proc ->

        let () = monitor context in_proc in

        let rec (dispatcher : process_dispatcher (call 'i 'o)) msg =
          match msg with
          [ Cmd `Shutdown ->
              send in_proc (Cmd `Shutdown) >>=
              cont
          | Cmd (`Exited (pid, st)) ->
              if pid = in_proc.p_pid
              then
                let cr = `Exn_string (string_of_process_exit_status st) in
                send combiner (Msg (`Exit_filling_snd (CR_Error cr)))
                >>= fun () ->
                process_exit ()
              else
                cont ()
          | Msg (rq, dest) ->
              sendt dests_addr (Msg dest) >>= fun () ->
              send in_proc (Msg rq) >>=
              cont
          ]
        and cont () =
          process_continue dispatcher
        in

        IO.return dispatcher
      )

    ;


(*
    value server_retry
     : ?retries:int -> ?init_timeout:float -> server_factory 'i 'o -> sf
     = fun ?(retries=3) ?(init_timeout=0.2) serv_fact ->
         .
    ;
*)


    (* respawns server on error, up to [max_count] times, then
       returns last error.
     *)

    value server_respawn
     : ! 'i 'o . ?max_count:int -> server_factory 'i 'o -> server_factory 'i 'o
     = fun ?(max_count=10) in_fact ->
         let () = assert (max_count > 0) in
         fun _ctx ->

           let opt_serv = ref None in

           let out_disp i =
             loop None max_count
             where rec loop last_error left =
               match (left, opt_serv.val, last_error) with
               [ (0, _, None) -> assert False
               | (0, None, Some e) -> server_error e
               | (left, None, last_error) ->
                   create_server in_fact >>= fun serv ->
                   ( opt_serv.val := Some serv
                   ; loop last_error left
                   )
               | (left, Some serv, _l) ->
                   call serv i >>= fun
                   [ CR_Ok r -> server_return r
                   | CR_Error e ->
                       send serv (Cmd `Shutdown) >>= fun () ->
                       ( opt_serv.val := None
                       ; loop (Some e) (left - 1)
                       )
                   ]
               ]
           in
             IO.return out_disp
    ;


    (*************************************************************)

    module Proto
     =
      struct

        open Cd_All; open Cdt; open Cd_Ser;

        value rec get_dests
         : ubox -> list (int * (string -> unit) * (unit -> string))
                       (* id, deserialize, serialize *)
         = fun u ->
             let rec get_dests_td td u =
               match td with
               [ Simple _ -> []
               | Dispatch_method disp -> get_dests_td (disp "ser") u
               | Sum_type destr _constr ->
                   let (_vname, disp) = destr u in
                   let uarr = disp "ser" in
                   get_dests_arr uarr
               | Record_type destr _utis _fields _constr ->
                   let uarrfn = destr u in
                   let uarr = Array.map (fun (_field_name, u) -> u) uarrfn in
                   get_dests_arr uarr
               | Lambda _ _ _ -> []
               | Tuple destr _utis _constr ->
                   get_dests_arr (destr u)
               ]

             and get_dests_arr uarr =
               List.concat & Array.map_to_list get_dests uarr

             in
               let uti = u.ub_uti in
               if has_meth "is_dest" uti
               then
                 match uti#type_desc with
                 [ Tuple _destr _utis _constr
                     -> assert False
                 | Simple _
                 | Lambda _ _ _
                 | Sum_type _ _
                     -> assert False

                 | Record_type destr _utis _fields _constr ->
                     match destr u with
                     [ [| ("dest_ref", _ur) ; ("dest_kind", uk) |] ->
                         match uk.ub_uti#type_desc with
                         [ Sum_type destr _constr ->
                             match destr uk with
                             [ ("DRemote", disp) ->
                                 let uarr = disp "get_dests" in
                                 match uarr with
                                 [ [| ui ; _u_tn ; uput_dest ; uget_dest |] ->
                                      [ ( uget_exn ti_int ui
                                        , fun s ->
                                            uget_exn ti_unit &
                                              u_app uput_dest (ubox ti_string s)
                                        , fun () ->
                                            uget_exn ti_string &
                                              u_app uget_dest (ubox ti_unit ())
                                        )
                                      ]
                                 | _ -> assert False
                                 ]
                             | _ -> assert False
                             ]
                         | Tuple _ _ _ | Simple _ | Lambda _ _ _
                         | Dispatch_method _ | Record_type _ _ _ _
                             -> assert False
                         ]
                     | _ -> assert False
                     ]

                 | Dispatch_method _
                     -> assert False
                 ]
               else
                 get_dests_td u.ub_uti#type_desc u
        ;


        type proto_call_resp = list (int * string)
        ;

        value ti_resp_elem =
          new Tuple2.ti
                ti_int
                ti_string
                ()
        ;
        value () = ti_add_ser_deser (ti_resp_elem :> ti _)
        ;

        value ti_proto_call_resp : #ti proto_call_resp =
          new List.ti ti_resp_elem
            ()
        ;
        value ti_proto_call_resp = (ti_proto_call_resp :> ti _)
        ;
        value () = ti_add_ser_deser ti_proto_call_resp
        ;



        value sort_dests =
          List.sort (fun (a, _, _) (b, _, _) -> compare a b)
        ;


        value proto_call
         : ti 'p -> process 'p -> 'p -> unit
         = fun ti_proto server p ->
           (*
             let dests : list (int * (string -> unit) * (unit -> string)) =
               sort_dests &
               get_dests &
               ubox ti_proto p
             in
             let () =
             ( List.iter
                 (fun (i, _d, _s) ->
                    dbg "dest found: id = %i\n%!" i
                 )
                 dests
             ; printf "dests total: %i\n%!" dests_count
             )
             in
             let proto_call_resp = server & ti_ser ti_proto p in
             let filled_dests = ti_deser ti_proto_call_resp proto_call_resp in
             let () = List.iter2
               (fun (sd_id, sd_put, _sd_get) (rc_id, rc_data) ->
                  if sd_id <> rc_id
                  then failwith "call_proto: dest id's mismatch (sd=%i rc=%i)"
                         sd_id rc_id
                  else
                    sd_put rc_data
               )
               dests
               filled_dests
             in
             ()
           *)
           (* тут -- только локальный случай. *)
           let () = ignore ti_proto in
           IO.run_and_ignore_result (send server (Msg p))
        ;


        value proto_server
         : ti 'p -> process_factory 'p -> process_factory 'p
         = fun ti_proto inner_factory ->
             (*
             let p_deser = ti_deser ti_proto in
             fun i_str ->
               let i = p_deser i_str in
               let dests : list (int * (string -> unit) * (unit -> string)) =
                 sort_dests &
                 get_dests &
                 ubox ti_proto i
               in
               let () = server_func i in
               let filled : proto_call_resp = List.map
                 (fun (i, _sd_put, sd_get) -> (i, sd_get ())
                 )
                 dests
               in
               ti_ser ti_proto_call_resp filled
             *)
             (* тут -- только локальный случай. *)
             let () = ignore ti_proto in

             fun outer_ctx ->
               create_process inner_factory >>= fun inner_process ->
               let () = monitor outer_ctx inner_process in
               let inner_pid = process_pid inner_process in
               let rec outer_disp = fun
                 [ Msg _ as msg ->
                     (* пред/пост обработка -- тут. *)
                     pass msg
                 | Cmd `Shutdown as msg -> pass msg
                 | Cmd (`Exited (pid, ps)) as msg ->
                     if pid = inner_pid
                     then process_exit_by_status ps
                     else pass msg
                 ]
               and pass msg =
                 send inner_process msg >>= fun () ->
                 process_continue outer_disp
               in
                 IO.return outer_disp
        ;


      end
    ;


    value proto_server = Proto.proto_server
    ;


    (*************************************************************)

    module type IT_TYPE
     =
      sig

        module Subarray
         :
          sig
            type t 'el;
            value of_string : string -> t char;
            value of_array : array 'el -> t 'el;
          end
        ;

        type err_msg = exn
        ;

        exception Divergent_iteratee of string
        ;

        type stream 'el =
          [ EOF of option err_msg
          | Chunk of Subarray.t 'el
          ]
        ;

        type iteratee 'el 'a =
          [ IE_done of 'a
          | IE_cont of option err_msg
                    and (stream 'el ->
                         IO.m (iteratee 'el 'a  * stream 'el))
          ]
        ;

      end
    ;


    exception Iteratee_doesn't_want_data;
    exception Iteratee_fails_without_data of exn;

    module It_pipe (I : IT_TYPE)
     :
      sig
        value pipe_of_iteratee :
          I.iteratee 'el 'a -> pipe (I.Subarray.t 'el) 'a
        ;
      end
     =
      struct

        value pipe_of_iteratee orig_it addr =
          create_process (fun _context ->

            let send x = sendt addr (Msg x) in

            let kont_of_it it =
              match it with
              [ I.IE_done _ ->
                  IO.error Iteratee_doesn't_want_data
              | I.IE_cont None k ->
                  IO.return k
              | I.IE_cont (Some e) _ ->
                  IO.error (Iteratee_fails_without_data e)
              ]
            in

            kont_of_it orig_it >>= fun orig_kont ->

            let rec run_repeat k s =
              k s >>= fun
              [ (I.IE_done x, s) ->
                  send x >>= fun () ->
                  run_repeat orig_kont s
              | (I.IE_cont (Some e) _, _) ->
                  IO.return (`Error e)
              | (I.IE_cont None k, _) ->
                  IO.return (`Moar k)
              ]
            in

            let eof_k k =
              k (I.EOF None) >>= fun (i, _s) ->
              match i with
              [ I.IE_done x ->
                  send x >>= fun () ->
                  process_exit ()
              | I.IE_cont (Some e) _ ->
                  process_exit_exn e
              | I.IE_cont None _ ->
                  process_exit_exn (I.Divergent_iteratee
                    "Parvel.pipe_of_iteratee")
              ]
            in

            let rec disp k msg =
              let cont k = process_continue (disp k) in
              match msg with
              [ Cmd `Shutdown ->
                  eof_k k

              | Cmd (`Exited _) -> cont k

              | Msg c ->
                  run_repeat k (I.Chunk c) >>= fun
                  [ `Error e -> process_exit_exn e
                  | `Moar k -> cont k
                  ]
              ]

            in
              IO.return (disp orig_kont)
          )
        ;
      end
    ;


    (*************************************************************)

    (* registering and running programs *)

    type program_exec_type =
      [= `Main | `Per_process ]
    ;

    value progs_queue
     : Queue.t (program_exec_type * string * (unit -> IO.m unit))
     = Queue.create ()
    ;

    value register_program prog_exec_type prog_name prog_code =
      Queue.push (prog_exec_type, prog_name, prog_code) progs_queue
    ;


    value run_programs_pred pred () =
      let (_names, codes) =
        Queue.fold
          (fun ((acc_n, acc_c) as accs) (pet, pn, pc) ->
             if pred pet
             then ([pn :: acc_n], [pc :: acc_c])
             else accs
          )
          ([], [])
          progs_queue
      in
      let () = Queue.clear progs_queue in
      IO.join (List.map (fun c -> c ()) codes)
    ;

    value run_programs () =
      run_programs_pred (fun _ -> True) ()
    ;

(*
  end
;
*)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.