jupyter_kernel_1.0.0_8c987c13/sources/jupyter/jupyter-start_kernel.adb

  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
--  SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com>
--
--  SPDX-License-Identifier: MIT
----------------------------------------------------------------

with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Containers.Hashed_Maps;
with Ada.Wide_Wide_Text_IO;
with GNAT.SHA256;
with Interfaces.C;

with League.Text_Codecs;
with League.Holders;
with League.JSON.Documents;
with League.JSON.Objects;
with League.JSON.Values;
with League.Stream_Element_Vectors;
with League.Strings;
with League.Strings.Hash;

with ZMQ.Contexts;
with ZMQ.Messages;
with ZMQ.Sockets;
with ZMQ.Low_Level;

procedure Jupyter.Start_Kernel
  (Kernel : in out Jupyter.Kernels.Kernel'Class;
   File   : League.Strings.Universal_String)
is
   function "+" (Text : Wide_Wide_String)
     return League.Strings.Universal_String
       renames League.Strings.To_Universal_String;

   function "-" (Text : Wide_Wide_String) return League.JSON.Values.JSON_Value;

   procedure Read_Connection_File
     (Name   : League.Strings.Universal_String;
      Result : out League.JSON.Objects.JSON_Object);

   procedure Bind
     (Ctx    : ZMQ.Contexts.Context;
      Socket : in out ZMQ.Sockets.Socket;
      CF     : League.JSON.Objects.JSON_Object;
      Port   : Wide_Wide_String;
      Kind   : ZMQ.Sockets.Socket_Type);

   type Frontend_Connection is record
      Ctx     : ZMQ.Contexts.Context;
      Key     : League.Strings.Universal_String;
      Shell   : ZMQ.Sockets.Socket;
      Stdin   : ZMQ.Sockets.Socket;
      IOPub   : ZMQ.Sockets.Socket;
      Control : ZMQ.Sockets.Socket;
      Ping    : ZMQ.Sockets.Socket;
   end record;

   package IO_Pubs is
      type IO_Pub (Up : not null access Frontend_Connection) is
        new Jupyter.Kernels.IO_Pub with
      record
         Request : League.JSON.Objects.JSON_Object;
         Id      : Positive;
         Count   : Positive;
      end record;

      overriding procedure Stream
        (Self : in out IO_Pub;
         Name : League.Strings.Universal_String;
         Text : League.Strings.Universal_String);

      overriding procedure Display_Data
        (Self      : in out IO_Pub;
         Data      : League.JSON.Objects.JSON_Object;
         Metadata  : League.JSON.Objects.JSON_Object;
         Transient : League.JSON.Objects.JSON_Object);

      overriding procedure Update_Display_Data
        (Self      : in out IO_Pub;
         Data      : League.JSON.Objects.JSON_Object;
         Metadata  : League.JSON.Objects.JSON_Object;
         Transient : League.JSON.Objects.JSON_Object);

      overriding procedure Execute_Result
        (Self      : in out IO_Pub;
         Data      : League.JSON.Objects.JSON_Object;
         Metadata  : League.JSON.Objects.JSON_Object;
         Transient : League.JSON.Objects.JSON_Object);

      overriding procedure Execute_Error
        (Self  : in out IO_Pub;
         Value : Jupyter.Kernels.Execution_Error);

      overriding procedure Clear_Output
        (Self  : in out IO_Pub;
         Wait  : Boolean);

      overriding procedure Debug_Event
        (Self      : in out IO_Pub;
         Content   : League.JSON.Objects.JSON_Object);
   end IO_Pubs;

   package Address_Lists is new Ada.Containers.Doubly_Linked_Lists
     (League.Stream_Element_Vectors.Stream_Element_Vector,
      League.Stream_Element_Vectors."=");

   function "-"
     (Text : League.Strings.Universal_String) return Address_Lists.List;

   procedure Send_Message
     (Socket  : in out ZMQ.Sockets.Socket;
      To      : Address_Lists.List;
      Key     : League.Strings.Universal_String;
      Kind    : Wide_Wide_String;
      Parent  : League.JSON.Objects.JSON_Object :=
        League.JSON.Objects.Empty_JSON_Object;
      Content : League.JSON.Objects.JSON_Object :=
        League.JSON.Objects.Empty_JSON_Object);

   package body IO_Pubs is separate;

   type Message is record
      From      : Address_Lists.List;
      Signature : League.Strings.Universal_String;
      Header    : League.JSON.Objects.JSON_Object;
      Parent    : League.JSON.Objects.JSON_Object;
      Metadata  : League.JSON.Objects.JSON_Object;
      Content   : League.JSON.Objects.JSON_Object;
   end record;

   procedure Read_Message
     (Socket : ZMQ.Sockets.Socket;
      Key    : League.Strings.Universal_String;
      Result : out Message);

   procedure Process_Shell_Message
     (Frontend : aliased in out Frontend_Connection;
      Request  : Message);

   function Has_More (Message : ZMQ.Messages.Message) return Boolean;

   type Session_Information is record
      Id    : Positive;
      Count : Positive;
   end record;

   package Session_Maps is new Ada.Containers.Hashed_Maps
     (Key_Type        => League.Strings.Universal_String,
      Element_Type    => Session_Information,
      Hash            => League.Strings.Hash,
      Equivalent_Keys => League.Strings."=");

   Next_Id : Positive := 1;
   Map     : Session_Maps.Map;

   ---------
   -- "-" --
   ---------

   function "-" (Text : Wide_Wide_String)
     return League.JSON.Values.JSON_Value is
   begin
      return League.JSON.Values.To_JSON_Value (+Text);
   end "-";

   ---------
   -- "-" --
   ---------

   function "-"
     (Text : League.Strings.Universal_String) return Address_Lists.List
   is
      Codec : constant League.Text_Codecs.Text_Codec :=
        League.Text_Codecs.Codec_For_Application_Locale;
   begin
      return Result : Address_Lists.List do
         Result.Append (Codec.Encode (Text));
      end return;
   end "-";

   ----------
   -- Bind --
   ----------

   procedure Bind
     (Ctx    : ZMQ.Contexts.Context;
      Socket : in out ZMQ.Sockets.Socket;
      CF     : League.JSON.Objects.JSON_Object;
      Port   : Wide_Wide_String;
      Kind   : ZMQ.Sockets.Socket_Type)
   is
      Image : constant String := CF.Value (+Port).To_Integer'Img;
      Address : constant String :=
        CF.Value (+"transport").To_String.To_UTF_8_String &
        "://" &
        CF.Value (+"ip").To_String.To_UTF_8_String &
        ":" & Image (2 .. Image'Last);
   begin
      Socket.Initialize (Ctx, Kind);
      Socket.Bind (Address);
   end Bind;

   --------------
   -- Has_More --
   --------------

   function Has_More (Message : ZMQ.Messages.Message) return Boolean is
      use type Interfaces.C.int;
   begin
      return ZMQ.Low_Level.zmq_msg_more (Message.GetImpl) /= 0;
   end Has_More;

   -------------
   -- Process --
   -------------

   procedure Process_Shell_Message
     (Frontend : aliased in out Frontend_Connection;
      Request  : Message)
   is
      use type League.Strings.Universal_String;
      Topic  : League.Strings.Universal_String;
      Reply  : League.JSON.Objects.JSON_Object;
      Action : League.Strings.Universal_String :=
        Request.Header.Value (+"msg_type").To_String;
   begin
      if Action.Ends_With ("_request") then
         Action := Action.Head_To (Action.Length - 8);
         Topic := Action & "_reply";
      else
         --  No _request in msg_type, ignore it
         return;
      end if;

      declare
         Content : League.JSON.Objects.JSON_Object;
      begin
         Content.Insert (+"execution_state", -"busy");
         Send_Message
           (Frontend.IOPub,
            -Topic,
            Frontend.Key,
            "status",
            Parent  => Request.Header,
            Content => Content);
      end;

      if Action = +"kernel_info" then
         Kernel.Kernel_Info (Reply);
         Send_Message
           (Frontend.Shell,
            Request.From,
            Frontend.Key,
            "kernel_info_reply",
            Parent  => Request.Header,
            Content => Reply);
      elsif Action = +"execute" then
         declare
            S : constant League.Strings.Universal_String :=
              Request.Header.Value (+"session").To_String;
            Input  : League.JSON.Objects.JSON_Object := Request.Content;
            Values : League.JSON.Objects.JSON_Object;
            Error  : Jupyter.Kernels.Execution_Error;
            Object : Jupyter.Kernels.Session_Access;
            Count  : League.Holders.Universal_Integer;
            IO_Pub : aliased IO_Pubs.IO_Pub :=
              (Frontend'Unchecked_Access,
               Request.Header,
               others => <>);
         begin
            if not Map.Contains (S) then
               IO_Pub.Id := Next_Id;
               IO_Pub.Count := 1;
               Count := 1;
               Kernel.Create_Session (IO_Pub.Id, Object);
               Map.Insert (S, (IO_Pub.Id, IO_Pub.Count));
               Next_Id := Next_Id + 1;
            else
               Map (S).Count := Map (S).Count + 1;
               IO_Pub.Id := Map (S).Id;
               IO_Pub.Count := Map (S).Count;
               Object := Kernel.Get_Session (IO_Pub.Id);
               Count := League.Holders.Universal_Integer (IO_Pub.Count);
            end if;

            Input.Insert
              (+"execution_count",
               League.JSON.Values.To_JSON_Value (Count));

            Send_Message
              (Frontend.IOPub,
               -(+"execute_input"),
               Frontend.Key,
               "execute_input",
               Parent  => Request.Header,
               Content => Input);

            Object.Execute
              (IO_Pub            => IO_Pub'Unchecked_Access,
               Execution_Counter => IO_Pub.Count,
               Code              => Input.Value (+"code").To_String,
               Silent            => Input.Value (+"silent").To_Boolean,
               User_Expressions => Input.Value (+"user_expressions").To_Object,
               Allow_Stdin       => Input.Value (+"allow_stdin").To_Boolean,
               Stop_On_Error     => Input.Value (+"stop_on_error").To_Boolean,
               Expression_Values => Values,
               Error             => Error);

            Reply.Insert
              (+"execution_count",
               League.JSON.Values.To_JSON_Value (Count));

            if Error.Name.Is_Empty then
               Reply.Insert (+"status", -"ok");
               Reply.Insert (+"user_expressions", Values.To_JSON_Value);
            else
               Reply.Insert (+"status", -"error");
               Reply.Insert
                 (+"ename", League.JSON.Values.To_JSON_Value (Error.Name));
               Reply.Insert
                 (+"evalue", League.JSON.Values.To_JSON_Value (Error.Value));
               --  FIXME: Copy traceback
            end if;

            Send_Message
              (Frontend.Shell,
               Request.From,
               Frontend.Key,
               "execute_reply",
               Parent  => Request.Header,
               Content => Reply);
         end;
      end if;

      declare
         Content : League.JSON.Objects.JSON_Object;
      begin
         Content.Insert (+"execution_state", -"idle");
         Send_Message
           (Frontend.IOPub,
            -Topic,
            Frontend.Key,
            "status",
            Parent  => Request.Header,
            Content => Content);
      end;
   end Process_Shell_Message;

   --------------------------
   -- Read_Connection_File --
   --------------------------

   procedure Read_Connection_File
     (Name   : League.Strings.Universal_String;
      Result : out League.JSON.Objects.JSON_Object)
   is
      Input : Ada.Wide_Wide_Text_IO.File_Type;
      Text  : League.Strings.Universal_String;
      Doc   : League.JSON.Documents.JSON_Document;
   begin
      Ada.Wide_Wide_Text_IO.Open
        (Input, Ada.Wide_Wide_Text_IO.In_File, Name.To_UTF_8_String);
      while not Ada.Wide_Wide_Text_IO.End_Of_File (Input) loop
         declare
            Line : constant Wide_Wide_String :=
              Ada.Wide_Wide_Text_IO.Get_Line (Input);
         begin
            Text.Append (Line);
            Text.Append (Ada.Characters.Wide_Wide_Latin_1.LF);
         end;
      end loop;
      Ada.Wide_Wide_Text_IO.Close (Input);
      Doc := League.JSON.Documents.From_JSON (Text);
      Result := Doc.To_JSON_Object;
   end Read_Connection_File;

   ------------------
   -- Read_Message --
   ------------------

   procedure Read_Message
     (Socket : ZMQ.Sockets.Socket;
      Key    : League.Strings.Universal_String;
      Result : out Message)
   is
      procedure Read_Object
        (Object : out League.JSON.Objects.JSON_Object;
         More   : out Boolean);

      Digest : GNAT.SHA256.Context :=
        GNAT.SHA256.HMAC_Initial_Context (Key.To_UTF_8_String);

      -----------------
      -- Read_Object --
      -----------------

      procedure Read_Object
        (Object : out League.JSON.Objects.JSON_Object;
         More   : out Boolean)
      is
         MSG : ZMQ.Messages.Message;
      begin
         MSG.Initialize (0);
         Socket.Recv (MSG);
         declare
            Text : constant String := MSG.GetData;
         begin
            More := Has_More (MSG);
            GNAT.SHA256.Update (Digest, Text);
            Object := League.JSON.Documents.From_JSON
              (League.Strings.From_UTF_8_String (Text)).To_JSON_Object;
         end;
      end Read_Object;

      More : Boolean;
   begin
      loop
         declare
            From : ZMQ.Messages.Message;
            Item : League.Stream_Element_Vectors.Stream_Element_Vector;
         begin
            From.Initialize (0);
            Socket.Recv (From);
            exit when From.GetData = "<IDS|MSG>";
            Item := League.Stream_Element_Vectors.To_Stream_Element_Vector
              (From.GetData);
            Result.From.Append (Item);
            pragma Assert (Has_More (From));
         end;
      end loop;

      Result.Signature := League.Strings.From_UTF_8_String (Socket.Recv);
      Read_Object (Result.Header, More);
      pragma Assert (More);
      Read_Object (Result.Parent, More);
      pragma Assert (More);
      Read_Object (Result.Metadata, More);
      pragma Assert (More);
      Read_Object (Result.Content, More);

      while More loop  --  Skip buffers if any
         declare
            Temp : ZMQ.Messages.Message;
         begin
            Temp.Initialize (0);
            Socket.Recv (Temp);
            More := Has_More (Temp);
         end;
      end loop;

   end Read_Message;

   -----------------
   -- Send_Status --
   -----------------

   procedure Send_Message
     (Socket  : in out ZMQ.Sockets.Socket;
      To      : Address_Lists.List;
      Key     : League.Strings.Universal_String;
      Kind    : Wide_Wide_String;
      Parent  : League.JSON.Objects.JSON_Object :=
        League.JSON.Objects.Empty_JSON_Object;
      Content : League.JSON.Objects.JSON_Object :=
        League.JSON.Objects.Empty_JSON_Object)
   is
      use type League.Strings.Universal_String;
      Object : League.JSON.Objects.JSON_Object;
      Digest : GNAT.SHA256.Context :=
        GNAT.SHA256.HMAC_Initial_Context (Key.To_UTF_8_String);
   begin
      Object.Insert
        (+"msg_id",
         League.JSON.Values.To_JSON_Value
           (Parent.Value (+"msg_id").To_String & Kind));

      Object.Insert (+"session", Parent.Value (+"session"));
      Object.Insert (+"username", Parent.Value (+"username"));
      if Parent.Contains (+"date") then
         Object.Insert (+"date", Parent.Value (+"date"));
      end if;
      Object.Insert (+"msg_type", -Kind);
      Object.Insert (+"version", -"5.3");

      GNAT.SHA256.Update
        (Digest,
         Object.To_JSON_Document.To_JSON.To_Stream_Element_Array);

      GNAT.SHA256.Update
        (Digest,
         Parent.To_JSON_Document.To_JSON.To_Stream_Element_Array);

      GNAT.SHA256.Update (Digest, "{}");

      GNAT.SHA256.Update
        (Digest,
         Content.To_JSON_Document.To_JSON.To_Stream_Element_Array);

      for X of To loop
         Socket.Send (X.To_Stream_Element_Array, 2);
      end loop;

      Socket.Send ("<IDS|MSG>", 2);
      Socket.Send (String'(GNAT.SHA256.Digest (Digest)), 2);
      Socket.Send
        (Object.To_JSON_Document.To_JSON.To_Stream_Element_Array,
         2);
      Socket.Send
        (Parent.To_JSON_Document.To_JSON.To_Stream_Element_Array,
         2);
      Socket.Send ("{}", 2);
      Socket.Send (Content.To_JSON_Document.To_JSON.To_Stream_Element_Array);
   end Send_Message;

   use type Interfaces.C.int;
   use type Interfaces.C.long;
   use type Interfaces.C.short;

   CF : League.JSON.Objects.JSON_Object;

   Frontend : aliased Frontend_Connection;
   Poll     : array (1 .. 4) of aliased ZMQ.Low_Level.zmq_pollitem_t;
begin
   Read_Connection_File (File, CF);

   Frontend.Key := CF.Value (+"key").To_String;

   Bind (Frontend.Ctx, Frontend.Shell, CF, "shell_port", ZMQ.Sockets.ROUTER);
   Bind (Frontend.Ctx, Frontend.Stdin, CF, "stdin_port", ZMQ.Sockets.ROUTER);
   Bind (Frontend.Ctx, Frontend.IOPub, CF, "iopub_port", ZMQ.Sockets.PUB);
   Bind (Frontend.Ctx, Frontend.Ping, CF, "hb_port", ZMQ.Sockets.ROUTER);
   Bind
     (Frontend.Ctx,
      Frontend.Control,
      CF,
      "control_port",
      ZMQ.Sockets.ROUTER);

   loop
      Poll :=
        (1 => (socket => Frontend.Shell.Get_Impl,
               fd     => 0,
               events => ZMQ.Low_Level.Defs.ZMQ_POLLIN,
               revents => 0),
         2 => (socket  => Frontend.Stdin.Get_Impl,
               fd      => 0,
               events  => ZMQ.Low_Level.Defs.ZMQ_POLLIN,
               revents => 0),
         3 => (socket  => Frontend.Ping.Get_Impl,
               fd      => 0,
               events  => ZMQ.Low_Level.Defs.ZMQ_POLLIN,
               revents => 0),
         4 => (socket => Frontend.Control.Get_Impl,
               fd     => 0,
               events => ZMQ.Low_Level.Defs.ZMQ_POLLIN,
               revents => 0));

      if ZMQ.Low_Level.zmq_poll
        (items_u   => Poll (1)'Access,
         nitems_u  => 4,
         timeout_u => -1) < 0
      then
         return;
      end if;

      if Poll (1).revents /= 0 then
         declare
            Msg : Message;
         begin
            Read_Message (Frontend.Shell, Frontend.Key, Msg);
            Process_Shell_Message (Frontend, Msg);
         end;
      end if;
   end loop;
end Jupyter.Start_Kernel;