/
messages.go
258 lines (226 loc) · 7.87 KB
/
messages.go
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
package jupyter
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
)
const (
currentProtocolVersion = "5.0"
messageTypeKernelInfoRequest = "kernel_info_request"
messageTypeKernelInfoReply = "kernel_info_reply"
messageTypeExecuteRequest = "execute_request"
messageTypeExecuteReply = "execute_reply"
messageTypeExecuteResult = "execute_result"
messageTypeShutdownRequest = "shutdown_request"
messageTypeShutdownReply = "shutdown_reply"
messageTypeStatus = "status"
messageTypeError = "error"
messageTypeIsCompleteRequest = "is_complete_request"
messageTypeIsCompleteReply = "is_complete_reply"
messageTypeCompleteRequest = "complete_request"
messageTypeCompleteReply = "complete_reply"
statusIdle kernelStatus = "idle"
statusBusy kernelStatus = "busy"
statusStarting kernelStatus = "starting"
)
type message struct {
Header messageHeader `json:"header"`
ParentHeader messageHeader `json:"parent_header"`
Metadata map[string]interface{} `json:"metadata"`
Content json.RawMessage `json:"content"`
}
type messageHeader struct {
Id string `json:"msg_id"`
Username string `json:"username"`
Session string `json:"session"`
Type string `json:"msg_type"`
Version string `json:"version,omitempty"`
}
type executeRequest struct {
// Source code to be executed by the kernel, one or more lines.
Code string `json:"code"`
// A boolean flag which, if True, signals the kernel to execute
// this code as quietly as possible.
// silent=True forces store_history to be False,
// and will *not*:
// - broadcast output on the IOPUB channel
// - have an execute_result
// The default is False.
Silent bool `json:"silent"`
// A boolean flag which, if True, signals the kernel to populate history
// The default is True if silent is False. If silent is True, store_history
// is forced to be False.
StoreHistory bool `json:"store_history"`
// A dict mapping names to expressions to be evaluated in the
// user's dict. The rich display-data representation of each will be
// evaluated after execution.
// See the display_data content for the structure of the representation data.
UserExpressions map[string]string `json:"user_expressions"`
// Some frontends do not support stdin requests.
// If raw_input is called from code executed from such a frontend,
// a StdinNotImplementedError will be raised.
AllowStdin bool `json:"allow_stdin"`
// A boolean flag, which, if True, does not abort the execution queue,
// if an exception is encountered.
// This allows the queued execution of multiple execute_requests, even
// if they generate exceptions.
StopOnError bool `json:"stop_on_error"`
}
type executeReply struct {
Status string `json:"status"`
ExecutionCount int `json:"execution_count"`
UserExpressions map[string]interface{} `json:"user_expressions,omitempty"`
ErrorName string `json:"ename,omitempty"`
ErrorValue string `json:"evalue,omitempty"`
Traceback []string `json:"traceback,omitempty"`
}
type executeResult struct {
ExecutionCount int `json:"execution_count"`
Source string `json:"source"`
Data map[string]interface{} `json:"data"`
Metadata map[string]interface{} `json:"metadata"`
}
type executeError struct {
ExecutionCount int `json:"execution_count"`
ErrorName string `json:"ename"`
ErrorValue string `json:"evalue"`
Traceback []string `json:"traceback"`
}
type kernelStatus string
func (s kernelStatus) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
ExecutionState string `json:"execution_state"`
}{string(s)})
}
type isCompleteRequest struct {
Code string `json:"code"`
}
type isCompleteReply struct {
Status string `json:"status"`
Indent string `json:"indent,omitempty"`
}
type completeRequest struct {
Code string `json:"code"`
CursorPos int `json:"cursor_pos"`
}
type completeReply struct {
Matches []string `json:"matches"`
CursorStart int `json:"cursor_start"`
CursorEnd int `json:"cursor_end"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Status string `json:"status"`
ErrorName string `json:"ename,omitempty"`
ErrorValue string `json:"evalue,omitempty"`
Traceback []string `json:"traceback,omitempty"`
}
// deserializeMessage parses a multipart 0MQ message received from a socket
// into a message struct and a slice of identities. parseMessage will verify
// the message signature with the provided key.
//
// See: http://jupyter-client.readthedocs.org/en/latest/messaging.html
func deserializeMessage(parts []string, key []byte) (_ *message, identities []string, _ error) {
for {
if len(parts) == 0 {
return nil, nil, errors.New("message delimiter not found")
}
if parts[0] == "<IDS|MSG>" {
parts = parts[1:]
break
}
identities = append(identities, parts[0])
parts = parts[1:]
}
if len(parts) < 5 {
return nil, nil, errors.New("not enough parts to message")
}
if parts[0] != "" {
mac := hmac.New(sha256.New, key)
for _, part := range parts[1:5] {
mac.Write([]byte(part))
}
signature, err := hex.DecodeString(parts[0])
if err != nil {
return nil, nil, fmt.Errorf("signature decoding failed: %v", err)
}
if !hmac.Equal(mac.Sum(nil), signature) {
return nil, nil, errors.New("signature validation failed")
}
}
var msg message
if err := json.Unmarshal([]byte(parts[1]), &msg.Header); err != nil {
return nil, nil, fmt.Errorf("unmarshalling message header: %v", err)
}
if err := json.Unmarshal([]byte(parts[2]), &msg.ParentHeader); err != nil {
return nil, nil, fmt.Errorf("unmarshalling message parent header: %v", err)
}
if err := json.Unmarshal([]byte(parts[3]), &msg.Metadata); err != nil {
return nil, nil, fmt.Errorf("unmarshalling message metadata: %v", err)
}
msg.Content = []byte(parts[4])
// TODO(axw) verify that content is in serialized-dict format, but
// leave its deseralisation to individual message type handlers.
return &msg, identities, nil
}
// newMessage creates a new message with the given type and parent message.
func newMessage(messageType string, parentMessageHeader *messageHeader) (*message, error) {
messageId, err := newUUID()
if err != nil {
return nil, fmt.Errorf("allocating message ID: %v", err)
}
msg := &message{
Header: messageHeader{
Id: messageId,
Type: messageType,
Version: currentProtocolVersion,
},
Content: json.RawMessage([]byte("{}")),
}
if parentMessageHeader != nil {
msg.ParentHeader = *parentMessageHeader
msg.Header.Username = parentMessageHeader.Username
msg.Header.Session = parentMessageHeader.Session
}
return msg, nil
}
// serializeMessage converts a message to the Jupyter wire format, signed with
// the given key, ready to be transmitted via 0MQ.
//
// See: http://jupyter-client.readthedocs.org/en/latest/messaging.html
func serializeMessage(msg *message, identities []string, key []byte) ([]string, error) {
result := make([]string, len(identities), len(identities)+6)
copy(result, identities)
result = append(result, "<IDS|MSG>")
header, err := json.Marshal(msg.Header)
if err != nil {
return nil, fmt.Errorf("marshalling message header")
}
parentHeader, err := json.Marshal(msg.ParentHeader)
if err != nil {
return nil, fmt.Errorf("marshalling message parent header")
}
metadata, err := json.Marshal(msg.Metadata)
if err != nil {
return nil, fmt.Errorf("marshalling message metadata")
}
var hmacSignature string
if len(key) != 0 {
mac := hmac.New(sha256.New, key)
mac.Write(header)
mac.Write(parentHeader)
mac.Write(metadata)
mac.Write(msg.Content)
hmacSignature = hex.EncodeToString(mac.Sum(nil))
}
result = append(
result,
hmacSignature,
string(header),
string(parentHeader),
string(metadata),
string(msg.Content),
)
return result, nil
}