-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Dynamic.jl
563 lines (459 loc) Β· 24.2 KB
/
Dynamic.jl
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
import UUIDs: uuid1
import .PkgCompat
import .Status
"Will hold all 'response handlers': functions that respond to a WebSocket request from the client."
const responses = Dict{Symbol,Function}()
Base.@kwdef struct ClientRequest
session::ServerSession
notebook::Union{Nothing,Notebook}
body::Any=nothing
initiator::Union{Initiator,Nothing}=nothing
end
require_notebook(r::ClientRequest) = if r.notebook === nothing
throw(ArgumentError("Notebook request called without a notebook π"))
end
###
# RESPONDING TO A NOTEBOOK STATE UPDATE
###
"""
## State management in Pluto
*Aka: how do the server and clients stay in sync?*
A Pluto notebook session has *state*: with this, we mean:
1. The input and ouput of each cell, the cell order, and more metadata about the notebook and cells [^state]
This state needs to be **synchronised between the server and all clients** (we support multiple synchronised clients), and note that:
- Either side wants to update the state. Generally, a client will update cell inputs, the server will update cell outputs.
- Both sides want to *react* to state updates
- The server is in Julia, the clients are in JS
- This is built on top of our websocket+msgpack connection, but that doesn't matter too much
We do this by implementing something similar to how you use Google Firebase: there is **one shared state object, any party can mutate it, and it will synchronise to all others automatically**. The state object is a nested structure of mutable `Dict`s, with immutable ints, strings, bools, arrays, etc at the endpoints.
Some cool things are:
- Our system uses object diffing, so only *changes to the state* are actually tranferred over the network. But you can use it as if the entire state is sent around constantly.
- In the frontend, the *shared state* is part of the *react state*, i.e. shared state updates automatically trigger visual updates.
- Within the client, state changes take effect instantly, without waiting for a round trip to the server. This means that when you add a cell, it shows up instantly.
Diffing is done using `immer.js` (frontend) and `src/webserver/Firebasey.jl` (server). We wrote Firebasey ourselves to match immer's functionality, and the cool thing is: **it is a Pluto notebook**! Since Pluto notebooks are `.jl` files, we can just `include` it in our module.
The shared state object is generated by [`notebook_to_js`](@ref). Take a look! The Julia server orchestrates this firebasey stuff. For this, we keep a **copy** of the latest state of each client on the server (see [`current_state_for_clients`](@ref)). When anything changes to the Julia state (e.g. when a cell finished running), we call [`send_notebook_changes!`](@ref), which will call [`notebook_to_js`](@ref) to compute the new desired state object. For each client, we diff the new state to their last known state, and send them the difference.
### Responding to changes made by a client
When a client updates the shared state object, we want the server to *react* to that change by taking an action. Which action to take depends on which field changes. For example, when `state["path"]` changes, we should rename the notebook file. When `state["cell_inputs"][a_cell_id]["code"]` changes, we should reparse and analyze that cel, etc. This location of the change, e.g. `"cell_inputs/<a_cell_id>/code"` is called the *path* of the change.
[`effects_of_changed_state`](@ref) define these pattern-matchers. We use a `Wildcard()` to take the place of *any* key, see [`Wildcard`](@ref), and we use the change/update/patch inside the given function.
### Not everything uses the shared state (yet)
Besides `:update_notebook`, you will find more functions in [`responses`](@ref) that respond to classic 'client requests', such as `:reshow_cell` and `:shutdown_notebook`. Some of these requests get a direct response, like the list of autocomplete options to a `:complete` request (in `src/webserver/REPLTools.jl`). On the javascript side, these direct responses can be `awaited`, because every message has a unique ID.
[^state]:
Two other meanings of _state_ could be:
2. The reactivity data: the parsed AST (`Expr`) of each cell, which variables are defined or referenced by which cells, in what order will cells run?
3. The state of the Julia process: i.e. which variables are defined, which packages are imported, etc.
The first two (1 & 2) are stored in a [`Notebook`](@ref) struct, remembered by the server process (Julia). (In fact, (2) is entirely described by (1), but we store it for performance reasons.) I included (3) for completeness, but it is not stored by us, we hope to control and minimize (3) by keeping track of (1) and (2).
"""
module Firebasey include("./Firebasey.jl") end
module FirebaseyUtils
# I put Firebasey here manually THANKS JULIA
import ..Firebasey
include("./FirebaseyUtils.jl")
end
# All of the arrays in the notebook_to_js object are 'immutable' (we write code as if they are), so we can enable this optimization:
Firebasey.use_triple_equals_for_arrays[] = true
# the only possible Arrays are:
# - cell_order
# - cell_execution_order
# - cell_result > * > output > body
# - bonds > * > value > *
# - cell_dependencies > * > downstream_cells_map > * >
# - cell_dependencies > * > upstream_cells_map > * >
function notebook_to_js(notebook::Notebook)
Dict{String,Any}(
"pluto_version" => PLUTO_VERSION_STR,
"notebook_id" => notebook.notebook_id,
"path" => notebook.path,
"shortpath" => basename(notebook.path),
"in_temp_dir" => startswith(notebook.path, new_notebooks_directory()),
"process_status" => notebook.process_status,
"last_save_time" => notebook.last_save_time,
"last_hot_reload_time" => notebook.last_hot_reload_time,
"cell_inputs" => Dict{UUID,Dict{String,Any}}(
id => Dict{String,Any}(
"cell_id" => cell.cell_id,
"code" => cell.code,
"code_folded" => cell.code_folded,
"metadata" => cell.metadata,
)
for (id, cell) in notebook.cells_dict),
"cell_results" => Dict{UUID,Dict{String,Any}}(
id => Dict{String,Any}(
"cell_id" => cell.cell_id,
"depends_on_disabled_cells" => cell.depends_on_disabled_cells,
"output" => FirebaseyUtils.ImmutableMarker(cell.output),
"published_object_keys" => collect(keys(cell.published_objects)),
"queued" => cell.queued,
"running" => cell.running,
"errored" => cell.errored,
"runtime" => cell.runtime,
"logs" => FirebaseyUtils.AppendonlyMarker(cell.logs),
"depends_on_skipped_cells" => cell.depends_on_skipped_cells,
)
for (id, cell) in notebook.cells_dict),
"cell_order" => notebook.cell_order,
"published_objects" => merge!(Dict{String,Any}(), (c.published_objects for c in values(notebook.cells_dict))...),
"bonds" => Dict{String,Dict{String,Any}}(
String(key) => Dict{String,Any}(
"value" => bondvalue.value,
)
for (key, bondvalue) in notebook.bonds),
"metadata" => notebook.metadata,
"nbpkg" => let
ctx = notebook.nbpkg_ctx
Dict{String,Any}(
"enabled" => ctx !== nothing,
"waiting_for_permission" => notebook.process_status === ProcessStatus.waiting_for_permission,
"waiting_for_permission_but_probably_disabled" => notebook.process_status === ProcessStatus.waiting_for_permission && !use_plutopkg(notebook.topology),
"restart_recommended_msg" => notebook.nbpkg_restart_recommended_msg,
"restart_required_msg" => notebook.nbpkg_restart_required_msg,
"installed_versions" => ctx === nothing ? Dict{String,String}() : notebook.nbpkg_installed_versions_cache,
"terminal_outputs" => notebook.nbpkg_terminal_outputs,
"install_time_ns" => notebook.nbpkg_install_time_ns,
"busy_packages" => notebook.nbpkg_busy_packages,
"instantiated" => notebook.nbpkg_ctx_instantiated,
)
end,
"status_tree" => Status.tojs(notebook.status_tree),
"cell_dependencies" => notebook._cached_cell_dependencies,
"cell_execution_order" => cell_id.(collect(notebook._cached_topological_order)),
)
end
"""
For each connected client, we keep a copy of their current state. This way we know exactly which updates to send when the server-side state changes.
"""
const current_state_for_clients = WeakKeyDict{ClientSession,Any}()
const current_state_for_clients_lock = ReentrantLock()
"""
Update the local state of all clients connected to this notebook.
"""
function send_notebook_changes!(π::ClientRequest; commentary::Any=nothing, skip_send::Bool=false)
outbox = Set{Tuple{ClientSession,UpdateMessage}}()
lock(current_state_for_clients_lock) do
notebook_dict = notebook_to_js(π.notebook)
for (_, client) in π.session.connected_clients
if client.connected_notebook !== nothing && client.connected_notebook.notebook_id == π.notebook.notebook_id
current_dict = get(current_state_for_clients, client, :empty)
patches = Firebasey.diff(current_dict, notebook_dict)
patches_as_dicts = Firebasey._convert(Vector{Dict}, patches)
current_state_for_clients[client] = deep_enough_copy(notebook_dict)
# Make sure we do send a confirmation to the client who made the request, even without changes
is_response = π.initiator !== nothing && client == π.initiator.client
if !skip_send && (!isempty(patches) || is_response)
response = Dict(
:patches => patches_as_dicts,
:response => is_response ? commentary : nothing
)
push!(outbox, (client, UpdateMessage(:notebook_diff, response, π.notebook, nothing, π.initiator)))
end
end
end
end
for (client, msg) in outbox
putclientupdates!(client, msg)
end
try_event_call(π.session, FileEditEvent(π.notebook))
end
"Like `deepcopy`, but anything other than `Dict` gets a shallow (reference) copy."
@generated function deep_enough_copy(d::Dict)
quote
out = $d()
for (k,v) in d
out[k] = deep_enough_copy(v)
end
out
end
end
deep_enough_copy(d) = d
"""
A placeholder path. The path elements that it replaced will be given to the function as arguments.
"""
struct Wildcard end
abstract type Changed end
struct CodeChanged <: Changed end
struct FileChanged <: Changed end
struct BondChanged <: Changed
bond_name::Symbol
is_first_value::Bool
end
# to support push!(x, y...) # with y = []
Base.push!(x::Set{Changed}) = x
const no_changes = Changed[]
const effects_of_changed_state = Dict(
"path" => function(; request::ClientRequest, patch::Firebasey.ReplacePatch)
SessionActions.move(request.session, request.notebook, patch.value)
return no_changes
end,
"process_status" => function(; request::ClientRequest, patch::Firebasey.ReplacePatch)
newstatus = patch.value
@info "Process status set by client" newstatus
end,
# "execution_allowed" => function(; request::ClientRequest, patch::Firebasey.ReplacePatch)
# Firebasey.applypatch!(request.notebook, patch)
# newstatus = patch.value
# @info "execution_allowed set by client" newstatus
# if newstatus
# @info "lets run some cells!"
# update_save_run!(request.session, request.notebook, notebook.cells;
# run_async=true, save=true
# )
# end
# end,
"in_temp_dir" => function(; _...) no_changes end,
"cell_inputs" => Dict(
Wildcard() => function(cell_id, rest...; request::ClientRequest, patch::Firebasey.JSONPatch)
Firebasey.applypatch!(request.notebook, patch)
if length(rest) == 0
[CodeChanged(), FileChanged()]
elseif length(rest) == 1 && Symbol(rest[1]) == :code
[CodeChanged(), FileChanged()]
else
[FileChanged()]
end
end,
),
"cell_order" => function(; request::ClientRequest, patch::Firebasey.ReplacePatch)
Firebasey.applypatch!(request.notebook, patch)
[FileChanged()]
end,
"bonds" => Dict(
Wildcard() => function(name; request::ClientRequest, patch::Firebasey.JSONPatch)
name = Symbol(name)
Firebasey.applypatch!(request.notebook, patch)
[BondChanged(name, patch isa Firebasey.AddPatch)]
end,
),
"metadata" => Dict(
Wildcard() => function(property; request::ClientRequest, patch::Firebasey.JSONPatch)
Firebasey.applypatch!(request.notebook, patch)
[FileChanged()]
end
)
)
responses[:update_notebook] = function response_update_notebook(π::ClientRequest)
require_notebook(π)
try
notebook = π.notebook
patches = (Base.convert(Firebasey.JSONPatch, update) for update in π.body["updates"])
if length(patches) == 0
send_notebook_changes!(π)
return nothing
end
if !haskey(current_state_for_clients, π.initiator.client)
throw(ErrorException("Updating without having a first version of the notebook??"))
end
# TODO Immutable ??
for patch in patches
Firebasey.applypatch!(current_state_for_clients[π.initiator.client], patch)
end
changes = Set{Changed}()
for patch in patches
(mutator, matches, rest) = trigger_resolver(effects_of_changed_state, patch.path)
current_changes = if isempty(rest) && applicable(mutator, matches...)
mutator(matches...; request=π, patch)
else
mutator(matches..., rest...; request=π, patch)
end
union!(changes, current_changes)
end
# We put a flag to check whether any patch changes the skip_as_script metadata. This is to eventually trigger a notebook updated if no reactive_run is part of this update
skip_as_script_changed = any(patches) do patch
path = patch.path
metadata_idx = findfirst(isequal("metadata"), path)
if metadata_idx === nothing
false
else
isequal(path[metadata_idx+1], "skip_as_script")
end
end
# If CodeChanged β changes, then the client will also send a request like run_multiple_cells, which will trigger a file save _before_ running the cells.
# In the future, we should get rid of that request, and save the file here. For now, we don't save the file here, to prevent unnecessary file IO.
# (You can put a log in save_notebook to track how often the file is saved)
if FileChanged() β changes && CodeChanged() β changes
if skip_as_script_changed
# If skip_as_script has changed but no cell run is happening we want to update the notebook dependency here before saving the file
update_skipped_cells_dependency!(notebook)
end
save_notebook(π.session, notebook)
end
let bond_changes = filter(x -> x isa BondChanged, changes)
bound_sym_names = Symbol[x.bond_name for x in bond_changes]
is_first_values = Bool[x.is_first_value for x in bond_changes]
set_bond_values_reactive(;
session=π.session,
notebook=π.notebook,
bound_sym_names=bound_sym_names,
is_first_values=is_first_values,
run_async=true,
initiator=π.initiator,
)
end
send_notebook_changes!(π; commentary=Dict(:update_went_well => :π))
catch ex
@error "Update notebook failed" π.body["updates"] exception=(ex, stacktrace(catch_backtrace()))
response = Dict(
:update_went_well => :π,
:why_not => sprint(showerror, ex),
:should_i_tell_the_user => ex isa SessionActions.UserError,
)
send_notebook_changes!(π; commentary=response)
end
end
function trigger_resolver(anything, path, values=[])
(value=anything, matches=values, rest=path)
end
function trigger_resolver(resolvers::Dict, path, values=[])
if isempty(path)
throw(BoundsError("resolver path ends at Dict with keys $(keys(resolvers))"))
end
segment, rest... = path
if haskey(resolvers, segment)
trigger_resolver(resolvers[segment], rest, values)
elseif haskey(resolvers, Wildcard())
trigger_resolver(resolvers[Wildcard()], rest, (values..., segment))
else
throw(BoundsError("failed to match path $(path), possible keys $(keys(resolvers))"))
end
end
###
# MISC RESPONSES
###
responses[:current_time] = function response_current_time(π::ClientRequest)
putclientupdates!(π.session, π.initiator, UpdateMessage(:current_time, Dict(:time => time()), nothing, nothing, π.initiator))
end
responses[:connect] = function response_connect(π::ClientRequest)
putclientupdates!(π.session, π.initiator, UpdateMessage(:π, Dict(
:notebook_exists => (π.notebook !== nothing),
:options => π.session.options,
:version_info => Dict(
:pluto => PLUTO_VERSION_STR,
:julia => JULIA_VERSION_STR,
:dismiss_update_notification => π.session.options.server.dismiss_update_notification,
),
), nothing, nothing, π.initiator))
end
responses[:ping] = function response_ping(π::ClientRequest)
putclientupdates!(π.session, π.initiator, UpdateMessage(:pong, Dict(), nothing, nothing, π.initiator))
end
responses[:reset_shared_state] = function response_reset_shared_state(π::ClientRequest)
delete!(current_state_for_clients, π.initiator.client)
if π.notebook !== nothing
send_notebook_changes!(π; commentary=Dict(:from_reset => true))
end
end
responses[:run_multiple_cells] = function response_run_multiple_cells(π::ClientRequest)
require_notebook(π)
uuids = UUID.(π.body["cells"])
cells = map(uuids) do uuid
π.notebook.cells_dict[uuid]
end
if will_run_code(π.notebook)
foreach(c -> c.queued = true, cells)
# run send_notebook_changes! without actually sending it, to update current_state_for_clients for our client with c.queued = true.
# later, during update_save_run!, the cell will actually run, eventually setting c.queued = false again, which will be sent to the client through a patch update.
# We *need* to send *something* to the client, because of https://github.com/fonsp/Pluto.jl/pull/1892, but we also don't want to send unnecessary updates. We can skip sending this update, because update_save_run! will trigger a send_notebook_changes! very very soon.
send_notebook_changes!(π; skip_send=true)
end
function on_auto_solve_multiple_defs(disabled_cells_dict)
response = Dict{Symbol,Any}(
:disabled_cells => Dict{UUID,Any}(cell_id(k) => v for (k,v) in disabled_cells_dict),
)
putclientupdates!(π.session, π.initiator, UpdateMessage(:run_feedback, response, π.notebook, nothing, π.initiator))
end
wfp = π.notebook.process_status == ProcessStatus.waiting_for_permission
update_save_run!(π.session, π.notebook, cells;
run_async=true, save=true,
auto_solve_multiple_defs=true, on_auto_solve_multiple_defs,
# special case: just render md cells in "Safe preview" mode
prerender_text=wfp,
clear_not_prerenderable_cells=wfp,
)
end
responses[:get_all_notebooks] = function response_get_all_notebooks(π::ClientRequest)
putplutoupdates!(π.session, clientupdate_notebook_list(π.session.notebooks, initiator=π.initiator))
end
responses[:interrupt_all] = function response_interrupt_all(π::ClientRequest)
require_notebook(π)
session_notebook = (π.session, π.notebook)
workspace = WorkspaceManager.get_workspace(session_notebook; allow_creation=false)
already_interrupting = π.notebook.wants_to_interrupt
anything_running = !isready(workspace.dowork_token)
if !already_interrupting && anything_running
π.notebook.wants_to_interrupt = true
WorkspaceManager.interrupt_workspace(session_notebook)
end
# TODO: notify user whether interrupt was successful
end
responses[:shutdown_notebook] = function response_shutdown_notebook(π::ClientRequest)
require_notebook(π)
SessionActions.shutdown(π.session, π.notebook; keep_in_session=π.body["keep_in_session"])
end
without_initiator(π::ClientRequest) = ClientRequest(session=π.session, notebook=π.notebook)
responses[:restart_process] = function response_restart_process(π::ClientRequest; run_async::Bool=true)
require_notebook(π)
if π.notebook.process_status != ProcessStatus.waiting_to_restart
π.notebook.process_status = ProcessStatus.waiting_to_restart
π.session.options.evaluation.run_notebook_on_load && _report_business_cells_planned!(π.notebook)
send_notebook_changes!(π |> without_initiator)
# TODO skip necessary?
SessionActions.shutdown(π.session, π.notebook; keep_in_session=true, async=true)
π.notebook.process_status = ProcessStatus.starting
send_notebook_changes!(π |> without_initiator)
update_save_run!(π.session, π.notebook, π.notebook.cells; run_async=run_async, save=true)
end
end
responses[:reshow_cell] = function response_reshow_cell(π::ClientRequest)
require_notebook(π)
@assert will_run_code(π.notebook)
cell = let
cell_id = UUID(π.body["cell_id"])
π.notebook.cells_dict[cell_id]
end
run = WorkspaceManager.format_fetch_in_workspace(
(π.session, π.notebook),
cell.cell_id,
ends_with_semicolon(cell.code),
collect(keys(cell.published_objects)),
(parse(PlutoRunner.ObjectID, π.body["objectid"], base=16), convert(Int64, π.body["dim"])),
)
set_output!(cell, run, ExprAnalysisCache(π.notebook.topology.codes[cell]); persist_js_state=true)
# send to all clients, why not
send_notebook_changes!(π |> without_initiator)
end
responses[:request_js_link_response] = function response_request_js_link_response(π::ClientRequest)
require_notebook(π)
@assert will_run_code(π.notebook)
Threads.@spawn try
result = WorkspaceManager.eval_fetch_in_workspace(
(π.session, π.notebook),
quote
PlutoRunner.evaluate_js_link(
$(π.notebook.notebook_id),
$(UUID(π.body["cell_id"])),
$(π.body["link_id"]),
$(π.body["input"]),
)
end
)
putclientupdates!(π.session, π.initiator, UpdateMessage(:π€, result, nothing, nothing, π.initiator))
catch ex
@error "Error in request_js_link_response" exception=(ex, stacktrace(catch_backtrace()))
end
end
responses[:nbpkg_available_versions] = function response_nbpkg_available_versions(π::ClientRequest)
# require_notebook(π)
all_versions = PkgCompat.package_versions(π.body["package_name"])
putclientupdates!(π.session, π.initiator, UpdateMessage(:π, Dict(
:versions => string.(all_versions),
), nothing, nothing, π.initiator))
end
responses[:package_completions] = function response_package_completions(π::ClientRequest)
results = PkgCompat.package_completions(π.body["query"])
putclientupdates!(π.session, π.initiator, UpdateMessage(:π³, Dict(
:results => results,
), nothing, nothing, π.initiator))
end
responses[:pkg_update] = function response_pkg_update(π::ClientRequest)
require_notebook(π)
update_nbpkg(π.session, π.notebook)
putclientupdates!(π.session, π.initiator, UpdateMessage(:π¦, Dict(), nothing, nothing, π.initiator))
end