dovetail 1.0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 75c91fdbedb2d615db9034b8d73d095aa4227df18599fb676c618ea5014c3980
4
+ data.tar.gz: 2511297ffcb29966c8211d556518426f7f081efddb9403e6e39c23341b59c087
5
+ SHA512:
6
+ metadata.gz: 8e2c186e8dd6dfc67f6dd0a3813db1976d28580380f060cbe7033715bc19105032d7fb2bf2f8d701a6162cfcbc1a23186e445a7a8ce164ca45b194cec4c43f8d
7
+ data.tar.gz: 2a8f9f2355cdbfbe3534c6a7f5f032e53fb643d4c1f812577f074a8eee3864102af7ae82bff18f7ea4a4fd1ec96c4185d16c98a562ce52def66331b5e6bc9c48
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,63 @@
1
+ # dovetail
2
+
3
+ The Ruby gem of [Dovetail](https://joegaudet.com/dovetail/): the protocol, rooms, the store
4
+ feed, the doc relay, awareness and notifications, for any Rack app. Not released yet. For
5
+ Rails, use `dovetail-rails`.
6
+
7
+ ```ruby
8
+ server = Dovetail::Server.new(
9
+ # The token is "<user id>.<secret>". The table keeps only the SHA-256 digest of the secret.
10
+ authenticate: lambda do |token|
11
+ id, secret = token.to_s.split(".", 2)
12
+ next nil if id.to_s.empty? || secret.to_s.empty?
13
+
14
+ user = User.find_by(id: id)
15
+ user if user&.token_digest && OpenSSL.secure_compare(user.token_digest, Digest::SHA256.hexdigest(secret))
16
+ end,
17
+ authorize: ->(user, room, action) { true },
18
+ handle_write: ->(write) { { ok: true } }, # write: { user:, session:, id:, room:, op: }
19
+ on_session_end: ->(info) { } # info: { id:, user:, rooms: }, once at the close
20
+ )
21
+
22
+ session = server.connect(sink) # sink: send_text(text), close(code, reason)
23
+ session.receive(frame) # each frame from the wire
24
+ session.closed # when the wire closes
25
+
26
+ server.publish("note:1", { "data" => { "type" => "note", "id" => "1" } })
27
+ server.notify("u2", verb: "commented", actor: { "type" => "user", "id" => "u1" },
28
+ target: { "type" => "note", "id" => "1" })
29
+ ```
30
+
31
+ | Part | |
32
+ | ------------------------------- | ----------------------------------------------------------------- |
33
+ | `Dovetail::Protocol.parse` | The trust boundary. The same checks and limits as `parseMessage`. |
34
+ | `Dovetail::Server` | The rules of `docs/protocol.md` and ADR 0012, as the Node server. |
35
+ | `Dovetail::NotificationsApp` | A Rack app: `GET /` (a page of notifications) and `POST /read-all`. |
36
+ | `MemoryNotificationStore`, `MemoryDocPersistence`, `MemoryFeedLog`, `LocalFanout` | The memory defaults, for development and tests only. |
37
+
38
+ Call `server.sweep_awareness` from time to time to remove old awareness states.
39
+
40
+ `handle_write` gets the id of the write (`id:`). A resend after a reconnect has the same id, so
41
+ the host can skip a write that it applied. `validate_update: ->(bytes, context) { true }` checks
42
+ each doc update before the server stores it; false or an exception refuses it with
43
+ `invalid-message`. When `merge_updates` raises, the sync sends the stored updates one by one.
44
+
45
+ A fanout has `join(session, room) { ... }`, `leave(session, room)` and
46
+ `deliver(room, message, except:)`. `join` calls its block when the session gets the broadcasts of
47
+ the room. The server sends the `ack` of the join in the block, so a new member gets each frame
48
+ after the `ack`. `LocalFanout` calls the block at once. `Dovetail::Rails::CableFanout` calls it
49
+ when ActionCable confirms the stream.
50
+
51
+ A feed log has `append(room, ops)`, `cursor(room)` and `since(room, seq)`. `since` gives the
52
+ entries `[seq, op]` after `seq`, or nil when it does not have each of them. Then the `ack` of the
53
+ join has `reset: true` and no feed follows, so the client loads the room again. The first cursor
54
+ of a room comes from the clock (in microseconds), so a cursor of an earlier process never matches
55
+ a new op. `MemoryFeedLog.new(history: 1000, history_bytes: 1 MiB)` limits each room.
56
+ `MemoryDocPersistence.new(max_doc_bytes: 16 MiB)` refuses a larger document with `too-large`.
57
+
58
+ `authorize` allows only when it gives `true`. Without it, a server with `authenticate` warns at
59
+ the start (`on_warning:`, default `warn`). `authorize_awareness: ->(user, room, state) { state }`
60
+ gives the awareness state to relay, or false to refuse it. Without it, the server sets
61
+ `state["user"]["id"]` to the id of the user. `Dovetail::Protocol.parse` never raises: it refuses
62
+ a string that is not valid UTF-8, counts the length of a name in UTF-16 units and checks the
63
+ range of each field of a date-time, as `parseMessage` does.
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ module Dovetail
7
+ # The notification endpoints as a Rack app (ADR 0012), as the Node server has them:
8
+ #
9
+ # - `GET /?filter=unread|all|archived&before=<next>&limit=<n>`: a page of notifications, the
10
+ # newest first, as a JSON:API document with `meta.next` and `meta.unread`.
11
+ # - `POST /read-all`: marks each unread notification as read.
12
+ #
13
+ # The user comes from the `Authorization: Bearer <token>` header and the `authenticate` hook.
14
+ class NotificationsApp
15
+ JSON_API = { "content-type" => "application/vnd.api+json" }.freeze
16
+ FILTERS = %w[unread all archived].freeze
17
+
18
+ # `server` is a Dovetail::Server, or a proc that gives it.
19
+ def initialize(server)
20
+ @server = server
21
+ end
22
+
23
+ def call(env)
24
+ server = @server.respond_to?(:call) ? @server.call : @server
25
+ header = env["HTTP_AUTHORIZATION"].to_s
26
+ user = server.authenticate(header.start_with?("Bearer ") ? header.delete_prefix("Bearer ") : nil)
27
+ return error(401, "Unauthorized") unless user
28
+
29
+ user_id = (user.respond_to?(:id) ? user.id : user[:id] || user["id"]).to_s
30
+ case [env["REQUEST_METHOD"], env["PATH_INFO"].to_s.delete_suffix("/")]
31
+ in ["GET", ""] then list(server, user_id, URI.decode_www_form(env["QUERY_STRING"].to_s).to_h)
32
+ in ["POST", "/read-all"] then answer(200, { "meta" => { "updated" => server.mark_all_read(user_id) } })
33
+ else error(404, "Not found")
34
+ end
35
+ end
36
+
37
+ private
38
+
39
+ def list(server, user_id, query)
40
+ filter = query.fetch("filter", "all")
41
+ return error(400, "Unknown filter") unless FILTERS.include?(filter)
42
+
43
+ page = server.notifications.list(user_id, filter: filter, before: query["before"],
44
+ limit: Integer(query.fetch("limit", 20), exception: false) || 20)
45
+ answer(200, { "data" => page[:data],
46
+ "meta" => { "next" => page[:next], "unread" => server.notifications.unread_count(user_id) } })
47
+ end
48
+
49
+ def answer(status, body) = [status, JSON_API.dup, [JSON.generate(body)]]
50
+ def error(status, title) = answer(status, { "errors" => [{ "status" => status.to_s, "title" => title }] })
51
+ end
52
+ end
@@ -0,0 +1,357 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Dovetail
6
+ # The wire protocol (docs/protocol.md), as @dovetail-ts/protocol has it. `parse` is the trust
7
+ # boundary: the server calls it on each frame before it uses the frame.
8
+ module Protocol
9
+ ERROR_CODES = %w[invalid-message too-large unsupported-version unauthorized forbidden not-joined
10
+ rate-limited internal].freeze
11
+ CLIENT_TYPES = %w[hello join leave write ping doc-update doc-sync awareness].freeze
12
+ SERVER_TYPES = %w[welcome ack reject error feed pong doc-update doc-sync awareness].freeze
13
+ SUPPORTED_VERSIONS = [1].freeze
14
+ NOTIFICATION_TYPE = "notification"
15
+ DEFAULT_LIMITS = { max_message_bytes: 1024 * 1024, max_name_length: 256, max_ops: 1000, max_depth: 32 }.freeze
16
+
17
+ BASE64 = %r{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z}
18
+ DATE_TIME = /\A\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))\z/
19
+ # The range of each field of DATE_TIME, as `Date.parse` of JavaScript checks it.
20
+ DATE_TIME_RANGES = [1..12, 1..31, 0..24, 0..59, 0..59, 0..23, 0..59].freeze
21
+ # The nesting that JSON.parse allows above `max_depth`: the fields that `json` checks are at
22
+ # most 7 levels below the root (feed, ops, op, document, included, resource, relationships).
23
+ WRAPPER_DEPTH = 8
24
+ USER_ROOM_PREFIX = "user:"
25
+
26
+ # The result of `parse`: a message, or an error with `code`, `path` and `message`.
27
+ Result = Struct.new(:message, :error) do
28
+ def ok? = error.nil?
29
+ end
30
+
31
+ # A check that failed.
32
+ class Failure < StandardError
33
+ attr_reader :code, :path
34
+
35
+ def initialize(path, message, code = "invalid-message")
36
+ super(message)
37
+ @path = path
38
+ @code = code
39
+ end
40
+ end
41
+
42
+ module_function
43
+
44
+ # Checks that `input` (a frame as text, or a parsed hash) is a valid message. It never
45
+ # raises. `from` is the side that sent it: `:client`, `:server` or nil for both.
46
+ def parse(input, from: nil, limits: {})
47
+ checker = Checker.new(DEFAULT_LIMITS.merge(limits))
48
+ value = input.is_a?(String) ? checker.json_text(input) : input
49
+ message = checker.object(value, "")
50
+ types = { client: CLIENT_TYPES, server: SERVER_TYPES }.fetch(from, CLIENT_TYPES | SERVER_TYPES)
51
+ type = message["type"]
52
+ checker.fail("type", "is not a #{from || 'known'} message type") unless types.include?(type)
53
+ checker.public_send("check_#{type.tr('-', '_')}", message)
54
+ Result.new(message, nil)
55
+ rescue Failure => e
56
+ where = e.path.empty? ? "the message" : e.path
57
+ Result.new(nil, { code: e.code, path: e.path, message: "#{where} #{e.message}" })
58
+ rescue StandardError
59
+ # `parse` never raises: an input that a check did not expect is not a valid message.
60
+ Result.new(nil, { code: "invalid-message", path: "", message: "the message is not valid" })
61
+ end
62
+
63
+ # True when the text is an ISO 8601 date-time with each field in range.
64
+ def date_time?(text)
65
+ match = DATE_TIME.match(text) or return false
66
+ match.captures.zip(DATE_TIME_RANGES).all? { |value, range| value.nil? || range.cover?(value.to_i) }
67
+ end
68
+
69
+ def encode(message) = JSON.generate(message)
70
+
71
+ # The highest version in both lists, or nil.
72
+ def negotiate_version(client_versions, server_versions = SUPPORTED_VERSIONS)
73
+ (Array(client_versions) & server_versions).max
74
+ end
75
+
76
+ def user_room(user_id)
77
+ raise ArgumentError, "user_room needs a user id" if user_id.to_s.empty?
78
+
79
+ "#{USER_ROOM_PREFIX}#{user_id}"
80
+ end
81
+
82
+ def user_room?(room) = room.start_with?(USER_ROOM_PREFIX) && room.length > USER_ROOM_PREFIX.length
83
+
84
+ # The checks of one message, with the limits and the path of each field.
85
+ class Checker
86
+ def initialize(limits)
87
+ @limits = limits
88
+ # True in a client write to a per-user room: a notification can be partial there.
89
+ @partial = false
90
+ end
91
+
92
+ def fail(path, message, code = "invalid-message")
93
+ raise Failure.new(path, message, code)
94
+ end
95
+
96
+ def json_text(text)
97
+ max = @limits[:max_message_bytes]
98
+ fail("", "is larger than #{max} bytes", "too-large") if text.bytesize > max
99
+ fail("", "is not valid UTF-8") unless text.valid_encoding?
100
+ JSON.parse(text, max_nesting: @limits[:max_depth] + WRAPPER_DEPTH)
101
+ rescue JSON::NestingError
102
+ fail("", "is nested deeper than #{@limits[:max_depth]}", "too-large")
103
+ rescue JSON::ParserError, EncodingError
104
+ fail("", "is not JSON")
105
+ end
106
+
107
+ def join(path, key)
108
+ return "#{path}[#{key}]" if key.is_a?(Integer)
109
+
110
+ path.empty? ? key : "#{path}.#{key}"
111
+ end
112
+
113
+ def object(value, path)
114
+ fail(path, "must be an object") unless value.is_a?(Hash)
115
+ value
116
+ end
117
+
118
+ def string(value, path)
119
+ fail(path, "must be a string") unless value.is_a?(String)
120
+ valid = value.valid_encoding? && (value.ascii_only? || value.encoding == Encoding::UTF_8)
121
+ fail(path, "must be valid UTF-8") unless valid
122
+ value
123
+ end
124
+
125
+ # A name. Its length is in UTF-16 units, as the length of a JavaScript string.
126
+ def name(value, path)
127
+ text = string(value, path)
128
+ fail(path, "must not be empty") if text.empty?
129
+ if text.encode(Encoding::UTF_16LE).bytesize / 2 > @limits[:max_name_length]
130
+ fail(path, "is longer than #{@limits[:max_name_length]}", "too-large")
131
+ end
132
+ text
133
+ end
134
+
135
+ def optional_name(record, key, path)
136
+ name(record[key], join(path, key)) if record.key?(key)
137
+ end
138
+
139
+ def base64(value, path)
140
+ fail(path, "must be base64") unless BASE64.match?(string(value, path))
141
+ end
142
+
143
+ def integer(value, path)
144
+ fail(path, "must be an integer") unless value.is_a?(Integer)
145
+ value
146
+ end
147
+
148
+ def array(value, path)
149
+ fail(path, "must be an array") unless value.is_a?(Array)
150
+ value
151
+ end
152
+
153
+ # Any JSON value, within `max_depth`.
154
+ def json(value, path, depth = 0)
155
+ case value
156
+ when String then string(value, path)
157
+ when nil, true, false then nil
158
+ when Integer then nil
159
+ when Float then fail(path, "must be a finite number") unless value.finite?
160
+ when Array, Hash
161
+ fail(path, "is nested deeper than #{@limits[:max_depth]}", "too-large") if depth >= @limits[:max_depth]
162
+ if value.is_a?(Array)
163
+ value.each_with_index { |item, i| json(item, join(path, i), depth + 1) }
164
+ else
165
+ value.each { |key, item| json(item, join(path, key.to_s), depth + 1) }
166
+ end
167
+ else fail(path, "must be a JSON value")
168
+ end
169
+ end
170
+
171
+ def json_object(value, path)
172
+ object(value, path)
173
+ json(value, path)
174
+ end
175
+
176
+ def optional_json_object(record, key, path)
177
+ json_object(record[key], join(path, key)) if record.key?(key)
178
+ end
179
+
180
+ def identifier(value, path)
181
+ ref = object(value, path)
182
+ name(ref["type"], join(path, "type"))
183
+ name(ref["id"], join(path, "id"))
184
+ end
185
+
186
+ def resource(value, path)
187
+ resource = object(value, path)
188
+ type = name(resource["type"], join(path, "type"))
189
+ name(resource["id"], join(path, "id"))
190
+ optional_json_object(resource, "attributes", path)
191
+ if resource.key?("relationships")
192
+ object(resource["relationships"], join(path, "relationships")).each do |key, relationship|
193
+ at = join(join(path, "relationships"), key)
194
+ data = object(relationship, at)["data"]
195
+ if data.is_a?(Array)
196
+ data.each_with_index { |ref, i| identifier(ref, join(join(at, "data"), i)) }
197
+ elsif !data.nil?
198
+ identifier(data, join(at, "data"))
199
+ end
200
+ json(relationship, at)
201
+ end
202
+ end
203
+ optional_json_object(resource, "links", path)
204
+ optional_json_object(resource, "meta", path)
205
+ notification(resource, path) if type == NOTIFICATION_TYPE
206
+ end
207
+
208
+ # A partial notification (a client write to the per-user room) can leave out each field.
209
+ def notification(resource, path)
210
+ return if @partial && !resource.key?("attributes")
211
+
212
+ attributes = object(resource["attributes"], "#{path}.attributes")
213
+ name(attributes["verb"], "#{path}.attributes.verb") unless @partial && !attributes.key?("verb")
214
+ { "createdAt" => false, "readAt" => true, "seenAt" => true, "archivedAt" => true }.each do |key, nullable|
215
+ value = attributes[key]
216
+ next if @partial && !attributes.key?(key)
217
+ next if nullable && (value.nil? || (key == "archivedAt" && !attributes.key?(key)))
218
+
219
+ text = string(value, "#{path}.attributes.#{key}")
220
+ fail("#{path}.attributes.#{key}", "must be an ISO 8601 date-time") unless Protocol.date_time?(text)
221
+ end
222
+ return if @partial && !resource.key?("relationships")
223
+
224
+ relationships = object(resource["relationships"], "#{path}.relationships")
225
+ %w[actor target].each do |key|
226
+ relationship = object(relationships[key], "#{path}.relationships.#{key}")
227
+ identifier(relationship["data"], "#{path}.relationships.#{key}.data")
228
+ end
229
+ end
230
+
231
+ def document(value, path)
232
+ document = object(value, path)
233
+ fail(join(path, "data"), "is required") unless document.key?("data")
234
+ data = document["data"]
235
+ if data.is_a?(Array)
236
+ data.each_with_index { |item, i| resource(item, join(join(path, "data"), i)) }
237
+ elsif !data.nil?
238
+ resource(data, join(path, "data"))
239
+ end
240
+ if document.key?("included")
241
+ array(document["included"], join(path, "included")).each_with_index do |item, i|
242
+ resource(item, join(join(path, "included"), i))
243
+ end
244
+ end
245
+ optional_json_object(document, "meta", path)
246
+ end
247
+
248
+ def store_op(value, path)
249
+ op = object(value, path)
250
+ case op["op"]
251
+ when "upsert" then document(op["document"], join(path, "document"))
252
+ when "delete" then identifier(op["ref"], join(path, "ref"))
253
+ else fail(join(path, "op"), "must be 'upsert' or 'delete'")
254
+ end
255
+ end
256
+
257
+ def api_error(value, path)
258
+ error = object(value, path)
259
+ %w[id status code title detail].each { |key| string(error[key], join(path, key)) if error.key?(key) }
260
+ if error.key?("source")
261
+ object(error["source"], join(path, "source")).each do |key, item|
262
+ string(item, join(join(path, "source"), key))
263
+ end
264
+ end
265
+ optional_json_object(error, "meta", path)
266
+ end
267
+
268
+ def check_hello(m)
269
+ array(m["versions"], "versions").each_with_index { |v, i| integer(v, join("versions", i)) }
270
+ string(m["token"], "token") if m.key?("token")
271
+ return unless m.key?("client")
272
+
273
+ client = object(m["client"], "client")
274
+ name(client["name"], "client.name")
275
+ name(client["version"], "client.version")
276
+ end
277
+
278
+ def check_join(m)
279
+ name(m["id"], "id")
280
+ name(m["room"], "room")
281
+ optional_name(m, "since", "")
282
+ end
283
+
284
+ def check_leave(m)
285
+ name(m["id"], "id")
286
+ name(m["room"], "room")
287
+ end
288
+
289
+ def check_write(m)
290
+ name(m["id"], "id")
291
+ @partial = Protocol.user_room?(name(m["room"], "room"))
292
+ store_op(m["op"], "op")
293
+ end
294
+
295
+ def check_ping(m) = name(m["id"], "id")
296
+
297
+ def check_doc_update(m)
298
+ name(m["room"], "room")
299
+ name(m["doc"], "doc")
300
+ base64(m["update"], "update")
301
+ optional_name(m, "origin", "")
302
+ end
303
+
304
+ def check_doc_sync(m)
305
+ name(m["room"], "room")
306
+ name(m["doc"], "doc")
307
+ case m["step"]
308
+ when 1 then base64(m["stateVector"], "stateVector")
309
+ when 2 then base64(m["update"], "update")
310
+ else fail("step", "must be 1 or 2")
311
+ end
312
+ end
313
+
314
+ def check_awareness(m)
315
+ name(m["room"], "room")
316
+ optional_name(m, "clientId", "")
317
+ json_object(m["state"], "state") unless m["state"].nil?
318
+ end
319
+
320
+ def check_welcome(m)
321
+ integer(m["version"], "version")
322
+ name(m["session"], "session")
323
+ name(object(m["user"], "user")["id"], "user.id") if m.key?("user")
324
+ end
325
+
326
+ def check_ack(m)
327
+ name(m["ref"], "ref")
328
+ optional_name(m, "cursor", "")
329
+ fail("reset", "must be a boolean") if m.key?("reset") && ![true, false].include?(m["reset"])
330
+ document(m["document"], "document") if m.key?("document")
331
+ end
332
+
333
+ def check_reject(m)
334
+ name(m["ref"], "ref")
335
+ status = integer(m["status"], "status")
336
+ fail("status", "must be a 4xx status") unless (400..499).cover?(status)
337
+ array(m["errors"], "errors").each_with_index { |e, i| api_error(e, join("errors", i)) }
338
+ end
339
+
340
+ def check_error(m)
341
+ optional_name(m, "ref", "")
342
+ fail("code", "is not a known code") unless ERROR_CODES.include?(m["code"])
343
+ string(m["message"], "message")
344
+ end
345
+
346
+ def check_feed(m)
347
+ name(m["room"], "room")
348
+ name(m["cursor"], "cursor")
349
+ ops = array(m["ops"], "ops")
350
+ fail("ops", "has more than #{@limits[:max_ops]} ops", "too-large") if ops.length > @limits[:max_ops]
351
+ ops.each_with_index { |op, i| store_op(op, join("ops", i)) }
352
+ end
353
+
354
+ def check_pong(m) = name(m["ref"], "ref")
355
+ end
356
+ end
357
+ end
@@ -0,0 +1,499 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "monitor"
5
+ require "securerandom"
6
+ require "time"
7
+
8
+ module Dovetail
9
+ # The members of each room in this process. A Rails app uses `Dovetail::Rails::CableFanout`,
10
+ # so that a broadcast reaches the members in each process.
11
+ class LocalFanout
12
+ def initialize
13
+ @rooms = {}
14
+ @lock = Mutex.new
15
+ end
16
+
17
+ # Adds the session to the room, then calls the block. Another fanout can call the block
18
+ # later, when the session gets the broadcasts of the room. The server sends the ack of the
19
+ # join in the block.
20
+ def join(session, room)
21
+ @lock.synchronize { (@rooms[room] ||= {})[session.id] = session }
22
+ yield
23
+ end
24
+
25
+ def leave(session, room)
26
+ @lock.synchronize do
27
+ members = @rooms[room] or next
28
+ members.delete(session.id)
29
+ @rooms.delete(room) if members.empty?
30
+ end
31
+ end
32
+
33
+ # The rooms with members.
34
+ def size = @lock.synchronize { @rooms.size }
35
+
36
+ # Sends a message to each member of the room, but not to the session `except`.
37
+ def deliver(room, message, except: nil)
38
+ members = @lock.synchronize { @rooms.fetch(room, {}).values }
39
+ members.each { |member| member.send_message(message) unless member.id == except }
40
+ end
41
+ end
42
+
43
+ # The server end of one connection. The sink is the wire: it has `send_text(text)` and
44
+ # `close(code, reason)`.
45
+ class Session
46
+ attr_reader :id, :sink, :rooms
47
+ attr_accessor :user, :version
48
+
49
+ def initialize(server, sink)
50
+ @server = server
51
+ @sink = sink
52
+ @id = "s-#{SecureRandom.uuid}"
53
+ @rooms = Set.new
54
+ # A Monitor, not a Mutex: a frame can close the session (a bad hello) while it holds it.
55
+ @lock = Monitor.new
56
+ @open = true
57
+ end
58
+
59
+ def open? = @open
60
+
61
+ # Gives one frame from the wire. The frames of one session run one at a time.
62
+ def receive(text)
63
+ @lock.synchronize { @server.handle(self, text) if @open }
64
+ end
65
+
66
+ # Tells the session that the wire closed. It waits for the frame in work, so a join that
67
+ # waits for a hook cannot add the closed session to a room after the leave.
68
+ def closed
69
+ @lock.synchronize do
70
+ next unless @open
71
+
72
+ @open = false
73
+ @server.drop(self)
74
+ end
75
+ end
76
+
77
+ def send_message(message)
78
+ @sink.send_text(Protocol.encode(message)) if @open
79
+ end
80
+
81
+ def close(code, reason)
82
+ @sink.close(code, reason)
83
+ closed
84
+ end
85
+ end
86
+
87
+ # A refusal that goes to the client as an `error` message.
88
+ class Refusal < StandardError
89
+ attr_reader :code
90
+
91
+ def initialize(code, message)
92
+ super(message)
93
+ @code = code
94
+ end
95
+ end
96
+
97
+ # The Dovetail server: sessions, rooms, the store feed, the doc relay, awareness and
98
+ # notifications. The same rules as @dovetail-ts/server (docs/protocol.md, ADR 0012).
99
+ #
100
+ # server = Dovetail::Server.new(
101
+ # authenticate: ->(token) { User.find_by_token(token) }, # never called with a blank token
102
+ # authorize: ->(user, room, action) { true },
103
+ # handle_write: ->(write) { { ok: true } } # write: { user:, session:, id:, room:, op: }
104
+ # )
105
+ # session = server.connect(sink)
106
+ # session.receive(frame)
107
+ class Server
108
+ DEFAULT_LIMITS = Protocol::DEFAULT_LIMITS.merge(max_rooms: 100).freeze
109
+
110
+ attr_reader :limits, :notifications
111
+
112
+ def initialize(authenticate: nil, authorize: nil, handle_write: nil, docs: MemoryDocPersistence.new,
113
+ merge_updates: nil, notifications: MemoryNotificationStore.new, limits: {},
114
+ awareness_timeout: 30, clock: -> { Time.now }, fanout: LocalFanout.new,
115
+ feed_log: MemoryFeedLog.new, on_error: nil, on_session_end: nil, allow_anonymous: false,
116
+ validate_update: nil, authorize_awareness: nil, on_warning: ->(message) { warn(message) })
117
+ @validate_update = validate_update
118
+ @authorize_awareness = authorize_awareness
119
+ if authenticate && !authorize
120
+ on_warning.call("dovetail: the server has no authorize hook, so each user can join and write each room.")
121
+ end
122
+ @authenticate = authenticate
123
+ @allow_anonymous = allow_anonymous
124
+ @authorize = authorize
125
+ @handle_write = handle_write
126
+ @docs = docs
127
+ @merge_updates = merge_updates
128
+ @notifications = notifications
129
+ @limits = DEFAULT_LIMITS.merge(limits)
130
+ @awareness_timeout = awareness_timeout
131
+ @clock = clock
132
+ @fanout = fanout
133
+ @feed_log = feed_log
134
+ @on_error = on_error
135
+ @on_session_end = on_session_end
136
+ @awareness = {}
137
+ @lock = Mutex.new
138
+ end
139
+
140
+ # Serves one connection.
141
+ def connect(sink) = Session.new(self, sink)
142
+
143
+ # The user of a token. Nil without the hook, for a token that is not valid, or on an error.
144
+ # A missing or blank token gives nil before the hook, unless `allow_anonymous`.
145
+ def authenticate(token)
146
+ blank = token.nil? || token.strip.empty?
147
+ return nil if blank && !@allow_anonymous
148
+
149
+ @authenticate&.call(blank ? nil : token)
150
+ rescue StandardError => e
151
+ @on_error&.call(e)
152
+ nil
153
+ end
154
+
155
+ # Sends a JSON:API document to the store feed of a room. Gives the cursor after it.
156
+ def publish(room, document)
157
+ if !Protocol.user_room?(room) && notification?(document)
158
+ raise ArgumentError, "dovetail: a notification goes only to a per-user room"
159
+ end
160
+
161
+ feed(room, [{ "op" => "upsert", "document" => document }])
162
+ end
163
+
164
+ # Sends the delete of one record to the store feed of a room. Gives the cursor after it.
165
+ def remove(room, ref) = feed(room, [{ "op" => "delete", "ref" => ref }])
166
+
167
+ # Makes a notification for a user, stores it and sends it to the per-user room (ADR 0009).
168
+ def notify(user_id, verb:, actor:, target:, id: nil, attributes: {})
169
+ notification = {
170
+ "type" => Protocol::NOTIFICATION_TYPE,
171
+ "id" => id || SecureRandom.uuid,
172
+ "attributes" => attributes.transform_keys(&:to_s).merge(
173
+ "verb" => verb, "createdAt" => now, "readAt" => nil, "seenAt" => nil, "archivedAt" => nil
174
+ ),
175
+ "relationships" => { "actor" => { "data" => actor }, "target" => { "data" => target } }
176
+ }
177
+ room = Protocol.user_room(user_id.to_s)
178
+ check(room, [{ "op" => "upsert", "document" => { "data" => notification } }])
179
+ @notifications.add(user_id.to_s, notification)
180
+ publish(room, { "data" => notification })
181
+ notification
182
+ end
183
+
184
+ def mark_read(user_id, id) = change(user_id, id, "readAt" => now)
185
+ def archive(user_id, id) = change(user_id, id, "archivedAt" => now)
186
+
187
+ # Marks each unread notification as read. Gives the count that changed.
188
+ def mark_all_read(user_id)
189
+ changed = @notifications.mark_all_read(user_id.to_s, now)
190
+ ops = changed.map { |n| { "op" => "upsert", "document" => { "data" => n } } }
191
+ ops.each_slice(@limits[:max_ops]) { |slice| feed(Protocol.user_room(user_id.to_s), slice) }
192
+ changed.size
193
+ end
194
+
195
+ # Removes each awareness state that is older than the timeout. Call it from time to time.
196
+ def sweep_awareness
197
+ limit = @clock.call - @awareness_timeout
198
+ stale = @lock.synchronize do
199
+ @awareness.flat_map { |room, states| states.select { |_, (_, at)| at < limit }.map { |id, _| [room, id] } }
200
+ end
201
+ stale.each { |room, id| clear_awareness(id, room) }
202
+ end
203
+
204
+ # The rooms with awareness states. @api private
205
+ def awareness_rooms = @lock.synchronize { @awareness.size }
206
+
207
+ # @api private
208
+ def handle(session, text)
209
+ message = {}
210
+ begin
211
+ result = Protocol.parse(text, from: :client, limits: @limits.slice(*Protocol::DEFAULT_LIMITS.keys))
212
+ unless result.ok?
213
+ return session.send_message("type" => "error", "code" => result.error[:code],
214
+ "message" => result.error[:message][0, 200])
215
+ end
216
+
217
+ message = result.message
218
+ dispatch(session, message)
219
+ rescue Refusal => e
220
+ session.send_message(error(message, e.code, e.message))
221
+ rescue StandardError => e
222
+ @on_error&.call(e)
223
+ session.send_message(error(message, "internal", "Internal error."))
224
+ end
225
+ end
226
+
227
+ # @api private
228
+ def drop(session)
229
+ rooms = session.rooms.to_a
230
+ rooms.each { |room| leave(session, room) }
231
+ begin
232
+ @on_session_end&.call({ id: session.id, user: session.user, rooms: rooms })
233
+ rescue StandardError => e
234
+ @on_error&.call(e)
235
+ end
236
+ end
237
+
238
+ private
239
+
240
+ def now = @clock.call.utc.iso8601(3)
241
+
242
+ # True when the document has a notification resource, in `data` or in `included`.
243
+ def notification?(document)
244
+ [document["data"], document["included"]].flatten(1).any? do |resource|
245
+ resource.is_a?(Hash) && resource["type"] == Protocol::NOTIFICATION_TYPE
246
+ end
247
+ end
248
+
249
+ def user_id(user)
250
+ return nil if user.nil?
251
+
252
+ (user.respond_to?(:id) ? user.id : user[:id] || user["id"]).to_s
253
+ end
254
+
255
+ def error(message, code, text)
256
+ { "type" => "error", "code" => code, "message" => text }.tap { |e| e["ref"] = message["id"] if message.key?("id") }
257
+ end
258
+
259
+ def change(user_id, id, changes)
260
+ changed = @notifications.update(user_id.to_s, id, changes)
261
+ publish(Protocol.user_room(user_id.to_s), { "data" => changed }) if changed
262
+ changed
263
+ end
264
+
265
+ def check(room, ops)
266
+ result = Protocol.parse({ "type" => "feed", "room" => room, "cursor" => "c0", "ops" => ops }, from: :server)
267
+ raise ArgumentError, "dovetail: #{result.error[:message]}" unless result.ok?
268
+ end
269
+
270
+ def feed(room, ops, except: nil)
271
+ check(room, ops)
272
+ cursor = @feed_log.append(room, ops)
273
+ @fanout.deliver(room, { "type" => "feed", "room" => room, "cursor" => cursor, "ops" => ops }, except: except)
274
+ cursor
275
+ end
276
+
277
+ def allowed?(user, room, action)
278
+ return false if Protocol.user_room?(room) && (user.nil? || room != Protocol.user_room(user_id(user)))
279
+
280
+ @authorize.nil? || @authorize.call(user, room, action) == true
281
+ end
282
+
283
+ def joined!(session, room)
284
+ raise Refusal.new("not-joined", "Join the room first.") unless session.rooms.include?(room)
285
+ end
286
+
287
+ # A write, a doc update and a step 2 change the room, so each one needs the write right.
288
+ def writable!(session, room)
289
+ joined!(session, room)
290
+ raise Refusal.new("forbidden", "You cannot write to this room.") unless allowed?(session.user, room, "write")
291
+ end
292
+
293
+ def dispatch(session, message)
294
+ return hello(session, message) if message["type"] == "hello"
295
+ raise Refusal.new("invalid-message", "Send hello first.") if session.version.nil?
296
+
297
+ case message["type"]
298
+ when "ping" then session.send_message("type" => "pong", "ref" => message["id"])
299
+ when "join" then join(session, message)
300
+ when "leave"
301
+ leave(session, message["room"])
302
+ session.send_message("type" => "ack", "ref" => message["id"])
303
+ when "write" then write(session, message)
304
+ when "doc-update"
305
+ store_update(session, message["room"], message["doc"], message["update"])
306
+ when "doc-sync"
307
+ if message["step"] == 2
308
+ store_update(session, message["room"], message["doc"], message["update"])
309
+ else
310
+ joined!(session, message["room"])
311
+ sync(session, message["room"], message["doc"])
312
+ end
313
+ when "awareness"
314
+ joined!(session, message["room"])
315
+ state = message["state"]
316
+ awareness(session, message["room"], state.nil? ? nil : check_awareness(session, message["room"], state))
317
+ end
318
+ end
319
+
320
+ def hello(session, message)
321
+ raise Refusal.new("invalid-message", "Send hello once.") unless session.version.nil?
322
+
323
+ version = Protocol.negotiate_version(message["versions"])
324
+ unless version
325
+ session.send_message("type" => "error", "code" => "unsupported-version",
326
+ "message" => "This server speaks the versions #{Protocol::SUPPORTED_VERSIONS.join(', ')}.")
327
+ return session.close(1002, "unsupported version")
328
+ end
329
+ if @authenticate
330
+ user = authenticate(message["token"])
331
+ unless user
332
+ session.send_message("type" => "error", "code" => "unauthorized", "message" => "The token is not valid.")
333
+ return session.close(1008, "unauthorized")
334
+ end
335
+ session.user = user
336
+ end
337
+ session.version = version
338
+ welcome = { "type" => "welcome", "version" => version, "session" => session.id }
339
+ welcome["user"] = { "id" => user_id(session.user) } if session.user
340
+ session.send_message(welcome)
341
+ end
342
+
343
+ def join(session, message)
344
+ room = message["room"]
345
+ if !session.rooms.include?(room) && session.rooms.size >= @limits[:max_rooms]
346
+ raise Refusal.new("rate-limited", "A connection can join #{@limits[:max_rooms]} rooms.")
347
+ end
348
+ raise Refusal.new("forbidden", "You cannot join this room.") unless allowed?(session.user, room, "join")
349
+
350
+ session.rooms << room
351
+ # The ack goes out only when the session gets the broadcasts of the room, so the member
352
+ # gets each frame after the ack.
353
+ @fanout.join(session, room) { joined(session, room, message) }
354
+ end
355
+
356
+ def joined(session, room, message)
357
+ ack = { "type" => "ack", "ref" => message["id"], "cursor" => @feed_log.cursor(room) }
358
+ since = message["since"]
359
+ entries = @feed_log.since(room, since[1..].to_i) if since&.match?(/\Ac\d+\z/)
360
+ # The log cannot give each op after `since`: the client must load the room again (R11).
361
+ ack["reset"] = true if since && entries.nil?
362
+ session.send_message(ack)
363
+ return unless entries
364
+
365
+ entries.each_slice(@limits[:max_ops]) do |chunk|
366
+ session.send_message("type" => "feed", "room" => room, "cursor" => "c#{chunk.last[0]}",
367
+ "ops" => chunk.map(&:last))
368
+ end
369
+ end
370
+
371
+ def leave(session, room)
372
+ clear_awareness(session.id, room)
373
+ @fanout.leave(session, room)
374
+ session.rooms.delete(room)
375
+ end
376
+
377
+ def write(session, message)
378
+ room = message["room"]
379
+ writable!(session, room)
380
+ return notification_write(session, message) if Protocol.user_room?(room)
381
+ if message["op"]["op"] == "upsert" && notification?(message["op"]["document"])
382
+ return reject(session, message, 403, "A notification goes only to a per-user room.")
383
+ end
384
+
385
+ result = @handle_write&.call(user: session.user, session: session.id, id: message["id"], room: room,
386
+ op: message["op"]) || { ok: true }
387
+ unless result[:ok]
388
+ return session.send_message("type" => "reject", "ref" => message["id"], "status" => result[:status],
389
+ "errors" => result[:errors])
390
+ end
391
+
392
+ document = result[:document]
393
+ op = document ? { "op" => "upsert", "document" => document } : message["op"]
394
+ ack = { "type" => "ack", "ref" => message["id"], "cursor" => feed(room, [op], except: session.id) }
395
+ ack["document"] = document if document
396
+ session.send_message(ack)
397
+ end
398
+
399
+ # A write to the own per-user room changes the read, seen and archived times only.
400
+ def notification_write(session, message)
401
+ op = message["op"]
402
+ data = op["op"] == "upsert" ? op["document"]["data"] : nil
403
+ unless data.is_a?(Hash) && data["type"] == Protocol::NOTIFICATION_TYPE
404
+ return reject(session, message, 422, "A per-user room takes only notification upserts.")
405
+ end
406
+
407
+ # A time goes from nil to a value only once. So a queued write with old values does not
408
+ # undo a newer change (for example, a mark read with `archivedAt: nil` after an archive).
409
+ stored = @notifications.get(user_id(session.user), data["id"])
410
+ return reject(session, message, 404, "Not found") unless stored
411
+
412
+ changes = (data["attributes"] || {}).slice("readAt", "seenAt", "archivedAt")
413
+ .select { |key, value| value.is_a?(String) && stored["attributes"][key].nil? }
414
+ changed = @notifications.update(user_id(session.user), data["id"], changes)
415
+ return reject(session, message, 404, "Not found") unless changed
416
+
417
+ document = { "data" => changed }
418
+ cursor = feed(message["room"], [{ "op" => "upsert", "document" => document }], except: session.id)
419
+ session.send_message("type" => "ack", "ref" => message["id"], "cursor" => cursor, "document" => document)
420
+ end
421
+
422
+ def reject(session, message, status, title)
423
+ session.send_message("type" => "reject", "ref" => message["id"], "status" => status,
424
+ "errors" => [{ "status" => status.to_s, "title" => title }])
425
+ end
426
+
427
+ def store_update(session, room, doc, update)
428
+ writable!(session, room)
429
+ if @validate_update && !valid_update?(session, room, doc, update)
430
+ raise Refusal.new("invalid-message", "The update is not valid.")
431
+ end
432
+
433
+ begin
434
+ @docs.append(room, doc, update)
435
+ rescue TooLarge => e
436
+ raise Refusal.new("too-large", e.message)
437
+ end
438
+ @fanout.deliver(room, { "type" => "doc-update", "room" => room, "doc" => doc, "update" => update,
439
+ "origin" => session.id }, except: session.id)
440
+ end
441
+
442
+ def valid_update?(session, room, doc, update)
443
+ @validate_update.call(update.unpack1("m"), { user: session.user, session: session.id, room: room, doc: doc }) == true
444
+ rescue StandardError => e
445
+ @on_error&.call(e)
446
+ false
447
+ end
448
+
449
+ def sync(session, room, doc)
450
+ updates = @docs.load(room, doc)
451
+ if updates.empty?
452
+ updates = [""]
453
+ elsif updates.size > 1 && @merge_updates
454
+ begin
455
+ updates = [[@merge_updates.call(updates.map { |u| u.unpack1("m") })].pack("m0")]
456
+ rescue StandardError => e
457
+ # One bad stored update must not make the doc unloadable: send them one by one.
458
+ @on_error&.call(e)
459
+ end
460
+ end
461
+ updates.each do |update|
462
+ session.send_message("type" => "doc-sync", "room" => room, "doc" => doc, "step" => 2, "update" => update)
463
+ end
464
+ end
465
+
466
+ # The state to relay: the one of `authorize_awareness`, or the state with the user id.
467
+ def check_awareness(session, room, state)
468
+ if @authorize_awareness
469
+ checked = @authorize_awareness.call(session.user, room, state)
470
+ raise Refusal.new("forbidden", "You cannot send this awareness state.") unless checked.is_a?(Hash)
471
+
472
+ return checked
473
+ end
474
+ return state unless session.user && state["user"].is_a?(Hash)
475
+
476
+ # The name and the other fields are client data. Only the id comes from the server.
477
+ state.merge("user" => state["user"].merge("id" => user_id(session.user)))
478
+ end
479
+
480
+ def awareness(session, room, state)
481
+ return clear_awareness(session.id, room) if state.nil?
482
+
483
+ @lock.synchronize { (@awareness[room] ||= {})[session.id] = [state, @clock.call] }
484
+ @fanout.deliver(room, { "type" => "awareness", "room" => room, "clientId" => session.id, "state" => state },
485
+ except: session.id)
486
+ end
487
+
488
+ def clear_awareness(session_id, room)
489
+ had = @lock.synchronize do
490
+ states = @awareness[room]
491
+ states&.delete(session_id).tap { @awareness.delete(room) if states&.empty? }
492
+ end
493
+ return unless had
494
+
495
+ @fanout.deliver(room, { "type" => "awareness", "room" => room, "clientId" => session_id, "state" => nil },
496
+ except: session_id)
497
+ end
498
+ end
499
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dovetail
4
+ # A store refuses a change over its size limit. The server answers it with `too-large`.
5
+ class TooLarge < StandardError; end
6
+
7
+ # The stored CRDT updates of each document, as base64. The server does not read them. This
8
+ # store is for development and tests only: a host gives its own store (a database) to keep the
9
+ # updates after a restart and to share them between processes. `max_doc_bytes` limits each
10
+ # document (default 16 MiB of base64).
11
+ class MemoryDocPersistence
12
+ def initialize(max_doc_bytes: 16 * 1024 * 1024)
13
+ @max_doc_bytes = max_doc_bytes
14
+ @updates = {}
15
+ @lock = Mutex.new
16
+ end
17
+
18
+ def append(room, doc, update)
19
+ @lock.synchronize do
20
+ entry = (@updates[[room, doc]] ||= { list: [], bytes: 0 })
21
+ raise TooLarge, "The document is larger than #{@max_doc_bytes} bytes." if entry[:bytes] + update.bytesize > @max_doc_bytes
22
+
23
+ entry[:list] << update
24
+ entry[:bytes] += update.bytesize
25
+ end
26
+ end
27
+
28
+ def load(room, doc) = @lock.synchronize { @updates.fetch([room, doc], { list: [] })[:list].dup }
29
+ end
30
+
31
+ # The store feed of each room: the ops after a cursor, for a join with `since`. The cursors
32
+ # are `c<n>`. The first cursor of a room comes from the clock (in microseconds), so it is above
33
+ # each cursor of an earlier process (R11). This log is in memory, for development and tests: a
34
+ # Rails app uses `Dovetail::Rails::CacheFeedLog`.
35
+ class MemoryFeedLog
36
+ EMPTY = { seq: 0, base: 0, floor: 0, log: [].freeze, bytes: 0 }.freeze
37
+
38
+ def initialize(history: 1000, history_bytes: 1024 * 1024, clock: -> { Time.now })
39
+ @history = history
40
+ @history_bytes = history_bytes
41
+ @clock = clock
42
+ @rooms = {}
43
+ @highest = 0
44
+ @lock = Mutex.new
45
+ end
46
+
47
+ # Adds ops, and gives the cursor after them.
48
+ def append(room, ops)
49
+ @lock.synchronize do
50
+ entry = (@rooms[room] ||= EMPTY.merge(log: []))
51
+ entry[:seq] = entry[:base] = entry[:floor] = [(@clock.call.to_r * 1_000_000).floor, @highest].max if entry[:seq].zero?
52
+ ops.each do |op|
53
+ bytes = JSON.generate(op).bytesize
54
+ entry[:log] << [entry[:seq] += 1, op, bytes]
55
+ entry[:bytes] += bytes
56
+ end
57
+ @highest = [@highest, entry[:seq]].max
58
+ trim(entry)
59
+ "c#{entry[:seq]}"
60
+ end
61
+ end
62
+
63
+ def cursor(room) = @lock.synchronize { "c#{@rooms.fetch(room, EMPTY)[:seq]}" }
64
+
65
+ # The entries `[seq, op]` after `seq`, or nil when the log does not have each of them (the
66
+ # cursor is older than the log, or comes from another process). Then the join gets `reset`.
67
+ def since(room, seq)
68
+ @lock.synchronize do
69
+ entry = @rooms.fetch(room, EMPTY)
70
+ next nil if seq > entry[:seq]
71
+ next nil unless seq >= entry[:floor] || (seq.zero? && entry[:floor] == entry[:base])
72
+
73
+ entry[:log].select { |at, _| at > seq }.map { |at, op, _| [at, op] }
74
+ end
75
+ end
76
+
77
+ # The rooms in the log.
78
+ def size = @lock.synchronize { @rooms.size }
79
+
80
+ private
81
+
82
+ def trim(entry)
83
+ while entry[:log].size > @history || (entry[:log].any? && entry[:bytes] > @history_bytes)
84
+ seq, _, bytes = entry[:log].shift
85
+ entry[:floor] = seq
86
+ entry[:bytes] -= bytes
87
+ end
88
+ end
89
+ end
90
+
91
+ # The notifications of each user (ADR 0009), in memory, for development and tests. The
92
+ # resources are JSON:API hashes with string keys. A Rails app uses
93
+ # `Dovetail::Rails::RecordNotificationStore`. A read does not add a user.
94
+ class MemoryNotificationStore
95
+ FILTERS = {
96
+ "all" => ->(n) { n["attributes"]["archivedAt"].nil? },
97
+ "unread" => ->(n) { n["attributes"]["archivedAt"].nil? && n["attributes"]["readAt"].nil? },
98
+ "archived" => ->(n) { !n["attributes"]["archivedAt"].nil? }
99
+ }.freeze
100
+
101
+ def initialize
102
+ @users = {}
103
+ @lock = Mutex.new
104
+ end
105
+
106
+ def add(user_id, notification) = @lock.synchronize { (@users[user_id] ||= []) << copy(notification) }
107
+
108
+ # The users that have notifications.
109
+ def users = @lock.synchronize { @users.size }
110
+
111
+ def get(user_id, id)
112
+ @lock.synchronize { (found = find(user_id, id)) && copy(found) }
113
+ end
114
+
115
+ # A page of notifications, the newest first: `{ data:, next: }`. `next` is the `before` of
116
+ # the older page, or nil.
117
+ def list(user_id, filter: "all", before: nil, limit: 20)
118
+ limit = limit.to_i.clamp(1, 100)
119
+ @lock.synchronize do
120
+ items = of(user_id).reverse.select(&FILTERS.fetch(filter))
121
+ if before
122
+ at = items.index { |n| n["id"] == before }
123
+ items = at ? items.drop(at + 1) : []
124
+ end
125
+ data = items.first(limit).map { |n| copy(n) }
126
+ { data: data, next: items.size > limit ? data.last["id"] : nil }
127
+ end
128
+ end
129
+
130
+ # Changes `readAt`, `seenAt` or `archivedAt`. Nil when the user has no such notification.
131
+ def update(user_id, id, changes)
132
+ @lock.synchronize do
133
+ found = find(user_id, id) or next nil
134
+ found["attributes"].merge!(changes.slice("readAt", "seenAt", "archivedAt"))
135
+ copy(found)
136
+ end
137
+ end
138
+
139
+ # Sets `readAt` on each unread notification, and gives the ones that changed.
140
+ def mark_all_read(user_id, at)
141
+ @lock.synchronize do
142
+ changed = of(user_id).select(&FILTERS["unread"])
143
+ changed.each { |n| n["attributes"]["readAt"] = at }
144
+ changed.map { |n| copy(n) }
145
+ end
146
+ end
147
+
148
+ def unread_count(user_id) = @lock.synchronize { of(user_id).count(&FILTERS["unread"]) }
149
+
150
+ private
151
+
152
+ def of(user_id) = @users.fetch(user_id, [])
153
+ def find(user_id, id) = of(user_id).find { |n| n["id"] == id }
154
+ def copy(notification) = Marshal.load(Marshal.dump(notification))
155
+ end
156
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dovetail
4
+ VERSION = "1.0.0"
5
+ end
data/lib/dovetail.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "dovetail/version"
4
+ require_relative "dovetail/protocol"
5
+ require_relative "dovetail/stores"
6
+ require_relative "dovetail/server"
7
+ require_relative "dovetail/notifications_app"
8
+
9
+ # Real-time and offline sync. See https://joegaudet.com/dovetail/.
10
+ module Dovetail
11
+ # The newest version of the wire protocol (docs/protocol.md) that this gem speaks.
12
+ PROTOCOL_VERSION = 1
13
+ end
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dovetail
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Joe Gaudet
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ email:
13
+ - joe@joegaudet.com
14
+ executables: []
15
+ extensions: []
16
+ extra_rdoc_files: []
17
+ files:
18
+ - LICENSE
19
+ - README.md
20
+ - lib/dovetail.rb
21
+ - lib/dovetail/notifications_app.rb
22
+ - lib/dovetail/protocol.rb
23
+ - lib/dovetail/server.rb
24
+ - lib/dovetail/stores.rb
25
+ - lib/dovetail/version.rb
26
+ homepage: "https://joegaudet.com/dovetail/"
27
+ licenses:
28
+ - MIT
29
+ metadata:
30
+ source_code_uri: "https://github.com/joegaudet/dovetail/tree/main/ruby/dovetail"
31
+ bug_tracker_uri: "https://github.com/joegaudet/dovetail/issues"
32
+ rubygems_mfa_required: "true"
33
+ rdoc_options: []
34
+ require_paths:
35
+ - lib
36
+ required_ruby_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ -
39
+ - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: "3.3"
42
+ required_rubygems_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ -
45
+ - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: "0"
48
+ requirements: []
49
+ rubygems_version: 4.1.1
50
+ specification_version: 4
51
+ summary: "Real-time and offline sync for Ruby: the Dovetail protocol, rooms and the store feed for Rack."
52
+ test_files: []