lattice-grid 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +179 -0
  4. data/lib/lattice/grid/aggregate_sql.rb +98 -0
  5. data/lib/lattice/grid/cells.rb +85 -0
  6. data/lib/lattice/grid/collab/axis.rb +40 -0
  7. data/lib/lattice/grid/collab/channel.rb +31 -0
  8. data/lib/lattice/grid/collab/channel_handler.rb +84 -0
  9. data/lib/lattice/grid/collab/connection.rb +72 -0
  10. data/lib/lattice/grid/collab/doc_model.rb +99 -0
  11. data/lib/lattice/grid/collab/doc_model_apply.rb +105 -0
  12. data/lib/lattice/grid/collab/doc_model_doc.rb +95 -0
  13. data/lib/lattice/grid/collab/doc_model_normalize.rb +120 -0
  14. data/lib/lattice/grid/collab/doc_server.rb +84 -0
  15. data/lib/lattice/grid/collab/doc_server_messages.rb +129 -0
  16. data/lib/lattice/grid/collab/iron_calc.rb +84 -0
  17. data/lib/lattice/grid/collab/iron_calc_ops.rb +118 -0
  18. data/lib/lattice/grid/collab/iron_calc_sheets.rb +69 -0
  19. data/lib/lattice/grid/collab/memory_store.rb +63 -0
  20. data/lib/lattice/grid/collab/refs.rb +131 -0
  21. data/lib/lattice/grid/collab/refs_shrink.rb +56 -0
  22. data/lib/lattice/grid/collab/wasm_book.rb +97 -0
  23. data/lib/lattice/grid/collab/wire.rb +135 -0
  24. data/lib/lattice/grid/collab/wire_model_ops.rb +33 -0
  25. data/lib/lattice/grid/collab/wire_ops.rb +120 -0
  26. data/lib/lattice/grid/collab/wire_style.rb +60 -0
  27. data/lib/lattice/grid/collab.rb +44 -0
  28. data/lib/lattice/grid/context.rb +82 -0
  29. data/lib/lattice/grid/dates.rb +76 -0
  30. data/lib/lattice/grid/filter_sql.rb +87 -0
  31. data/lib/lattice/grid/json.rb +60 -0
  32. data/lib/lattice/grid/keyset.rb +49 -0
  33. data/lib/lattice/grid/kind.rb +58 -0
  34. data/lib/lattice/grid/levels.rb +121 -0
  35. data/lib/lattice/grid/limits.rb +51 -0
  36. data/lib/lattice/grid/pager.rb +118 -0
  37. data/lib/lattice/grid/parser/filter_rules.rb +119 -0
  38. data/lib/lattice/grid/parser/group_rules.rb +105 -0
  39. data/lib/lattice/grid/parser/request_rules.rb +131 -0
  40. data/lib/lattice/grid/parser/tree_rules.rb +68 -0
  41. data/lib/lattice/grid/parser.rb +126 -0
  42. data/lib/lattice/grid/pivot_sql.rb +78 -0
  43. data/lib/lattice/grid/query.rb +76 -0
  44. data/lib/lattice/grid/request.rb +19 -0
  45. data/lib/lattice/grid/respond.rb +60 -0
  46. data/lib/lattice/grid/sql.rb +103 -0
  47. data/lib/lattice/grid/tree_sql.rb +59 -0
  48. data/lib/lattice/grid/values.rb +124 -0
  49. data/lib/lattice/grid/version.rb +7 -0
  50. data/lib/lattice/grid.rb +29 -0
  51. data/wasm/ironcalc_wasi.wasm +0 -0
  52. metadata +110 -0
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The server copy of the sheet model: a port of `DocModel` in
7
+ # packages/server/src/collab/model.ts. It applies the `SheetOp` rules of `Workbook` and keeps
8
+ # tombstones, so a late op can find where a deleted row was. A cell is a Hash with the keys
9
+ # "value", "formula", "computed", "format", "style" and "note"; a key that is not there is the
10
+ # TypeScript `undefined`, and nil is the JSON null.
11
+ class DocModel
12
+ # The TypeScript `undefined` in a change to a cell: the key goes away.
13
+ UNSET = Object.new.freeze
14
+
15
+ # One sheet of the model.
16
+ Sheet = Struct.new(:id, :name, :rows, :cols, :cells, :merges, :frozen)
17
+
18
+ NO_PANES = { "rows" => 0, "cols" => 0 }.freeze
19
+
20
+ attr_reader :sheets, :names
21
+
22
+ def initialize(doc, axes = {})
23
+ @sheets = []
24
+ @names = {}
25
+ @removed_sheets = Set.new
26
+ styles = doc["styles"] || {}
27
+ doc["sheets"].each { |s| @sheets << load_sheet(s, axes[s["id"]], styles) }
28
+ (doc["names"] || []).each { |n| @names[n["name"]] = n["ref"] }
29
+ end
30
+
31
+ def sheet(id) = @sheets.find { |s| s.id == id }
32
+
33
+ def cell(sheet_id, row, col)
34
+ sheet(sheet_id)&.cells&.dig(row, col)
35
+ end
36
+
37
+ # Sets the computed values that the engine gives. A change for an empty cell is skipped.
38
+ def take(changes)
39
+ changes.each do |c|
40
+ s = sheet(c["sheet"])
41
+ current = s&.cells&.dig(c["row"], c["col"])
42
+ put(s, c["row"], c["col"], current.merge("computed" => c["value"])) if current
43
+ end
44
+ end
45
+
46
+ def axes
47
+ @sheets.to_h { |s| [s.id, { "rows" => s.rows.all.dup, "cols" => s.cols.all.dup }] }
48
+ end
49
+
50
+ private
51
+
52
+ def load_sheet(data, axes, styles)
53
+ sheet = Sheet.new(data["id"], data["name"], axis(data, axes, "rows"), axis(data, axes, "cols"), {},
54
+ deep(data["merges"] || []), NO_PANES.merge(data["frozen"] || {}))
55
+ data["cells"].each { |c| load_cell(sheet, c, styles) }
56
+ sheet
57
+ end
58
+
59
+ def axis(data, axes, key) = Axis.new(data[key], axes&.dig(key))
60
+
61
+ def load_cell(sheet, data, styles)
62
+ cell = data.except("row", "col", "style")
63
+ # As `Workbook.load`: a plain value is its own computed value.
64
+ cell["computed"] = cell["value"] if !cell["formula"] && !cell.key?("computed") && cell.key?("value")
65
+ style = data.key?("style") && styles[data["style"]]
66
+ cell["style"] = style if style
67
+ put(sheet, data["row"], data["col"], cell)
68
+ end
69
+
70
+ def deep(value) = Marshal.load(Marshal.dump(value))
71
+
72
+ def put(sheet, row, col, cell)
73
+ if cell.empty?
74
+ sheet.cells[row]&.delete(col)
75
+ return
76
+ end
77
+ (sheet.cells[row] ||= {})[col] = cell
78
+ end
79
+
80
+ def update(sheet, row, col, change)
81
+ cell = (sheet.cells.dig(row, col) || {}).dup
82
+ change.each { |k, v| v.equal?(UNSET) ? cell.delete(k) : cell[k] = v }
83
+ put(sheet, row, col, cell)
84
+ end
85
+
86
+ def ctx(full)
87
+ Refs.context(@sheets.map do |s|
88
+ { "id" => s.id, "name" => s.name, "rows" => full ? s.rows.all : s.rows.live,
89
+ "cols" => full ? s.cols.all : s.cols.live }
90
+ end)
91
+ end
92
+
93
+ def name_used?(name, except = nil)
94
+ @sheets.any? { |s| s.id != except && s.name.downcase == name.downcase }
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # `DocModel#apply`: applies a normalized op with the same rules as `Workbook.apply`.
7
+ class DocModel
8
+ APPLY = {
9
+ "setCell" => :apply_set_cell, "insertRows" => :apply_insert, "insertCols" => :apply_insert,
10
+ "deleteRows" => :apply_delete, "deleteCols" => :apply_delete, "setFormat" => :apply_format,
11
+ "setStyle" => :apply_format, "merge" => :apply_merge, "unmerge" => :apply_unmerge,
12
+ "setName" => :apply_name, "addSheet" => :apply_add_sheet, "removeSheet" => :apply_remove_sheet,
13
+ "renameSheet" => :apply_rename_sheet, "setNote" => :apply_note, "freeze" => :apply_freeze
14
+ }.freeze
15
+
16
+ # Give one `read` Hash to all the ops of a batch. It keeps the computed value of each cell
17
+ # before the batch (the last value that the engine read). A formula keeps that value until
18
+ # the engine reports a change.
19
+ def apply(operation, read = {})
20
+ send(APPLY.fetch(operation["type"]), operation, read)
21
+ end
22
+
23
+ private
24
+
25
+ def apply_set_cell(operation, read)
26
+ s = sheet(operation["sheet"])
27
+ at = operation.values_at("sheet", "row", "col")
28
+ read[at] = computed_of(s, operation) unless read.key?(at)
29
+ given = operation.fetch("value", UNSET)
30
+ formula = operation["formula"]
31
+ change = { "value" => formula ? UNSET : given, "formula" => formula || UNSET,
32
+ "computed" => formula ? read[at] : given }
33
+ update(s, operation["row"], operation["col"], change)
34
+ end
35
+
36
+ def computed_of(sheet, operation)
37
+ current = sheet.cells.dig(operation["row"], operation["col"])
38
+ current ? current.fetch("computed", UNSET) : UNSET
39
+ end
40
+
41
+ def apply_insert(operation, _read)
42
+ s = sheet(operation["sheet"])
43
+ (operation["type"] == "insertRows" ? s.rows : s.cols).insert(operation["ids"], operation["before"])
44
+ end
45
+
46
+ def apply_format(operation, _read)
47
+ s = sheet(operation["range"]["sheet"])
48
+ key = operation["type"] == "setFormat" ? "format" : "style"
49
+ change = { key => operation[key].nil? ? UNSET : operation[key] }
50
+ cells_of(s, operation["range"]).each { |row, col| update(s, row, col, change) }
51
+ end
52
+
53
+ def apply_merge(operation, _read)
54
+ sheet(operation["range"]["sheet"]).merges += [deep(operation["range"].slice("start", "end"))]
55
+ end
56
+
57
+ def apply_unmerge(operation, _read)
58
+ area = operation["range"].slice("start", "end")
59
+ s = sheet(operation["range"]["sheet"])
60
+ s.merges = s.merges.reject { |m| m == area }
61
+ end
62
+
63
+ def apply_name(operation, _read)
64
+ operation["ref"].nil? ? @names.delete(operation["name"]) : @names[operation["name"]] = operation["ref"]
65
+ end
66
+
67
+ def apply_add_sheet(operation, _read)
68
+ rows, cols = operation.values_at("rows", "cols").map { |ids| Axis.new(ids) }
69
+ @sheets << Sheet.new(operation["id"], operation["name"], rows, cols, {}, [], NO_PANES)
70
+ end
71
+
72
+ def apply_remove_sheet(operation, _read)
73
+ @sheets.reject! { |s| s.id == operation["id"] }
74
+ @removed_sheets << operation["id"]
75
+ end
76
+
77
+ def apply_rename_sheet(operation, _read)
78
+ sheet(operation["id"]).name = operation["name"]
79
+ end
80
+
81
+ def apply_note(operation, _read)
82
+ note = operation["note"].nil? ? UNSET : operation["note"]
83
+ update(sheet(operation["sheet"]), operation["row"], operation["col"], { "note" => note })
84
+ end
85
+
86
+ def apply_freeze(operation, _read)
87
+ sheet(operation["sheet"]).frozen = operation.slice("rows", "cols")
88
+ end
89
+
90
+ def cells_of(sheet, area)
91
+ rows = span(sheet.rows.live, area, "row")
92
+ cols = span(sheet.cols.live, area, "col")
93
+ rows && cols ? rows.product(cols) : []
94
+ end
95
+
96
+ # The IDs from the start to the end of an area on one axis, or nil when an end is not there.
97
+ def span(ids, area, key)
98
+ from = ids.index(area["start"][key])
99
+ to = ids.index(area["end"][key])
100
+ ids[from..to] if from && to
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The row and column delete of `DocModel`, and the doc forms for the engine and the clients.
7
+ class DocModel
8
+ # The doc for the engine.
9
+ def sheet_doc
10
+ doc = to_doc
11
+ sheets = doc["sheets"].map do |s|
12
+ s.slice("id", "name", "rows", "cols").merge("cells" => engine_cells(s["cells"]))
13
+ end
14
+ { "sheets" => sheets, "names" => doc["names"] }
15
+ end
16
+
17
+ # The doc for the clients, with the computed values. Equal styles share one ID.
18
+ def to_doc
19
+ styles = {}
20
+ sheets = @sheets.map { |s| sheet_out(s, styles) }
21
+ { "sheets" => sheets, "names" => @names.map { |name, ref| { "name" => name, "ref" => ref } },
22
+ "styles" => styles.values.to_h }
23
+ end
24
+
25
+ private
26
+
27
+ def engine_cells(cells)
28
+ cells.filter_map { |c| c.slice("row", "col", "value", "formula") if c.key?("value") || c.key?("formula") }
29
+ end
30
+
31
+ def sheet_out(sheet, styles)
32
+ cells = sheet.cells.flat_map { |row, cols| cols.map { |col, cell| cell_out(row, col, cell, styles) } }
33
+ { "id" => sheet.id, "name" => sheet.name, "rows" => sheet.rows.live.dup, "cols" => sheet.cols.live.dup,
34
+ "cells" => cells, "merges" => deep(sheet.merges) }.merge(panes(sheet))
35
+ end
36
+
37
+ # Only when set, so a doc without panes keeps the form of wire version 1.
38
+ def panes(sheet) = sheet.frozen == NO_PANES ? {} : { "frozen" => sheet.frozen.dup }
39
+
40
+ def cell_out(row, col, cell, styles)
41
+ out = { "row" => row, "col" => col }.merge(cell.except("style"))
42
+ return out unless cell.key?("style")
43
+
44
+ # The key is the JSON text of the style, as in the TypeScript server.
45
+ id, = styles[cell["style"].to_json] ||= ["st#{styles.size + 1}", cell["style"]]
46
+ out.merge("style" => id)
47
+ end
48
+
49
+ def apply_delete(operation, _read)
50
+ s = sheet(operation["sheet"])
51
+ key = operation["type"] == "deleteRows" ? "row" : "col"
52
+ shrink_formulas({ "sheet" => s.id, "#{key}s" => operation["ids"] })
53
+ remove_ids(s, key, operation["ids"].to_set)
54
+ end
55
+
56
+ def remove_ids(sheet, key, gone)
57
+ axis = key == "row" ? sheet.rows : sheet.cols
58
+ sheet.merges = shrink_merges(sheet.merges, axis.live, key, gone)
59
+ drop_cells(sheet, key, gone)
60
+ axis.remove(gone)
61
+ end
62
+
63
+ def drop_cells(sheet, key, gone)
64
+ return gone.each { |id| sheet.cells.delete(id) } if key == "row"
65
+
66
+ sheet.cells.each_value { |cols| gone.each { |id| cols.delete(id) } }
67
+ end
68
+
69
+ def shrink_formulas(deletion)
70
+ context = ctx(false)
71
+ @sheets.each { |s| s.cells.each_value { |cols| shrink_row(cols, s.id, context, deletion) } }
72
+ @names.transform_values! { |ref| Refs.shrink_deleted(ref, deletion["sheet"], context, deletion) }
73
+ end
74
+
75
+ def shrink_row(cols, sheet_id, context, deletion)
76
+ cols.each do |col, cell|
77
+ next unless cell["formula"]
78
+
79
+ formula = Refs.shrink_deleted(cell["formula"], sheet_id, context, deletion)
80
+ cols[col] = cell.merge("formula" => formula) if formula != cell["formula"]
81
+ end
82
+ end
83
+
84
+ def shrink_merges(merges, ids, key, gone)
85
+ merges.filter_map do |area|
86
+ keep = (span(ids, area, key) || []).reject { |id| gone.include?(id) }
87
+ next if keep.empty?
88
+
89
+ { "start" => area["start"].merge(key => keep.first), "end" => area["end"].merge(key => keep.last) }
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # `DocModel#normalize`: the only transform. Every op names IDs, so the server checks each op
7
+ # against the current state.
8
+ class DocModel
9
+ NORMALIZE = {
10
+ "setCell" => :fit_set_cell, "insertRows" => :fit_insert, "insertCols" => :fit_insert,
11
+ "deleteRows" => :fit_delete, "deleteCols" => :fit_delete, "setFormat" => :fit_area,
12
+ "setStyle" => :fit_area, "merge" => :fit_area, "unmerge" => :fit_area, "setName" => :itself_op,
13
+ "addSheet" => :fit_add_sheet, "removeSheet" => :fit_remove_sheet, "renameSheet" => :fit_rename_sheet,
14
+ "setNote" => :fit_note, "freeze" => :fit_freeze
15
+ }.freeze
16
+
17
+ # The op as the server applies it now, or nil when it must drop.
18
+ def normalize(operation) = send(NORMALIZE.fetch(operation["type"]), operation)
19
+
20
+ private
21
+
22
+ def itself_op(operation) = operation
23
+
24
+ def fit_set_cell(operation)
25
+ s = sheet(operation["sheet"])
26
+ return unless s&.rows&.has?(operation["row"]) && s.cols.has?(operation["col"])
27
+
28
+ formula = operation["formula"]
29
+ formula ? operation.merge("formula" => late_formula(formula, operation["sheet"])) : operation
30
+ end
31
+
32
+ def fit_note(operation)
33
+ s = sheet(operation["sheet"])
34
+ operation if s&.rows&.has?(operation["row"]) && s.cols.has?(operation["col"])
35
+ end
36
+
37
+ def fit_freeze(operation) = sheet(operation["sheet"]) && operation
38
+
39
+ def axis_of(operation)
40
+ s = sheet(operation["sheet"])
41
+ s && (operation["type"].end_with?("Rows") ? s.rows : s.cols)
42
+ end
43
+
44
+ def unique?(ids) = ids.uniq.size == ids.size
45
+
46
+ def fit_insert(operation)
47
+ axis = axis_of(operation)
48
+ ids = operation["ids"]
49
+ return if axis.nil? || !unique?(ids) || ids.any? { |id| axis.known?(id) }
50
+
51
+ before = operation["before"]
52
+ return operation if before.nil?
53
+
54
+ operation.merge("before" => axis.next_live(before)) if axis.known?(before)
55
+ end
56
+
57
+ def fit_delete(operation)
58
+ axis = axis_of(operation)
59
+ ids = operation["ids"].uniq.select { |id| axis&.has?(id) }
60
+ return if ids.empty?
61
+
62
+ ids.size == operation["ids"].size ? operation : operation.merge("ids" => ids)
63
+ end
64
+
65
+ def fit_area(operation)
66
+ s = sheet(operation["range"]["sheet"])
67
+ range = s && late_area(s, operation["range"])
68
+ range && operation.merge("range" => range)
69
+ end
70
+
71
+ def fit_add_sheet(operation)
72
+ return if sheet(operation["id"]) || @removed_sheets.include?(operation["id"]) || name_used?(operation["name"])
73
+
74
+ operation if unique?(operation["rows"]) && unique?(operation["cols"])
75
+ end
76
+
77
+ def fit_remove_sheet(operation) = sheet(operation["id"]) && @sheets.size > 1 ? operation : nil
78
+
79
+ def fit_rename_sheet(operation)
80
+ operation if sheet(operation["id"]) && !name_used?(operation["name"], operation["id"])
81
+ end
82
+
83
+ # Moves the range ends of a late formula off deleted rows and columns.
84
+ def late_formula(formula, sheet_id)
85
+ deletions = @sheets.filter_map { |s| dead_of(s) }
86
+ return formula if deletions.empty?
87
+
88
+ context = ctx(true)
89
+ deletions.reduce(formula) { |f, deletion| Refs.shrink_deleted(f, sheet_id, context, deletion) }
90
+ end
91
+
92
+ def dead_of(sheet)
93
+ return if sheet.rows.dead.empty? && sheet.cols.dead.empty?
94
+
95
+ { "sheet" => sheet.id, "rows" => sheet.rows.dead.to_a, "cols" => sheet.cols.dead.to_a }
96
+ end
97
+
98
+ # Moves dead range ends inward in the full order; nil when no live row or column is left.
99
+ def late_area(sheet, range)
100
+ out = deep(range)
101
+ { "row" => sheet.rows, "col" => sheet.cols }.each do |key, axis|
102
+ live = live_span(axis, range, key) or return nil
103
+ move_ends(out, key, axis, live)
104
+ end
105
+ out
106
+ end
107
+
108
+ def move_ends(out, key, axis, live)
109
+ out["start"][key] = live.first if axis.dead.include?(out["start"][key])
110
+ out["end"][key] = live.last if axis.dead.include?(out["end"][key])
111
+ end
112
+
113
+ def live_span(axis, range, key)
114
+ live = span(axis.all, range, key)&.reject { |id| axis.dead.include?(id) }
115
+ live unless live.nil? || live.empty?
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The op log server for sheet docs (plan 8.4, ADR 0016): a port of `createDocServer` in
7
+ # packages/server/src/collab/server.ts. The server holds the truth. It orders the submits,
8
+ # applies each op that still fits the current state, recalcs with the engine and sends the
9
+ # applied ops and the changes to every client. It has no transport: see `Channel`.
10
+ #
11
+ # Thread safety: each open doc has a lock, so the submits of one doc run one at a time.
12
+ class DocServer
13
+ # One open doc. `done` maps `[clientId, opId]` to its seq, so a resent submit applies once.
14
+ OpenDoc = Struct.new(:id, :seq, :model, :engine, :done, :conns, :presence, :lock)
15
+
16
+ # `engine` makes a new engine for each open doc, for example `-> { IronCalc.new }`.
17
+ def initialize(store:, engine:, snapshot_every: 100)
18
+ @store = store
19
+ @engine = engine
20
+ @snapshot_every = snapshot_every
21
+ @docs = {}
22
+ @lock = Mutex.new
23
+ end
24
+
25
+ # Makes a new doc at seq 0.
26
+ def create(doc_id, doc)
27
+ model = DocModel.new(doc)
28
+ @store.save_snapshot(doc_id, { "seq" => 0, "doc" => model.to_doc, "axes" => model.axes })
29
+ end
30
+
31
+ # A new client link. The block takes each server message (a Hash with String keys).
32
+ def connect(&send) = Connection.new(self, send)
33
+
34
+ # The current doc, with the computed values: `{ "seq", "doc" }`.
35
+ def snapshot(doc_id)
36
+ doc = open_doc(doc_id) or raise ArgumentError, %(Lattice: no doc "#{doc_id}")
37
+ doc.lock.synchronize { { "seq" => doc.seq, "doc" => doc.model.to_doc } }
38
+ end
39
+
40
+ # The op log: the version history.
41
+ def history(doc_id) = @store.entries(doc_id, 0)
42
+
43
+ # The doc as it was after `seq`, from the nearest snapshot and the log.
44
+ def doc_at(doc_id, seq)
45
+ built = rebuild(doc_id, seq) or raise ArgumentError, %(Lattice: no doc "#{doc_id}" at seq #{seq})
46
+ built[0].to_doc
47
+ end
48
+
49
+ # The open doc, or nil when the doc does not exist. Used by `Connection`.
50
+ def open_doc(doc_id)
51
+ @lock.synchronize { @docs[doc_id] ||= load_doc(doc_id) }
52
+ end
53
+
54
+ private
55
+
56
+ def load_doc(doc_id)
57
+ model, seq = rebuild(doc_id)
58
+ return unless model
59
+
60
+ engine = @engine.call
61
+ engine.load(model.sheet_doc)
62
+ model.take(engine.values)
63
+ # All entries, so a resend after a restart applies once also when a snapshot holds it.
64
+ done = @store.entries(doc_id, 0).to_h { |e| [[e["clientId"], e["opId"]], e["seq"]] }
65
+ OpenDoc.new(doc_id, seq, model, engine, done, [], {}, Monitor.new)
66
+ end
67
+
68
+ def rebuild(doc_id, up_to = nil)
69
+ snap = @store.snapshot(doc_id, up_to) or return
70
+ model = DocModel.new(snap["doc"], snap["axes"])
71
+ entries = @store.entries(doc_id, snap["seq"], up_to)
72
+ entries.each { |entry| replay(model, entry) }
73
+ [model, entries.last&.fetch("seq") || snap["seq"]]
74
+ end
75
+
76
+ def replay(model, entry)
77
+ read = {}
78
+ entry["ops"].each { |operation| model.apply(operation, read) }
79
+ model.take(entry["changes"])
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The join, submit, presence and close rules of `DocServer`. `Connection` calls them with
7
+ # the lock of the doc held.
8
+ class DocServer
9
+ # The ops that change only the model. The engine does not get them.
10
+ MODEL_OPS = %w[setNote freeze].freeze
11
+
12
+ def join(conn, doc, message)
13
+ conn.attach(doc, message["clientId"], message["name"] || message["clientId"])
14
+ doc.conns << conn unless doc.conns.include?(conn)
15
+ catch_up(conn, doc, message["sinceSeq"])
16
+ send_peers(conn, doc)
17
+ end
18
+
19
+ def submit(conn, doc, message)
20
+ seen = doc.done[message.values_at("clientId", "opId")]
21
+ return conn.send_message(msg("ack", doc.id, "opId" => message["opId"], "seq" => seen)) if seen
22
+
23
+ reason = sequence(doc, message)
24
+ conn.send_message(reject(doc.id, message["opId"], reason)) if reason
25
+ end
26
+
27
+ def presence(conn, doc, message)
28
+ state = message.slice("cursor", "selection", "editing")
29
+ doc.presence[conn.client_id] = { name: conn.name, state: state, conn: conn }
30
+ broadcast(doc, presence_message(doc, conn.client_id, conn.name, state), except: conn.client_id)
31
+ end
32
+
33
+ def leave(conn, doc)
34
+ doc.conns.delete(conn)
35
+ doc.presence.delete(conn.client_id) if doc.presence.dig(conn.client_id, :conn).equal?(conn)
36
+ broadcast(doc, msg("leave", doc.id, "clientId" => conn.client_id))
37
+ end
38
+
39
+ def reject(doc_id, op_id, reason) = msg("reject", doc_id, "opId" => op_id, "reason" => reason)
40
+
41
+ private
42
+
43
+ def msg(type, doc_id, rest = {}) = { "v" => 1, "type" => type, "docId" => doc_id }.merge(rest)
44
+
45
+ def presence_message(doc, client_id, name, state)
46
+ msg("presence", doc.id, "clientId" => client_id, "name" => name).merge(state)
47
+ end
48
+
49
+ def catch_up(conn, doc, since)
50
+ missed = missed(doc, since)
51
+ return missed.each { |e| conn.send_message(msg("ops", doc.id, e)) } if missed
52
+
53
+ conn.send_message(msg("snapshot", doc.id, "seq" => doc.seq, "doc" => doc.model.to_doc))
54
+ end
55
+
56
+ # The entries after `since`, or nil when the client needs a snapshot. A store can drop old
57
+ # entries: then the client loads a snapshot.
58
+ def missed(doc, since)
59
+ return if since.nil? || since > doc.seq
60
+
61
+ entries = @store.entries(doc.id, since)
62
+ entries if entries.size == doc.seq - since
63
+ end
64
+
65
+ def send_peers(conn, doc)
66
+ doc.presence.each do |client_id, peer|
67
+ next if client_id == conn.client_id
68
+
69
+ conn.send_message(presence_message(doc, client_id, peer[:name], peer[:state]))
70
+ end
71
+ end
72
+
73
+ def broadcast(doc, message, except: nil)
74
+ doc.conns.each { |c| c.send_message(message) unless except && c.client_id == except }
75
+ end
76
+
77
+ # Applies a new submit. Gives the reject reason, or nil.
78
+ def sequence(doc, message)
79
+ ops = fit(doc, message["ops"])
80
+ return "conflict" if ops.empty?
81
+
82
+ changes = recalc(doc, ops) or return "invalid"
83
+ record(doc, message.slice("clientId", "opId").merge("seq" => doc.seq + 1, "ops" => ops, "changes" => changes))
84
+ nil
85
+ end
86
+
87
+ def fit(doc, ops)
88
+ read = {}
89
+ ops.filter_map do |operation|
90
+ fitted = doc.model.normalize(operation)
91
+ doc.model.apply(fitted, read) if fitted
92
+ fitted
93
+ end
94
+ end
95
+
96
+ # The changes, or nil when the engine refused an op. Then the model goes back to the log.
97
+ def recalc(doc, ops)
98
+ engine_changes(doc, ops)
99
+ rescue StandardError
100
+ doc.model = rebuild(doc.id)[0]
101
+ doc.engine.load(doc.model.sheet_doc)
102
+ doc.model.take(doc.engine.values)
103
+ nil
104
+ end
105
+
106
+ # Notes and panes are model ops only: the engine does not know them.
107
+ def engine_changes(doc, ops)
108
+ engine_ops = ops.reject { |o| MODEL_OPS.include?(o["type"]) }
109
+ engine_ops.empty? ? [] : doc.engine.apply(engine_ops)
110
+ end
111
+
112
+ def record(doc, entry)
113
+ doc.model.take(entry["changes"])
114
+ doc.seq = entry["seq"]
115
+ doc.done[entry.values_at("clientId", "opId")] = doc.seq
116
+ @store.append(doc.id, entry)
117
+ broadcast(doc, msg("ops", doc.id, entry))
118
+ save_snapshot(doc)
119
+ end
120
+
121
+ def save_snapshot(doc)
122
+ return unless (doc.seq % @snapshot_every).zero?
123
+
124
+ @store.save_snapshot(doc.id, { "seq" => doc.seq, "doc" => doc.model.to_doc, "axes" => doc.model.axes })
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end