dovetail-rails 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 +7 -0
- data/LICENSE +21 -0
- data/README.md +69 -0
- data/lib/dovetail/rails/cable_fanout.rb +18 -0
- data/lib/dovetail/rails/cache_feed_log.rb +62 -0
- data/lib/dovetail/rails/channel.rb +91 -0
- data/lib/dovetail/rails/configuration.rb +23 -0
- data/lib/dovetail/rails/model.rb +79 -0
- data/lib/dovetail/rails/record_notification_store.rb +69 -0
- data/lib/dovetail/rails.rb +75 -0
- data/lib/dovetail-rails.rb +3 -0
- data/lib/generators/dovetail/install/install_generator.rb +26 -0
- data/lib/generators/dovetail/install/templates/create_dovetail_notifications.rb.tt +16 -0
- data/lib/generators/dovetail/install/templates/initializer.rb.tt +16 -0
- metadata +121 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: a4481bd2e5d1e60646c391d5585689f4d1b4aeb24ef00d47eea2c0224db1bb88
|
|
4
|
+
data.tar.gz: 6db0542bd76790d8eefb7876d691de6a11a8b747126dad546f48d40ee0698169
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: d2924e64c16254abf1691a843d7653c1ac338bd42690921cedf493d839aa62b71d6160f006a2c907f84348eb9701bd80c0ef1b33200f63c73abb37bfa66d6679
|
|
7
|
+
data.tar.gz: d3e63c8580f6cdff74fda06d7a49b60c982ebd04890629b026c4962d86b605534deb2e1813dc42fe81c2c88551f15d260aaa35a3a8789e921d2f2c3bb26ca06c
|
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,69 @@
|
|
|
1
|
+
# dovetail-rails
|
|
2
|
+
|
|
3
|
+
The Rails gem of [Dovetail](https://joegaudet.com/dovetail/): an ActionCable channel, model
|
|
4
|
+
broadcast, notifications, the auth hooks and a generator. Not released yet. It passes
|
|
5
|
+
`@dovetail-ts/conformance` over a real ActionCable server.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bin/rails generate dovetail:install # the initializer and the notifications table
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
# config/initializers/dovetail.rb
|
|
13
|
+
Dovetail::Rails.configure do |config|
|
|
14
|
+
# The token is "<user id>.<secret>". The table keeps only the SHA-256 digest of the secret.
|
|
15
|
+
config.authenticate = lambda do |token|
|
|
16
|
+
id, secret = token.to_s.split(".", 2)
|
|
17
|
+
next nil if id.blank? || secret.blank?
|
|
18
|
+
|
|
19
|
+
user = User.find_by(id: id)
|
|
20
|
+
digest = Digest::SHA256.hexdigest(secret)
|
|
21
|
+
user if user&.dovetail_token_digest &&
|
|
22
|
+
ActiveSupport::SecurityUtils.secure_compare(user.dovetail_token_digest, digest)
|
|
23
|
+
end
|
|
24
|
+
config.authorize = ->(user, room, action) { user.can?(action, room) }
|
|
25
|
+
config.notifications = Dovetail::Rails::RecordNotificationStore.new
|
|
26
|
+
config.on_session_end = ->(info) { Rails.logger.info("left #{info[:rooms]}") } # when a channel unsubscribes
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# config/routes.rb
|
|
30
|
+
mount Dovetail::Rails.notifications_app, at: "/dovetail/notifications"
|
|
31
|
+
|
|
32
|
+
class Note < ApplicationRecord
|
|
33
|
+
broadcasts_dovetail to: ->(note) { "note:#{note.id}" }, attributes: %i[title body updated_at]
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
class Comment < ApplicationRecord
|
|
37
|
+
notifies_dovetail to: :recipient, verb: "commented", actor: :author, target: :note
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
Dovetail::Rails.notify(user, verb: "mentioned", actor: author, target: note)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Never give a missing or blank token to a database query: `User.find_by(dovetail_token: nil)`
|
|
44
|
+
finds the first user with no token. The server refuses a missing or blank token before it calls
|
|
45
|
+
`authenticate`, unless `config.allow_anonymous = true`. Keep the check in the hook too.
|
|
46
|
+
|
|
47
|
+
`broadcasts_dovetail` needs `attributes:` (an allowlist) or `document:`. It never sends each
|
|
48
|
+
column of the record.
|
|
49
|
+
|
|
50
|
+
The client uses `@dovetail-ts/transport-cable`, which subscribes to `Dovetail::Channel`.
|
|
51
|
+
|
|
52
|
+
- A broadcast goes through ActionCable, so each process gets it (`CableFanout`).
|
|
53
|
+
- The feed cursors come from `Rails.cache` (`CacheFeedLog`). The cache must have an atomic
|
|
54
|
+
`increment`.
|
|
55
|
+
- When the cache does not have each op after the `since` of a join (an entry expired, the
|
|
56
|
+
cursor is older than the history, or the cache was cleared), the `ack` has `reset: true` and
|
|
57
|
+
the client loads the room again.
|
|
58
|
+
- The process runs one sweep of the old awareness states each 5 s, when the server starts.
|
|
59
|
+
- ActionCable logs the data of each action. The channel hides the token of a `hello` frame in
|
|
60
|
+
that log line (`"token":"[FILTERED]"`).
|
|
61
|
+
- ActionCable runs the actions of a connection on a worker pool, so two frames can arrive in a
|
|
62
|
+
different order. `@dovetail-ts/transport-cable` numbers each frame (`seq`), and the channel
|
|
63
|
+
runs the frames of a connection in that order. A frame with no number runs at once.
|
|
64
|
+
- The `ack` of a join goes out only when the stream of the room is live (the pubsub adapter
|
|
65
|
+
confirms the subscription). Thus a new member gets each broadcast after the join, with each
|
|
66
|
+
adapter. The order of a broadcast and the `ack` is fixed only with a worker pool of 1 (see
|
|
67
|
+
above).
|
|
68
|
+
- The awareness states and the default doc store are in the memory of each process. Give
|
|
69
|
+
`config.docs` a shared store when you run more than one cable process.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Dovetail
|
|
4
|
+
module Rails
|
|
5
|
+
# The members of a room through ActionCable: a session streams `dovetail:<room>`, and a
|
|
6
|
+
# broadcast reaches each member in each process. The channel skips the frames of its own
|
|
7
|
+
# session (`except`).
|
|
8
|
+
class CableFanout
|
|
9
|
+
# Calls the block when the stream of the room is live (ActionCable subscribes later).
|
|
10
|
+
def join(session, room, &ready) = session.sink.stream_room(room, &ready)
|
|
11
|
+
def leave(session, room) = session.sink.stop_room(room)
|
|
12
|
+
|
|
13
|
+
def deliver(room, message, except: nil)
|
|
14
|
+
ActionCable.server.broadcast("dovetail:#{room}", { "frame" => Protocol.encode(message), "except" => except })
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Dovetail
|
|
4
|
+
module Rails
|
|
5
|
+
# The store feed of each room in a Rails cache, so the web processes and the cable processes
|
|
6
|
+
# give the same cursors. The cache must have an atomic `increment` (Redis, Memcache, Solid
|
|
7
|
+
# Cache). The cursors are `c<n>`. The first cursor of a room comes from the clock (in
|
|
8
|
+
# microseconds), so a cleared cache never gives an old cursor again (R11).
|
|
9
|
+
class CacheFeedLog
|
|
10
|
+
def initialize(cache, history: 1000, expires_in: 86_400, clock: -> { Time.now })
|
|
11
|
+
@cache = cache
|
|
12
|
+
@history = history
|
|
13
|
+
@expires_in = expires_in
|
|
14
|
+
@clock = clock
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Adds ops, and gives the cursor after them.
|
|
18
|
+
def append(room, ops)
|
|
19
|
+
start(room) if last(room).zero?
|
|
20
|
+
seq = 0
|
|
21
|
+
ops.each do |op|
|
|
22
|
+
seq = @cache.increment(key(room, "seq"), 1)
|
|
23
|
+
@cache.write(key(room, seq), op, expires_in: @expires_in)
|
|
24
|
+
end
|
|
25
|
+
"c#{seq}"
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def cursor(room) = "c#{last(room)}"
|
|
29
|
+
|
|
30
|
+
# The entries `[seq, op]` after `seq`, or nil when the cache does not have each of them:
|
|
31
|
+
# the cursor is older than the history, an entry expired, or the cursor comes from before
|
|
32
|
+
# a clear of the cache. Then the join gets `reset`.
|
|
33
|
+
def since(room, seq)
|
|
34
|
+
upto = last(room)
|
|
35
|
+
base = @cache.read(key(room, "base"), raw: true).to_i
|
|
36
|
+
return nil if seq > upto || (seq < base && !seq.zero?)
|
|
37
|
+
|
|
38
|
+
from = [seq, base].max + 1
|
|
39
|
+
return nil if upto - from + 1 > @history
|
|
40
|
+
return [] if from > upto
|
|
41
|
+
|
|
42
|
+
keys = (from..upto).to_h { |at| [key(room, at), at] }
|
|
43
|
+
found = @cache.read_multi(*keys.keys)
|
|
44
|
+
return nil if found.size < keys.size
|
|
45
|
+
|
|
46
|
+
found.map { |name, op| [keys[name], op] }.sort_by(&:first)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
private
|
|
50
|
+
|
|
51
|
+
# The first op of a room (or the first after a clear of the cache) starts at the clock.
|
|
52
|
+
def start(room)
|
|
53
|
+
base = (@clock.call.to_r * 1_000_000).floor
|
|
54
|
+
@cache.write(key(room, "base"), base, raw: true, unless_exist: true)
|
|
55
|
+
@cache.write(key(room, "seq"), base, raw: true, unless_exist: true)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def last(room) = @cache.read(key(room, "seq"), raw: true).to_i
|
|
59
|
+
def key(room, part) = "dovetail:feed:#{room}:#{part}"
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Dovetail
|
|
4
|
+
# The ActionCable channel of Dovetail. Each frame of the protocol is the string field `frame`
|
|
5
|
+
# of the cable data, both ways (ADR 0012). `receive` is its only action.
|
|
6
|
+
#
|
|
7
|
+
# ActionCable runs the actions of a connection on a worker pool, so two frames can arrive in a
|
|
8
|
+
# different order. The client numbers each frame (`seq`, from 1), and the channel runs them in
|
|
9
|
+
# that order (R6). A frame with no number runs at once.
|
|
10
|
+
class Channel < ActionCable::Channel::Base
|
|
11
|
+
# The frames that can wait for a missing number. Over it, the session ends.
|
|
12
|
+
MAX_WAITING = 256
|
|
13
|
+
|
|
14
|
+
# The wire of the session. It is not the channel, because each public method of a channel
|
|
15
|
+
# is an action that a client can call.
|
|
16
|
+
class Sink
|
|
17
|
+
def initialize(channel) = @channel = channel
|
|
18
|
+
def send_text(text) = @channel.__send__(:transmit, { "frame" => text })
|
|
19
|
+
def close(_code, _reason) = @channel.__send__(:stop_all_streams)
|
|
20
|
+
def stream_room(room, &ready) = @channel.__send__(:dovetail_stream, room, &ready)
|
|
21
|
+
def stop_room(room) = @channel.__send__(:stop_stream_from, "dovetail:#{room}")
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def receive(data)
|
|
25
|
+
frame = data.is_a?(Hash) ? data["frame"] : nil
|
|
26
|
+
text = frame.is_a?(String) ? frame : ""
|
|
27
|
+
seq = data.is_a?(Hash) ? data["seq"] : nil
|
|
28
|
+
return @session.receive(text) unless seq.is_a?(Integer)
|
|
29
|
+
|
|
30
|
+
@order.synchronize { ordered(seq, text) }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# The callbacks are private: each public method of a channel is an action of the client.
|
|
34
|
+
private
|
|
35
|
+
|
|
36
|
+
TOKEN = /"token"\s*:\s*"(?:[^"\\]|\\.)*"/
|
|
37
|
+
|
|
38
|
+
# ActionCable logs each action with its data. A hello frame has the token of the user, and a
|
|
39
|
+
# `filter_parameters` rule cannot reach into the frame string, so hide the token here (S10).
|
|
40
|
+
def action_signature(action, data)
|
|
41
|
+
frame = data["frame"]
|
|
42
|
+
super(action, frame.is_a?(String) ? data.merge("frame" => frame.gsub(TOKEN, '"token":"[FILTERED]"')) : data)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def subscribed
|
|
46
|
+
@session = Dovetail::Rails.server.connect(Sink.new(self))
|
|
47
|
+
@order = Mutex.new
|
|
48
|
+
@waiting = {}
|
|
49
|
+
@next_seq = 1
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Keeps the frame until each frame before it ran, then runs each frame that is ready.
|
|
53
|
+
def ordered(seq, text)
|
|
54
|
+
return if @waiting.nil? || seq < @next_seq
|
|
55
|
+
|
|
56
|
+
@waiting[seq] = text
|
|
57
|
+
if @waiting.size > MAX_WAITING
|
|
58
|
+
@waiting = nil
|
|
59
|
+
error = { "type" => "error", "code" => "rate-limited", "message" => "Too many frames out of order." }
|
|
60
|
+
transmit({ "frame" => Protocol.encode(error) })
|
|
61
|
+
return @session.close(1008, "too many frames out of order")
|
|
62
|
+
end
|
|
63
|
+
while (ready = @waiting.delete(@next_seq))
|
|
64
|
+
@next_seq += 1
|
|
65
|
+
@session.receive(ready)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def unsubscribed
|
|
70
|
+
@session&.closed
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Streams the room, as `stream_from` does, and calls `ready` when the subscription is live.
|
|
74
|
+
# `stream_from` gives no such callback: it subscribes later on the event loop, so a broadcast
|
|
75
|
+
# just after the ack of the join did not reach the new member. `ready` runs on the worker
|
|
76
|
+
# pool, as the frames of the stream do.
|
|
77
|
+
def dovetail_stream(room, &ready)
|
|
78
|
+
return if unsubscribed?
|
|
79
|
+
|
|
80
|
+
broadcasting = "dovetail:#{room}"
|
|
81
|
+
relay = lambda do |message|
|
|
82
|
+
transmit({ "frame" => message["frame"] }) unless message["except"] == @session.id
|
|
83
|
+
end
|
|
84
|
+
handler = worker_pool_stream_handler(broadcasting, relay, coder: ActiveSupport::JSON)
|
|
85
|
+
streams[broadcasting] = handler
|
|
86
|
+
pubsub.subscribe(broadcasting, handler, lambda do
|
|
87
|
+
connection.worker_pool.async_invoke(ready, :call, connection: connection) if ready
|
|
88
|
+
end)
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Dovetail
|
|
4
|
+
module Rails
|
|
5
|
+
# The options of the server of a Rails app. Each one is an option of `Dovetail::Server`.
|
|
6
|
+
class Configuration
|
|
7
|
+
OPTIONS = %i[authenticate authorize handle_write docs merge_updates notifications limits
|
|
8
|
+
awareness_timeout fanout feed_log on_error on_session_end allow_anonymous
|
|
9
|
+
validate_update authorize_awareness on_warning].freeze
|
|
10
|
+
|
|
11
|
+
attr_accessor(*OPTIONS)
|
|
12
|
+
|
|
13
|
+
def initialize
|
|
14
|
+
# A broadcast goes through ActionCable, so it reaches the members in each process.
|
|
15
|
+
@fanout = CableFanout.new
|
|
16
|
+
# The cursors come from Rails.cache, so each process gives the same cursors.
|
|
17
|
+
@feed_log = CacheFeedLog.new(::Rails.cache)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def to_h = OPTIONS.to_h { |name| [name, public_send(name)] }.compact
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Dovetail
|
|
4
|
+
module Rails
|
|
5
|
+
# The model macros. A Rails app gets them on each ActiveRecord model.
|
|
6
|
+
module Model
|
|
7
|
+
extend ActiveSupport::Concern
|
|
8
|
+
|
|
9
|
+
class_methods do
|
|
10
|
+
# Sends the record as a JSON:API document to the store feed after each commit, and a
|
|
11
|
+
# delete after a destroy (ADR 0004).
|
|
12
|
+
#
|
|
13
|
+
# broadcasts_dovetail to: ->(note) { "note:#{note.id}" }, attributes: %i[title body]
|
|
14
|
+
#
|
|
15
|
+
# `to` is a room, a list of rooms, a method name or a proc. `type` is the JSON:API type
|
|
16
|
+
# (default: the model name, as `note`). `attributes` is the allowlist of the attributes
|
|
17
|
+
# to send. `document` is a proc that makes the document. Give one of them: each member of
|
|
18
|
+
# the room gets the document, so the default is not "each column".
|
|
19
|
+
def broadcasts_dovetail(to:, type: nil, attributes: nil, document: nil)
|
|
20
|
+
unless attributes || document
|
|
21
|
+
raise ArgumentError, "broadcasts_dovetail needs attributes: (an allowlist) or document:"
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
after_commit(on: %i[create update]) do
|
|
25
|
+
doc = document ? document.call(self) : Model.document(self, type, attributes)
|
|
26
|
+
Model.rooms(self, to).each { |room| Dovetail::Rails.server.publish(room, doc) }
|
|
27
|
+
end
|
|
28
|
+
after_commit(on: :destroy) do
|
|
29
|
+
ref = { "type" => type || Model.type_of(self), "id" => id.to_s }
|
|
30
|
+
Model.rooms(self, to).each { |room| Dovetail::Rails.server.remove(room, ref) }
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Notifies users after the commit of a new record (ADR 0009).
|
|
35
|
+
#
|
|
36
|
+
# notifies_dovetail to: :recipient, verb: "commented", actor: :author, target: :note
|
|
37
|
+
#
|
|
38
|
+
# `to` gives a user or a list of users (records or ids). `actor` and `target` give a
|
|
39
|
+
# record or a JSON:API identifier. `target` is the record itself by default. Each one is
|
|
40
|
+
# a method name, a proc or a value.
|
|
41
|
+
def notifies_dovetail(to:, verb:, actor:, target: nil, on: :create)
|
|
42
|
+
after_commit(on: on) do
|
|
43
|
+
recipients = Array(Model.resolve(self, to)).compact
|
|
44
|
+
recipients.each do |user|
|
|
45
|
+
Dovetail::Rails.notify(user, verb: verb, actor: Model.identifier(Model.resolve(self, actor)),
|
|
46
|
+
target: Model.identifier(target ? Model.resolve(self, target) : self))
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
class << self
|
|
53
|
+
def resolve(record, value)
|
|
54
|
+
case value
|
|
55
|
+
when Proc then value.call(record)
|
|
56
|
+
when Symbol then record.public_send(value)
|
|
57
|
+
else value
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def rooms(record, to) = Array(resolve(record, to)).map(&:to_s)
|
|
62
|
+
|
|
63
|
+
def type_of(record) = record.model_name.singular.dasherize
|
|
64
|
+
|
|
65
|
+
def identifier(value)
|
|
66
|
+
return value.to_h.transform_keys(&:to_s) unless value.respond_to?(:model_name)
|
|
67
|
+
|
|
68
|
+
{ "type" => type_of(value), "id" => value.id.to_s }
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# The document of the allowlist: each attribute as JSON, with a camelCase key.
|
|
72
|
+
def document(record, type, names)
|
|
73
|
+
attributes = names.to_h { |name| [name.to_s.camelize(:lower), record.public_send(name).as_json] }
|
|
74
|
+
{ "data" => { "type" => type || type_of(record), "id" => record.id.to_s, "attributes" => attributes } }
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "active_record"
|
|
4
|
+
|
|
5
|
+
module Dovetail
|
|
6
|
+
module Rails
|
|
7
|
+
# A row of `dovetail_notifications` (`rails generate dovetail:install`).
|
|
8
|
+
class NotificationRecord < ActiveRecord::Base
|
|
9
|
+
self.table_name = "dovetail_notifications"
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# The notifications of each user in the database, so each process sees the same
|
|
13
|
+
# notifications. It has the methods of `Dovetail::MemoryNotificationStore`.
|
|
14
|
+
class RecordNotificationStore
|
|
15
|
+
def add(user_id, notification)
|
|
16
|
+
attributes = notification["attributes"]
|
|
17
|
+
NotificationRecord.create!(uid: notification["id"], user_id: user_id, payload: JSON.generate(notification),
|
|
18
|
+
read_at: attributes["readAt"], archived_at: attributes["archivedAt"])
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def get(user_id, id) = (record = scope(user_id).find_by(uid: id)) && resource(record)
|
|
22
|
+
|
|
23
|
+
def list(user_id, filter: "all", before: nil, limit: 20)
|
|
24
|
+
limit = limit.to_i.clamp(1, 100)
|
|
25
|
+
rows = filtered(scope(user_id), filter).order(id: :desc)
|
|
26
|
+
if before
|
|
27
|
+
anchor = scope(user_id).find_by(uid: before) or return { data: [], next: nil }
|
|
28
|
+
rows = rows.where(id: ...anchor.id)
|
|
29
|
+
end
|
|
30
|
+
rows = rows.limit(limit + 1).to_a
|
|
31
|
+
data = rows.first(limit).map { |record| resource(record) }
|
|
32
|
+
{ data: data, next: rows.size > limit ? data.last["id"] : nil }
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def update(user_id, id, changes)
|
|
36
|
+
record = scope(user_id).find_by(uid: id) or return nil
|
|
37
|
+
change(record, changes)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def mark_all_read(user_id, at)
|
|
41
|
+
filtered(scope(user_id), "unread").order(:id).map { |record| change(record, "readAt" => at) }
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def unread_count(user_id) = filtered(scope(user_id), "unread").count
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def scope(user_id) = NotificationRecord.where(user_id: user_id.to_s)
|
|
49
|
+
def resource(record) = JSON.parse(record.payload)
|
|
50
|
+
|
|
51
|
+
def filtered(rows, filter)
|
|
52
|
+
case filter
|
|
53
|
+
when "all" then rows.where(archived_at: nil)
|
|
54
|
+
when "unread" then rows.where(archived_at: nil, read_at: nil)
|
|
55
|
+
when "archived" then rows.where.not(archived_at: nil)
|
|
56
|
+
else raise ArgumentError, "unknown filter"
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def change(record, changes)
|
|
61
|
+
notification = resource(record)
|
|
62
|
+
attributes = notification["attributes"].merge!(changes.slice("readAt", "seenAt", "archivedAt"))
|
|
63
|
+
record.update!(payload: JSON.generate(notification), read_at: attributes["readAt"],
|
|
64
|
+
archived_at: attributes["archivedAt"])
|
|
65
|
+
notification
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "dovetail"
|
|
4
|
+
require "rails"
|
|
5
|
+
require "action_cable"
|
|
6
|
+
require "concurrent"
|
|
7
|
+
require_relative "rails/configuration"
|
|
8
|
+
require_relative "rails/cache_feed_log"
|
|
9
|
+
require_relative "rails/cable_fanout"
|
|
10
|
+
require_relative "rails/model"
|
|
11
|
+
require_relative "rails/channel"
|
|
12
|
+
|
|
13
|
+
module Dovetail
|
|
14
|
+
# Dovetail for Rails: an ActionCable channel that speaks the protocol (`Dovetail::Channel`),
|
|
15
|
+
# the model macros `broadcasts_dovetail` and `notifies_dovetail`, the auth hooks and a
|
|
16
|
+
# generator (`rails generate dovetail:install`).
|
|
17
|
+
#
|
|
18
|
+
# Dovetail::Rails.configure do |config|
|
|
19
|
+
# config.authenticate = ->(token) { User.find_by_dovetail_token(token) } # nil for a blank token
|
|
20
|
+
# config.authorize = ->(user, room, action) { user.can?(action, room) }
|
|
21
|
+
# end
|
|
22
|
+
module Rails
|
|
23
|
+
autoload :RecordNotificationStore, "dovetail/rails/record_notification_store"
|
|
24
|
+
autoload :NotificationRecord, "dovetail/rails/record_notification_store"
|
|
25
|
+
|
|
26
|
+
class << self
|
|
27
|
+
def config = @config ||= Configuration.new
|
|
28
|
+
|
|
29
|
+
# Sets the hooks and the stores. Call it before the first connection.
|
|
30
|
+
def configure
|
|
31
|
+
raise "Dovetail::Rails: the server already started; configure it in an initializer" if @server
|
|
32
|
+
|
|
33
|
+
yield config
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# The seconds between two sweeps of the old awareness states.
|
|
37
|
+
SWEEP_EVERY = 5
|
|
38
|
+
|
|
39
|
+
# The server of this process. It starts on first use, with the configuration, and with
|
|
40
|
+
# one awareness sweep for the process (not one for each subscription).
|
|
41
|
+
def server
|
|
42
|
+
@server ||= Dovetail::Server.new(**config.to_h).tap do |made|
|
|
43
|
+
@sweeper = Concurrent::TimerTask.execute(execution_interval: SWEEP_EVERY) { made.sweep_awareness }
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# The timer of the awareness sweep, after the server started.
|
|
48
|
+
attr_reader :sweeper
|
|
49
|
+
|
|
50
|
+
# Notifies a user (a record with `id`, or an id) on the per-user room (ADR 0009).
|
|
51
|
+
def notify(user, verb:, actor:, target:, **options)
|
|
52
|
+
server.notify(user.respond_to?(:id) ? user.id.to_s : user.to_s, verb: verb, actor: actor, target: target, **options)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# A Rack app for the notification endpoints. Mount it in the routes:
|
|
56
|
+
# `mount Dovetail::Rails.notifications_app, at: "/dovetail/notifications"`.
|
|
57
|
+
def notifications_app = Dovetail::NotificationsApp.new(-> { server })
|
|
58
|
+
|
|
59
|
+
# Forgets the server and the configuration. For tests.
|
|
60
|
+
def reset!
|
|
61
|
+
@sweeper&.shutdown
|
|
62
|
+
@sweeper = nil
|
|
63
|
+
@server = nil
|
|
64
|
+
@config = nil
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Loads Dovetail into a Rails app.
|
|
69
|
+
class Railtie < ::Rails::Railtie
|
|
70
|
+
initializer "dovetail.model" do
|
|
71
|
+
ActiveSupport.on_load(:active_record) { include Dovetail::Rails::Model }
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/generators"
|
|
4
|
+
require "rails/generators/active_record"
|
|
5
|
+
|
|
6
|
+
module Dovetail
|
|
7
|
+
module Generators
|
|
8
|
+
# `rails generate dovetail:install` writes the initializer with the hooks, and the migration
|
|
9
|
+
# of the notifications table.
|
|
10
|
+
class InstallGenerator < ::Rails::Generators::Base
|
|
11
|
+
include ::Rails::Generators::Migration
|
|
12
|
+
|
|
13
|
+
source_root File.expand_path("templates", __dir__)
|
|
14
|
+
|
|
15
|
+
def self.next_migration_number(dirname) = ::ActiveRecord::Generators::Base.next_migration_number(dirname)
|
|
16
|
+
|
|
17
|
+
def create_initializer
|
|
18
|
+
template "initializer.rb.tt", "config/initializers/dovetail.rb"
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def create_migration_file
|
|
22
|
+
migration_template "create_dovetail_notifications.rb.tt", "db/migrate/create_dovetail_notifications.rb"
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class CreateDovetailNotifications < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
|
|
4
|
+
def change
|
|
5
|
+
create_table :dovetail_notifications do |t|
|
|
6
|
+
t.string :uid, null: false
|
|
7
|
+
t.string :user_id, null: false
|
|
8
|
+
t.text :payload, null: false
|
|
9
|
+
t.string :read_at
|
|
10
|
+
t.string :archived_at
|
|
11
|
+
t.timestamps
|
|
12
|
+
end
|
|
13
|
+
add_index :dovetail_notifications, %i[user_id uid], unique: true
|
|
14
|
+
add_index :dovetail_notifications, %i[user_id id]
|
|
15
|
+
end
|
|
16
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Dovetail: real-time and offline sync (https://joegaudet.com/dovetail/).
|
|
4
|
+
Dovetail::Rails.configure do |config|
|
|
5
|
+
# The user of the token of the client `getToken()` hook, or nil to refuse it.
|
|
6
|
+
config.authenticate = ->(token) { nil }
|
|
7
|
+
|
|
8
|
+
# Decides each join and each write. A user can join only the own per-user room.
|
|
9
|
+
config.authorize = ->(user, room, action) { false }
|
|
10
|
+
|
|
11
|
+
# Applies a write: { ok: true, document: } or { ok: false, status: 422, errors: [] }.
|
|
12
|
+
# config.handle_write = ->(write) { { ok: true } }
|
|
13
|
+
|
|
14
|
+
# The notifications stay in the dovetail_notifications table.
|
|
15
|
+
config.notifications = Dovetail::Rails::RecordNotificationStore.new
|
|
16
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: dovetail-rails
|
|
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
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: actioncable
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
-
|
|
17
|
+
- ">="
|
|
18
|
+
- !ruby/object:Gem::Version
|
|
19
|
+
version: "7.1"
|
|
20
|
+
-
|
|
21
|
+
- "<"
|
|
22
|
+
- !ruby/object:Gem::Version
|
|
23
|
+
version: "9"
|
|
24
|
+
type: :runtime
|
|
25
|
+
prerelease: false
|
|
26
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
27
|
+
requirements:
|
|
28
|
+
-
|
|
29
|
+
- ">="
|
|
30
|
+
- !ruby/object:Gem::Version
|
|
31
|
+
version: "7.1"
|
|
32
|
+
-
|
|
33
|
+
- "<"
|
|
34
|
+
- !ruby/object:Gem::Version
|
|
35
|
+
version: "9"
|
|
36
|
+
- !ruby/object:Gem::Dependency
|
|
37
|
+
name: dovetail
|
|
38
|
+
requirement: !ruby/object:Gem::Requirement
|
|
39
|
+
requirements:
|
|
40
|
+
-
|
|
41
|
+
- "="
|
|
42
|
+
- !ruby/object:Gem::Version
|
|
43
|
+
version: 1.0.0
|
|
44
|
+
type: :runtime
|
|
45
|
+
prerelease: false
|
|
46
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
-
|
|
49
|
+
- "="
|
|
50
|
+
- !ruby/object:Gem::Version
|
|
51
|
+
version: 1.0.0
|
|
52
|
+
- !ruby/object:Gem::Dependency
|
|
53
|
+
name: railties
|
|
54
|
+
requirement: !ruby/object:Gem::Requirement
|
|
55
|
+
requirements:
|
|
56
|
+
-
|
|
57
|
+
- ">="
|
|
58
|
+
- !ruby/object:Gem::Version
|
|
59
|
+
version: "7.1"
|
|
60
|
+
-
|
|
61
|
+
- "<"
|
|
62
|
+
- !ruby/object:Gem::Version
|
|
63
|
+
version: "9"
|
|
64
|
+
type: :runtime
|
|
65
|
+
prerelease: false
|
|
66
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
67
|
+
requirements:
|
|
68
|
+
-
|
|
69
|
+
- ">="
|
|
70
|
+
- !ruby/object:Gem::Version
|
|
71
|
+
version: "7.1"
|
|
72
|
+
-
|
|
73
|
+
- "<"
|
|
74
|
+
- !ruby/object:Gem::Version
|
|
75
|
+
version: "9"
|
|
76
|
+
email:
|
|
77
|
+
- joe@joegaudet.com
|
|
78
|
+
executables: []
|
|
79
|
+
extensions: []
|
|
80
|
+
extra_rdoc_files: []
|
|
81
|
+
files:
|
|
82
|
+
- LICENSE
|
|
83
|
+
- README.md
|
|
84
|
+
- lib/dovetail-rails.rb
|
|
85
|
+
- lib/dovetail/rails.rb
|
|
86
|
+
- lib/dovetail/rails/cable_fanout.rb
|
|
87
|
+
- lib/dovetail/rails/cache_feed_log.rb
|
|
88
|
+
- lib/dovetail/rails/channel.rb
|
|
89
|
+
- lib/dovetail/rails/configuration.rb
|
|
90
|
+
- lib/dovetail/rails/model.rb
|
|
91
|
+
- lib/dovetail/rails/record_notification_store.rb
|
|
92
|
+
- lib/generators/dovetail/install/install_generator.rb
|
|
93
|
+
- lib/generators/dovetail/install/templates/create_dovetail_notifications.rb.tt
|
|
94
|
+
- lib/generators/dovetail/install/templates/initializer.rb.tt
|
|
95
|
+
homepage: "https://joegaudet.com/dovetail/"
|
|
96
|
+
licenses:
|
|
97
|
+
- MIT
|
|
98
|
+
metadata:
|
|
99
|
+
source_code_uri: "https://github.com/joegaudet/dovetail/tree/main/ruby/dovetail-rails"
|
|
100
|
+
bug_tracker_uri: "https://github.com/joegaudet/dovetail/issues"
|
|
101
|
+
rubygems_mfa_required: "true"
|
|
102
|
+
rdoc_options: []
|
|
103
|
+
require_paths:
|
|
104
|
+
- lib
|
|
105
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
106
|
+
requirements:
|
|
107
|
+
-
|
|
108
|
+
- ">="
|
|
109
|
+
- !ruby/object:Gem::Version
|
|
110
|
+
version: "3.3"
|
|
111
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
112
|
+
requirements:
|
|
113
|
+
-
|
|
114
|
+
- ">="
|
|
115
|
+
- !ruby/object:Gem::Version
|
|
116
|
+
version: "0"
|
|
117
|
+
requirements: []
|
|
118
|
+
rubygems_version: 4.1.1
|
|
119
|
+
specification_version: 4
|
|
120
|
+
summary: "Dovetail for Rails: an ActionCable channel, model broadcast, the auth hook and a generator."
|
|
121
|
+
test_files: []
|