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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0c9eeadf8275453bb3f42a134e630b334dd756090a053f7b3494bc0a43cc1fa2
4
+ data.tar.gz: 5f1cc1728eb4364ff5c25c3cef1febe1760ebfdac793f232dbdb5727bfb4a17a
5
+ SHA512:
6
+ metadata.gz: 8922d2f4a399e911957697eb8e3edf06ff2f27c021c7a83d107827118598fa3b5759f7ad38b1688163fdb8c5084bc7b567aa4bbd70fea4a52df5b4d8336f1f01
7
+ data.tar.gz: 4de0d87936b384cda476a648302c801fb4f41123f3a60cc50d9d3ccde59587f1ff5d4dabdfb02218cb98f979faeada638e1dbc1eedef98db1501d84e5032b720
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,179 @@
1
+ # lattice-grid
2
+
3
+ The Lattice grid wire protocol, version 1, for Rails and ActiveRecord. The gem answers the
4
+ row requests of a Lattice grid from an ActiveRecord relation. The protocol is in
5
+ [ADR 0005](../../docs/adr/0005-wire-protocol.md).
6
+
7
+ Part of [Lattice](https://joegaudet.com/ember-lattice/). Not released yet.
8
+
9
+ ## Install
10
+
11
+ ```ruby
12
+ gem "lattice-grid"
13
+ ```
14
+
15
+ The gem needs Ruby 3.2 or later and ActiveRecord 7.1 or later.
16
+
17
+ ## The allow-list
18
+
19
+ The allow-list is the trust boundary. A request can use only the columns, filter ops and
20
+ aggregate functions that the allow-list names. Each column is a column of the table of the model.
21
+
22
+ ```ruby
23
+ COLUMNS = [
24
+ { name: "id", type: :number, filter: %i[eq in], sort: true },
25
+ { name: "name", type: :string, filter: %i[eq contains blank], sort: true, search: true },
26
+ { name: "dept", type: :string, filter: %i[eq in], sort: true, group: true, aggregate: %i[count] },
27
+ { name: "salary", type: :number, filter: %i[gt lt between], sort: true, aggregate: %i[sum avg min max] },
28
+ { name: "hired", type: :date, filter: %i[lt gt inRange], sort: true }
29
+ ].freeze
30
+ ```
31
+
32
+ The types are `string`, `number`, `boolean` and `date`. The `key:` option names the unique row
33
+ id. Cursor paging needs it.
34
+
35
+ ## A Rails controller
36
+
37
+ ```ruby
38
+ class PeopleController < ApplicationController
39
+ include Lattice::Grid::Controller
40
+
41
+ def rows
42
+ render_lattice(Person.where(account: current_account), columns: COLUMNS, key: "id")
43
+ end
44
+ end
45
+ ```
46
+
47
+ `render_lattice` reads the raw JSON body. It renders the response with status 200, or the
48
+ errors with status 400. It rejects a body that is larger than 1 MB. Set a different limit
49
+ with `max_body:`. The check runs after Rails reads the body, so also limit the body size in
50
+ Rack or in the proxy.
51
+
52
+ Keep the tenant conditions in the relation. The gem adds its conditions to them. It replaces
53
+ only the order, the select, the limit and the offset of the relation.
54
+
55
+ ## Without the concern
56
+
57
+ ```ruby
58
+ render json: Lattice::Grid.respond(scope, request.raw_post, columns: COLUMNS, key: "id")
59
+ ```
60
+
61
+ `respond` accepts a JSON string, a Hash or Rails `params`. Use the raw body if you can.
62
+ Rails `params` can add keys, and `wrap_parameters` adds a key. The parser rejects each unknown
63
+ key. When the response has `errors`, send it with status 400.
64
+
65
+ To parse a request only, use `Lattice::Grid::Request.parse(input, columns: COLUMNS)`. It never
66
+ raises. It returns a result with `ok?`, `value` and `errors`. The value is a frozen copy that
67
+ holds only known keys.
68
+
69
+ To run a request on a relation, use
70
+ `Lattice::Grid::Query.new(scope, columns: COLUMNS, key: "id").call(input)`.
71
+
72
+ ## Security
73
+
74
+ - The parser is a port of `parseRowsRequest`. It has the same limits and gives the same errors.
75
+ - Column names in SQL come from the allow-list, never from the request.
76
+ - Every value is a bind parameter: filter values, search terms, group keys, pivot keys and
77
+ cursor values.
78
+ - SQL aliases are fixed names such as `a0` and `p1`. The output keys are set in Ruby.
79
+ - The gem checks each cursor value against the type of its sort column.
80
+ - The parser rejects a string that holds U+0000 or a lone surrogate, with the code `bad_string`.
81
+ In Ruby, a lone surrogate is invalid UTF-8. In a JSON body, `respond` changes a lone `\uD800`
82
+ escape to U+0000 before it parses the body, so the result is the same as in JavaScript.
83
+ - Before it builds the pivot SQL, the gem counts the distinct pivot values. Above 200, it rejects
84
+ the request with the code `pivot_too_wide`.
85
+
86
+ ## Semantics
87
+
88
+ The gem follows the reference evaluator in `packages/protocol/src/evaluate.ts`:
89
+
90
+ - Strings sort and compare in binary order. On Postgres the gem adds `COLLATE "C"`. On MySQL it
91
+ adds `COLLATE utf8mb4_bin`.
92
+ - Nulls are last by default, in both directions. The gem writes `NULLS FIRST` or `NULLS LAST`.
93
+ - `contains`, `startsWith` and `endsWith` use `LOWER(column) LIKE LOWER(pattern) ESCAPE '\'`.
94
+ `%`, `_` and `\` in a value are literal characters.
95
+ - Dates compare as instants. A date-time without a zone is UTC. Each date field must exist on the
96
+ calendar, and the year is 0001 to 9999.
97
+ - A pivot `field` is the compact JSON of the keys and the value key. The gem writes numbers as
98
+ JavaScript does, for example `1e-7` and `1`.
99
+ - Pivot cells use `FILTER (WHERE ...)` on Postgres and `CASE` on other databases.
100
+ - `first` and `last` use `FIRST_VALUE` window functions in the leaf sort order.
101
+ - The gem counts the rows only when the request asks, or when the page is the last page.
102
+
103
+ ## Known differences
104
+
105
+ - SQLite `LOWER` changes ASCII letters only. JavaScript changes all letters. The conformance
106
+ data is ASCII.
107
+ - Strings with characters above U+FFFF can sort in a different order. Databases use code point
108
+ order; JavaScript uses UTF-16 code unit order.
109
+ - A date-time column comes back as `2020-01-01T10:00:00.000Z`, not as the text that was stored.
110
+ - MySQL is not tested.
111
+
112
+ ## Collaboration (the op log server)
113
+
114
+ `Lattice::Grid::Collab` is a port of the Node collab server in `packages/server/src/collab`
115
+ ([ADR 0016](../../docs/adr/0016-collaboration.md)). It has the same wire format, limits,
116
+ conflict rules, tombstones, snapshots, history and presence. Load it on its own:
117
+
118
+ ```ruby
119
+ require "lattice/grid/collab"
120
+
121
+ server = Lattice::Grid::Collab::DocServer.new(
122
+ store: Lattice::Grid::Collab::MemoryStore.new,
123
+ engine: -> { Lattice::Grid::Collab::IronCalc.new }
124
+ )
125
+ server.create("d1", { "sheets" => [{ "id" => "s1", "name" => "Sheet1", "rows" => ["r1"], "cols" => ["c1"], "cells" => [] }] })
126
+ ```
127
+
128
+ For Action Cable, `require "lattice/grid/collab/channel"` and set
129
+ `Lattice::Grid::Collab::Channel.collab_server = server`. To use your own
130
+ `ApplicationCable::Channel`, include `Lattice::Grid::Collab::ChannelHandler` and define
131
+ `collab_server`. Authenticate the connection before it subscribes: the server trusts the client
132
+ ID of the join.
133
+
134
+ The formula engine is the IronCalc WASI module of [ADR 0007](../../docs/adr/0007-server-formula-runtime.md)
135
+ and [ADR 0020](../../docs/adr/0020-ironcalc-wasi-module.md). It needs the `wasmtime` gem (add
136
+ `gem "wasmtime"` to your Gemfile). The gem ships the module in `wasm/ironcalc_wasi.wasm`. Set
137
+ `LATTICE_IRONCALC_WASM` or `Lattice::Grid::Collab::WasmBook.path` to use another file. The engine
138
+ keeps the workbook between submits and applies each submit with one `ic_apply_batch` call: about
139
+ 5 ms to 20 ms for each submit at 10,000 cells.
140
+
141
+ Action Cable can run two messages of one connection on two threads, in a different order. The
142
+ channel runs its messages one at a time, and it holds the messages that arrive before the first
143
+ join until that join is done.
144
+
145
+ `spec/fixtures/collab/collab.json` holds client message sequences and the outputs of the Node
146
+ server. The cross spec checks that the Ruby server gives the same outputs. Make the file again
147
+ after a change to the Node server:
148
+
149
+ ```sh
150
+ volta run --node 24.11.1 node ruby/lattice-grid/spec/fixtures/collab/generate.mjs # from the repo root
151
+ ```
152
+
153
+ ## Tests
154
+
155
+ The collab specs need the IronCalc module. Build it first; the specs find it in `target/`:
156
+
157
+ ```sh
158
+ (cd ../../wasm/ironcalc-wasi && cargo build --release --target wasm32-wasip1)
159
+ bundle config set --local path vendor/bundle
160
+ bundle install
161
+ bundle exec rspec
162
+ LATTICE_PG=1 bundle exec rspec # Postgres too; PGHOST and PGUSER select the server
163
+ bundle exec rubocop
164
+ ```
165
+
166
+ `gem build` needs the module in the gem. Copy it there first, as CI does:
167
+
168
+ ```sh
169
+ mkdir -p wasm && cp ../../wasm/ironcalc-wasi/target/wasm32-wasip1/release/ironcalc_wasi.wasm wasm/
170
+ gem build lattice-grid.gemspec
171
+ ```
172
+
173
+ The conformance spec runs every case in `packages/protocol/conformance/cases.v1.json`. The
174
+ Postgres tests make and drop the database `lattice_test_ruby`. They skip when the server does
175
+ not answer.
176
+
177
+ ## License
178
+
179
+ MIT
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Aggregates and `$count`. They read a subquery, `lattice_rows`, over the request scope.
6
+ # `first` and `last` read FIRST_VALUE window columns of that subquery.
7
+ class AggregateSql
8
+ ROWS = Arel::Table.new("lattice_rows")
9
+ FIRST_LAST = %w[first last].freeze
10
+
11
+ def initialize(context, pivot)
12
+ @context = context
13
+ @sql = context.sql
14
+ @pivot = pivot
15
+ end
16
+
17
+ # The subquery. `partition` names the group columns of the `first` and `last` windows.
18
+ def relation(partition)
19
+ inner = @context.base.select(*inner_columns.map { |n| @sql.table[n] }, *all_windows(partition))
20
+ @context.model.unscoped.from(inner, ROWS.name)
21
+ end
22
+
23
+ # The aggregates, `$count` and the pivot cells.
24
+ def selects
25
+ aggregate_selects + [@sql.function("COUNT", Arel.star).as("n")] + @pivot.selects(self)
26
+ end
27
+
28
+ # The output of `selects`.
29
+ def cells(row)
30
+ aggregate_cells(row).merge(GROUP_COUNT_KEY => @context.cells.number(row["n"])).merge(@pivot.cells(row))
31
+ end
32
+
33
+ # The aggregates over the whole scope.
34
+ def total
35
+ aggregate_cells(@context.select_all(relation([]).select(*aggregate_selects)).first)
36
+ end
37
+
38
+ # One aggregate over `lattice_rows`, for the rows that match `cond` when it is given.
39
+ # Postgres uses FILTER (WHERE cond); other databases use CASE.
40
+ def node(agg, index, prefix, cond = nil)
41
+ expr = input(agg, index, prefix)
42
+ fn = FIRST_LAST.include?(agg.fn) ? "MIN" : agg.fn.upcase
43
+ return @sql.function(fn, expr) unless cond
44
+ return @sql.function(fn, expr).filter(cond) if @sql.postgres?
45
+
46
+ @sql.function(fn, Arel::Nodes::Case.new.when(cond).then(expr))
47
+ end
48
+
49
+ private
50
+
51
+ def aggregates
52
+ @context.request.aggregate
53
+ end
54
+
55
+ def aggregate_selects
56
+ aggregates.each_with_index.map { |agg, i| node(agg, i, "w").as("a#{i}") }
57
+ end
58
+
59
+ def aggregate_cells(row)
60
+ aggregates.each_with_index.to_h { |agg, i| [agg.key, @context.cells.aggregate(agg, row["a#{i}"])] }
61
+ end
62
+
63
+ def inner_columns
64
+ (@context.request.group.by + aggregates.map(&:column) + @pivot.by + @pivot.values.map(&:column)).uniq
65
+ end
66
+
67
+ def all_windows(partition)
68
+ windows(aggregates, partition, "w") + windows(@pivot.values, partition + @pivot.by, "v")
69
+ end
70
+
71
+ def windows(list, partition, prefix)
72
+ list.each_with_index.filter_map do |agg, i|
73
+ window(agg, partition).as("#{prefix}#{i}") if FIRST_LAST.include?(agg.fn)
74
+ end
75
+ end
76
+
77
+ # FIRST_VALUE in the leaf order. `last` is FIRST_VALUE in the reverse order.
78
+ def window(agg, partition)
79
+ window = Arel::Nodes::Window.new
80
+ window.partition(*partition.map { |n| @sql.table[n] }) if partition.any?
81
+ order = window_order(agg)
82
+ window.order(*order) if order.any?
83
+ @sql.function("FIRST_VALUE", @sql.table[agg.column]).over(window)
84
+ end
85
+
86
+ def window_order(agg)
87
+ keys = agg.fn == "last" ? Keyset.reverse(@context.leaf_keys) : @context.leaf_keys
88
+ keys.map { |key| @sql.order(*key) }
89
+ end
90
+
91
+ def input(agg, index, prefix)
92
+ return ROWS["#{prefix}#{index}"] if FIRST_LAST.include?(agg.fn)
93
+
94
+ %w[min max].include?(agg.fn) ? @sql.collated(agg.column, ROWS) : ROWS[agg.column]
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "json"
5
+
6
+ module Lattice
7
+ module Grid
8
+ # Turns database values into protocol JSON values, and reads and writes cursors.
9
+ class Cells
10
+ # A decoded cursor value fits the type of its sort column.
11
+ FITS = {
12
+ "string" => ->(v) { Kind.string?(v) && !Kind.bad_string?(v) },
13
+ "number" => ->(v) { !Kind.number(v).nil? },
14
+ "boolean" => ->(v) { Kind.boolean?(v) },
15
+ "date" => ->(v) { Dates.valid?(v) }
16
+ }.freeze
17
+
18
+ def initialize(model, columns)
19
+ @model = model
20
+ @types = columns.to_h { |c| [c.name, c.type] }
21
+ end
22
+
23
+ # The JSON value of a raw database value of a column.
24
+ def cell(name, raw)
25
+ return if raw.nil?
26
+
27
+ case @types.fetch(name)
28
+ when "number" then number(raw)
29
+ when "boolean" then ActiveModel::Type::Boolean.new.cast(raw)
30
+ when "date" then date(@model.type_for_attribute(name).deserialize(raw))
31
+ else raw.to_s
32
+ end
33
+ end
34
+
35
+ # The JSON value of an aggregate.
36
+ def aggregate(agg, raw)
37
+ %w[sum avg count].include?(agg.fn) ? number(raw) : cell(agg.column, raw)
38
+ end
39
+
40
+ # A number as JavaScript gives it: a whole value is an Integer.
41
+ def number(raw)
42
+ return if raw.nil?
43
+ return raw if Kind.of?(raw, Integer)
44
+
45
+ float = (Kind.string?(raw) ? BigDecimal(raw) : raw).to_f
46
+ float.finite? && float == float.floor && float.abs < 2**53 ? float.to_i : float
47
+ end
48
+
49
+ # The cursor is the JSON tuple of the sort values of a row.
50
+ def encode(tuple)
51
+ JSON.generate(tuple)
52
+ end
53
+
54
+ # Decodes a cursor, and checks each value against the type of its sort column.
55
+ def decode(cursor, names, path)
56
+ tuple = parse(cursor)
57
+ return tuple if Kind.of?(tuple, Array) && tuple.size == names.size && tuple.each_with_index.all? do |v, i|
58
+ fits?(v, names[i])
59
+ end
60
+
61
+ raise Failure, Issue.new(path: path, code: "bad_cursor", message: "bad cursor")
62
+ end
63
+
64
+ private
65
+
66
+ def parse(cursor)
67
+ JSON.parse(cursor, max_nesting: 2)
68
+ rescue JSON::ParserError
69
+ nil
70
+ end
71
+
72
+ def fits?(value, name)
73
+ value.nil? || FITS.fetch(@types.fetch(name)).call(value)
74
+ end
75
+
76
+ def date(value)
77
+ case value
78
+ when Date then value.iso8601
79
+ when Time, DateTime then value.to_time.utc.iso8601(3)
80
+ else value&.to_s
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # One axis of a sheet: the live order, and the full order with the deleted IDs in their old
7
+ # places (the tombstones). A port of `Axis` in packages/server/src/collab/model.ts.
8
+ class Axis
9
+ attr_reader :live, :all, :dead
10
+
11
+ def initialize(live, all = nil)
12
+ @live = live.dup
13
+ @all = (all || live).dup
14
+ @known = @all.to_set
15
+ alive = live.to_set
16
+ @dead = @all.reject { |id| alive.include?(id) }.to_set
17
+ end
18
+
19
+ def has?(id) = @known.include?(id) && !@dead.include?(id)
20
+
21
+ def known?(id) = @known.include?(id)
22
+
23
+ # The first live ID at or after `id` in the full order, or nil for the end.
24
+ def next_live(id)
25
+ @all.drop(@all.index(id)).find { |x| !@dead.include?(x) }
26
+ end
27
+
28
+ def insert(ids, before)
29
+ [@live, @all].each { |list| list.insert(before.nil? ? list.size : list.index(before), *ids) }
30
+ @known.merge(ids)
31
+ end
32
+
33
+ def remove(ids)
34
+ @live.reject! { |id| ids.include?(id) }
35
+ @dead.merge(ids)
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_cable"
4
+ require "lattice/grid/collab"
5
+
6
+ module Lattice
7
+ module Grid
8
+ module Collab
9
+ # An Action Cable channel for the collab server. Load it with
10
+ # `require "lattice/grid/collab/channel"` in a Rails app:
11
+ #
12
+ # Lattice::Grid::Collab::Channel.collab_server = Lattice::Grid::Collab::DocServer.new(
13
+ # store: MyStore.new, engine: -> { Lattice::Grid::Collab::IronCalc.new }
14
+ # )
15
+ #
16
+ # To use your own `ApplicationCable::Channel`, include `ChannelHandler` and define
17
+ # `collab_server` there.
18
+ class Channel < ActionCable::Channel::Base
19
+ include ChannelHandler
20
+
21
+ class << self
22
+ attr_accessor :collab_server
23
+ end
24
+
25
+ private
26
+
27
+ def collab_server = self.class.collab_server || Channel.collab_server
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The message handling of the Action Cable channel, with no dependency on Rails. A port of
7
+ # `attachSocket` in packages/server/src/collab/socket.ts. The including class gives
8
+ # `transmit(message)` (as `ActionCable::Channel::Base` does) and `collab_server`.
9
+ #
10
+ # Authenticate the connection before it subscribes: the server trusts the client ID of the
11
+ # join. Action Cable parses the JSON before `receive`, so the size check here is a second
12
+ # limit; also limit the frame size in the proxy.
13
+ #
14
+ # Action Cable runs the commands of one connection on a pool of threads, so they can run
15
+ # out of order: a message can run before `subscribed`, and a submit sent after a join can
16
+ # run before it. A lock runs the messages of one channel one at a time, and the channel
17
+ # holds each message that runs before the first join until that join is done.
18
+ module ChannelHandler
19
+ MAX_BYTES = 1_000_000
20
+ # The messages that a channel holds until its first join. When more wait, all go on at once
21
+ # (and get `not_joined`), so a client that never joins cannot fill the memory.
22
+ HOLD_MAX = 100
23
+ LOCKS = Mutex.new
24
+
25
+ # The only public method: Action Cable lets a client call each public method as an action.
26
+ def receive(data)
27
+ return collab_reject("too_large") if JSON.generate(data).bytesize > collab_max_bytes
28
+
29
+ # `perform` adds the "action" key; the wire format does not know it.
30
+ message = data.is_a?(Hash) ? data.except("action") : data
31
+ collab_lock.synchronize { collab_deliver(message) }
32
+ rescue JSON::GeneratorError
33
+ collab_reject("bad_message")
34
+ end
35
+
36
+ private
37
+
38
+ def subscribed
39
+ collab_lock.synchronize { collab }
40
+ end
41
+
42
+ def unsubscribed
43
+ collab_lock.synchronize do
44
+ @collab&.close
45
+ @collab_held = nil
46
+ end
47
+ end
48
+
49
+ def collab_max_bytes = MAX_BYTES
50
+ def collab_hold_max = HOLD_MAX
51
+
52
+ def collab = @collab ||= collab_server.connect { |message| transmit(message) }
53
+
54
+ def collab_lock = @collab_lock || LOCKS.synchronize { @collab_lock ||= Mutex.new }
55
+
56
+ def collab_deliver(message)
57
+ join = message.is_a?(Hash) && message["type"] == "join"
58
+ held = (@collab_held ||= [])
59
+ return collab_hold(held, message) unless join || @collab_joined
60
+
61
+ collab.receive(message)
62
+ return unless join
63
+
64
+ @collab_joined = true
65
+ collab_flush(held)
66
+ end
67
+
68
+ def collab_hold(held, message)
69
+ held << message
70
+ collab_flush(held) if held.length > collab_hold_max
71
+ end
72
+
73
+ def collab_flush(held)
74
+ @collab_held = []
75
+ held.each { |m| collab.receive(m) }
76
+ end
77
+
78
+ def collab_reject(reason)
79
+ transmit({ "v" => 1, "type" => "reject", "docId" => "", "opId" => nil, "reason" => reason })
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # One client link to a `DocServer`. The transport calls `receive` for each parsed JSON
7
+ # message and `close` at the end. `receive` never raises.
8
+ class Connection
9
+ ACTIONS = { "submit" => :submit, "presence" => :presence }.freeze
10
+
11
+ attr_reader :client_id, :name
12
+
13
+ def initialize(server, send)
14
+ @server = server
15
+ @send = send
16
+ @lock = Mutex.new
17
+ end
18
+
19
+ # Takes one parsed JSON message. The messages of one link run one at a time.
20
+ def receive(input)
21
+ @lock.synchronize { handle(input) }
22
+ nil
23
+ end
24
+
25
+ def close
26
+ @lock.synchronize do
27
+ doc = @doc
28
+ next if doc.nil? || @client_id.nil?
29
+
30
+ @doc = nil
31
+ doc.lock.synchronize { @server.leave(self, doc) }
32
+ end
33
+ end
34
+
35
+ # Used by `DocServer`.
36
+ def send_message(message) = @send.call(message)
37
+
38
+ def attach(doc, client_id, name)
39
+ @doc = doc
40
+ @client_id = client_id
41
+ @name = name
42
+ end
43
+
44
+ private
45
+
46
+ def handle(input)
47
+ parsed = Wire.parse(input)
48
+ return route(parsed.message) if parsed.ok?
49
+
50
+ doc_id = input.is_a?(Hash) && input["docId"].is_a?(String) ? input["docId"] : ""
51
+ send_message(@server.reject(doc_id, nil, "bad_message"))
52
+ end
53
+
54
+ def route(message)
55
+ doc = @server.open_doc(message["docId"]) or return refuse(message, "unknown_doc")
56
+ return doc.lock.synchronize { @server.join(self, doc, message) } if message["type"] == "join"
57
+ return refuse(message, "not_joined") unless joined?(doc, message)
58
+
59
+ doc.lock.synchronize { @server.public_send(ACTIONS.fetch(message["type"]), self, doc, message) }
60
+ rescue StandardError
61
+ refuse(message, "server_error")
62
+ end
63
+
64
+ def refuse(message, reason) = send_message(@server.reject(message["docId"], message["opId"], reason))
65
+
66
+ def joined?(doc, message)
67
+ @doc.equal?(doc) && (message["type"] != "submit" || message["clientId"] == @client_id)
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end