messages.scm 7.72 KB
Newer Older
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
;;; Guix-kernel -- Guix kernel for Jupyter
;;; Copyright (C) 2018 Evgeny Panfilov <epanfilov@gmail.com>
;;; Copyright (C) 2018, 2019 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program 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 General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

(define-module (jupyter messages)
  #:use-module (simple-zmq)
  #:use-module (json)
  #:use-module (gcrypt hmac)
  #:use-module (gcrypt base16)
  #:use-module (rnrs bytevectors)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-19)
  #:use-module (ice-9 match)
  #:export (message
            make-message
            reply
            message?
            message-header
            message-parent-header
            message-metadata
            message-content
            message-buffers
            message-type
            message-sender
            message-parts
            parts->message

41
42
            header
            make-header
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
            header?
            header-id
            header-user
            header-session-id
            header-date
            header-type
            header-version
            header-sender))

;;; Commentary:
;;;
;;; This file implements Jupyter messaging as defined at
;;; <https://jupyter-client.readthedocs.io/en/stable/messaging.html>.
;;;
;;; Code:

;; Jupyter message header as defined at
;; <https://jupyter-client.readthedocs.io/en/stable/messaging.html#general-message-format>.
(define-record-type <header>
62
  (%header id user session date type version sender)
63
64
65
66
67
68
69
70
71
72
73
74
  header?
  (id           header-id)                         ;bytevector (UUID)
  (user         header-user)                       ;string
  (session      header-session)                    ;bytevector (UUID)
  (date         header-date)                       ;string
  (type         header-message-type)               ;string
  (version      header-version)                    ;string

  ;; This is the ZeroMQ identity of the sender and not part of the header
  ;; itself.
  (sender       header-sender))                    ;bytevector (UUID) | #f

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

(define %protocol-version "5.0")

(define (current-date-string)
  (date->string (time-utc->date (current-time time-utc))
                "~5.~N"))

(define* (header type user session
                 #:key
                 (id (make-id))
                 (date (current-date-string))
                 (version %protocol-version)
                 sender)
  "Return a new Jupyter message header."
  (%header id user session date type version sender))

(define make-header header)

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
;; Jupyter message.
(define-record-type <message>
  (%message header parent-header metadata content buffers)
  message?
  (header          message-header)                ;<header>
  (parent-header   message-parent-header)         ;<header> | #f
  (metadata        message-metadata)              ;hash table (?)
  (content         message-content)               ;bytevector
  (buffers         message-buffers))              ;bytevector

(define* (message header content
                  #:key parent-header metadata (buffers '()))
  "Return a new Jupyter message."
  (%message header parent-header metadata content buffers))

(define make-message message)

(define (make-id)
  (number->string (random (expt 2 128)) 16))

(define (get-signature key str)
  "Return a hexadecimal string containing the SHA256 HMAC of STR, a string,
with KEY, another string."
  (bytevector->base16-string
   (sign-data key (string->utf8 str)
              #:algorithm 'sha256)))

(define* (message-parts message key
                        #:key
                        (recipient (and=> (message-parent-header message)
                                          header-sender)))
  "Return the list of parts (bytevectors) of MESSAGE for RECIPIENT, a ZeroMQ
identity (a bytevector).

This is a low-level procedure for internal use."
  (let* ((header    (header->string (message-header message)))
         (parent    (match (message-parent-header message)
                      (#f "{}")
                      (header (header->string header))))
         (metadata  (or (message-metadata message) "{}"))
         (content   (message-content message))
         (payload   (string-append header parent metadata content))
         (signature (get-signature key payload)))
    (cons* recipient DELIM
           (map string->utf8
                (list signature
                      header parent
                      metadata content)))))

(define (reply message type content)
  "Return a Jupyter message that is a reply to MESSAGE."
  (let ((parent (message-header message)))
145
146
    (make-message (header type (header-user parent)
                          (header-session parent))
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
                  content
                  #:parent-header parent)))

(define (message-type message)
  "Return the type of MESSAGE as a string--e.g., \"kernel_info_request\"."
  (header-message-type (message-header message)))

(define (message-sender message)
  "Return the identity (a bytevector) of the sender of MESSAGE or #f."
  (header-sender (message-header message)))

(define* (string->header str #:optional sender)
  "Read the JSON dictionary in STR and return the corresponding <header>
record.  Return #f if STR is the empty dictionary."
  (let ((table (json-string->scm str)))
    (if (zero? (hash-count (const #t) table))
        #f
164
        (header (hash-ref table "msg_type")
165
166
                (hash-ref table "username")
                (hash-ref table "session")
167
168
169
170
                #:id (hash-ref table "msg_id")
                #:date (hash-ref table "date")
                #:version (hash-ref table "version")
                #:sender sender))))
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

(define (header->string header)
  "Return HEADER as a JSON string."
  (scm->json-string `(("msg_id" . ,(header-id header))
                      ("username" . ,(header-user header))
                      ("session" . ,(header-session header))
                      ,@(match (header-date header)
                          (#f   '())
                          (date `(("date" . ,date))))
                      ("msg_type" . ,(header-message-type header))
                      ("version" . ,(header-version header)))))

(define DELIM (string->utf8 "<IDS|MSG>"))

(define (parts->message parts)
  "Return a message record from PARTS, a list of bytevectors as returned by
'zmq-get-msg-parts-bytevector'.

This is a low-level procedure for internal use."

  (define (delimiter? bv)
    (bytevector=? DELIM bv))

  ;; Note: The "routing prefix", which comes before <IDS|MSG>, "can be zero
  ;; or more socket identities", quoth
  ;; <https://jupyter-client.readthedocs.io/en/stable/messaging.html#messages-on-the-shell-router-dealer-channel>.
  ;; Here we only remember the first one, which is the real sender identity;
  ;; subsequent identities can appear when the message has been relayed.
  (match parts
    ((routing ... (? delimiter?) signature
              (= utf8->string header)
              (= utf8->string parent-header)
              (= utf8->string metadata)
              (= utf8->string content))
     (message (string->header header
                              (match routing
                                (() #f)
                                ((sender _ ...) sender)))
              content
              #:parent-header (string->header parent-header)
              #:metadata metadata))))