monkrb 0.29.0 → 0.30.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7132e58f0298e396b2a37747ebff177461dc6bd8423aae6f01d7265b0f07326e
4
- data.tar.gz: 5a4d712e95850492f12f544836e8286601daff42ce4f40cdf47c15bde5950413
3
+ metadata.gz: c2be6827b58d52cd4affcab6277ed623343125cfebed3b6d6bec9f8936802ee7
4
+ data.tar.gz: 6b1e52510611432e11bbda58c6025382bba32218d3a51b3f71af12643019c7ff
5
5
  SHA512:
6
- metadata.gz: 60789c467217ee7d51a872c4b14c3d17f8b93f0d05388755c18dcab577c9a90fad07a47923e513681984e420310c8daab9e8099f5436b041d5bf5fab645f5895
7
- data.tar.gz: adf149afd042a07fc9796d0eaaafd7414972413be97c0582a356fbb80559a35ef0e2c6d4d49477140eaf679ab6ffbe3dde6072a06b224c7c90b2f3be83b3682d
6
+ metadata.gz: 6346e59feabaa1fbbd09e74f5ca3425e40e1b5ec9e85fd69976d042e5063ace76b1452c19f3a4eb5598db330ce3cf17992f92fe11b108f9b9b77d3984e3c8f24
7
+ data.tar.gz: 684dd9255869b878238fdf6c612153bfd9a92399d2bd7b15d3162b3f2b09cef3f0d8869b8fb9db0476fd43bd2796c949ead4382d3a95c1f77b456f5cc90c32bb
data/CHANGELOG.md CHANGED
@@ -4,6 +4,30 @@ All notable changes to this project are documented here. Format is loosely
4
4
  [Keep a Changelog](https://keepachangelog.com/); versions are as released
5
5
  in `lib/monk/version.rb`.
6
6
 
7
+ ## 0.30.0 - 2026-11-27
8
+
9
+ Batched topic authorization in Live. Existing apps: nothing to change,
10
+ unless a rule's block returns a collection
11
+ ([`upgrading.md`](docs/guides/upgrading.md#030)).
12
+
13
+ ### Added
14
+
15
+ - **`Monk::Live.authorize(..., batch: true) { |subject, topics| ... }`.**
16
+ The block decides all of a subscribe message's topics that the rule
17
+ matches first, in one call, and returns the allowed ones (an Array or
18
+ a Set). With `db_pool:`, one pool call and one query per message
19
+ instead of one per topic: a page subscribing to a topic per row no
20
+ longer runs a query per row on every load and reconnect. Fails closed
21
+ for the whole group; `true` never means "all" (ADR 0009, amended).
22
+
23
+ ### Changed
24
+
25
+ - **A rule whose block returns an Array, a Set or a Hash denies.** Such
26
+ a result is truthy even when empty, so a batch block declared without
27
+ `batch: true` would have let every topic in. The denial is logged.
28
+ - **A rule block that raises is logged**, not only denied, with the rule
29
+ and the exception.
30
+
7
31
  ## 0.29.0 - 2026-11-27
8
32
 
9
33
  Live's first-connect resync, and a baseline for offline. Existing apps:
data/README.md CHANGED
@@ -21,7 +21,7 @@ bin/server # -> http://localhost:9292/hello
21
21
  monk add --list # the modules you can add: postgres, auth, jobs, live...
22
22
  ```
23
23
 
24
- `monk new` scaffolds the app's own `Gemfile` with `gem "monkrb", "~> 0.29", require: "monk"`.
24
+ `monk new` scaffolds the app's own `Gemfile` with `gem "monkrb", "~> 0.30", require: "monk"`.
25
25
 
26
26
  `monk new` writes a working app: an HTML home page, a `/hello` route and a `/api/hello` JSON route, `public/`, its tests, a `SETUP.md`, and an `AGENTS.md` for coding agents. The app's own code goes under `app/`: `app/app.rb` and `app/routes/` for routes, `app/views/`, and one directory per role (`models/`, `presenters/`, `helpers/`, `mailers/`, `broadcasts/`, `jobs/`).
27
27
 
@@ -6,7 +6,8 @@ module Monk
6
6
  # rule matches is denied, and so is an anonymous subject (nil) unless
7
7
  # the matching rule says `anonymous: true`: a block like
8
8
  # `topic == "contacts:#{subject}"` would otherwise let a nil subject
9
- # in through "contacts:". A block that raises fails closed.
9
+ # in through "contacts:". A block that raises fails closed, and the
10
+ # reason is logged.
10
11
  #
11
12
  # A rule with db_pool: runs its block in that Monk::Persistence::Pg pool,
12
13
  # not in the socket's own Ractor, so a rule that queries the database
@@ -14,8 +15,18 @@ module Monk
14
15
  # as it is: rules are shareable procs already. If the pool itself fails
15
16
  # (not started in this process, timed out, full), the rule denies and the
16
17
  # reason is logged.
18
+ #
19
+ # A rule with batch: true decides a subscribe message's topics in one
20
+ # call: its block gets every topic of the message that this rule
21
+ # matches first (at most Session::MAX_TOPICS_PER_MESSAGE), and returns
22
+ # the allowed ones, an Array or a Set; nil or false allows none. With
23
+ # db_pool:, that's one pool call per message, not one per topic. A
24
+ # returned topic that wasn't asked for is ignored; any other result
25
+ # denies them all and is logged, so `true` never means "all". A
26
+ # single-topic rule that returns a collection denies too: it is a batch
27
+ # block missing batch: true, and an Array is truthy even when empty.
17
28
  module Policy
18
- Rule = Data.define(:pattern, :anonymous, :check, :db_pool) do
29
+ Rule = Data.define(:pattern, :anonymous, :check, :db_pool, :batch) do
19
30
  def matches?(topic)
20
31
  if pattern.end_with?("*")
21
32
  topic.start_with?(pattern.chomp("*"))
@@ -25,7 +36,12 @@ module Monk
25
36
  end
26
37
  end
27
38
 
28
- def self.build_rule(pattern, anonymous, block, db_pool = nil)
39
+ POOL_ERRORS = [
40
+ Monk::PersistenceTimeoutError, Monk::PoolFullError, Monk::PoolNotStartedError, Monk::UnknownPoolError,
41
+ Monk::PoolWorkerDiedError, Monk::PoolStoppedError,
42
+ ].freeze
43
+
44
+ def self.build_rule(pattern, anonymous, block, db_pool: nil, batch: false)
29
45
  unless pattern.is_a?(String) && !pattern.strip.empty? && valid_wildcard?(pattern)
30
46
  raise ArgumentError,
31
47
  "pattern must be a topic or a topic prefix ending in a single *, got #{pattern.inspect}"
@@ -34,43 +50,97 @@ module Monk
34
50
  unless db_pool.nil? || db_pool.is_a?(Symbol)
35
51
  raise ArgumentError, "db_pool must be a pool name (a Symbol), got #{db_pool.inspect}"
36
52
  end
53
+ raise ArgumentError, "batch must be true or false, got #{batch.inspect}" unless [true, false].include?(batch)
37
54
 
38
- Rule.new(pattern: pattern.dup.freeze, anonymous: anonymous, check: shareable(block), db_pool: db_pool)
55
+ Rule.new(pattern: pattern.dup.freeze, anonymous: anonymous, check: shareable(block), db_pool: db_pool,
56
+ batch: batch,)
39
57
  end
40
58
 
41
- def self.allowed?(rules, subject, topic)
42
- rule = rules.find { |candidate| candidate.matches?(topic) }
43
- return false unless rule
44
- return false if subject.nil? && !rule.anonymous
59
+ def self.allowed?(rules, subject, topic) = allowed_topics(rules, subject, [topic]).include?(topic)
60
+
61
+ # The topics of one subscribe message that may be subscribed, as a
62
+ # Set. Each distinct topic goes to the first rule it matches; a
63
+ # single-topic rule is called per topic, a batch rule once with its
64
+ # group. Topics are frozen first, so a block can't change one the
65
+ # session goes on to register.
66
+ def self.allowed_topics(rules, subject, topics)
67
+ groups = {}.compare_by_identity
68
+ topics.uniq.each do |topic|
69
+ rule = rules.find { |candidate| candidate.matches?(topic) }
70
+ (groups[rule] ||= []) << topic.freeze if rule
71
+ end
72
+
73
+ groups.each_with_object(Set.new) do |(rule, group), allowed|
74
+ next if subject.nil? && !rule.anonymous
75
+
76
+ if rule.batch
77
+ allowed.merge(decide_many(rule, subject, group.freeze))
78
+ else
79
+ group.each { |topic| allowed << topic if decide(rule, subject, topic) }
80
+ end
81
+ end
82
+ end
45
83
 
46
- run(rule, subject, topic) ? true : false
47
- rescue Monk::PersistenceTimeoutError, Monk::PoolFullError, Monk::PoolNotStartedError, Monk::UnknownPoolError,
48
- Monk::PoolWorkerDiedError, Monk::PoolStoppedError => e
84
+ # What a pooled rule runs in the pool's worker: one topic, or a
85
+ # batch rule's group.
86
+ def self.check(block, subject, topics) = block.call(subject, topics)
87
+
88
+ def self.decide(rule, subject, topic)
89
+ result = run(rule, subject, topic)
90
+ if result.is_a?(Array) || result.is_a?(Set) || result.is_a?(Hash)
91
+ log_denial(rule, topic,
92
+ "its block returned #{result.class}: a rule that returns the allowed topics needs batch: true",)
93
+ return false
94
+ end
95
+ result ? true : false
96
+ rescue *POOL_ERRORS => e
49
97
  log_pool_failure(rule, topic, e)
50
98
  false
51
- rescue StandardError
99
+ rescue StandardError => e
100
+ log_denial(rule, topic, "its block raised #{e.class}: #{e.message}")
52
101
  false
53
102
  end
103
+ private_class_method :decide
104
+
105
+ def self.decide_many(rule, subject, group)
106
+ case (result = run(rule, subject, group))
107
+ when nil, false then []
108
+ when Array, Set then group & result.to_a
109
+ else
110
+ log_denial(rule, counted(group),
111
+ "its block returned #{result.class}, not the allowed topics (an Array or a Set)",)
112
+ []
113
+ end
114
+ rescue *POOL_ERRORS => e
115
+ log_pool_failure(rule, counted(group), e)
116
+ []
117
+ rescue StandardError => e
118
+ log_denial(rule, counted(group), "its block raised #{e.class}: #{e.message}")
119
+ []
120
+ end
121
+ private_class_method :decide_many
54
122
 
55
- # What a pooled rule runs in the pool's worker.
56
- def self.check(block, subject, topic) = block.call(subject, topic)
123
+ def self.counted(group) = group.size == 1 ? "1 topic" : "#{group.size} topics"
124
+ private_class_method :counted
57
125
 
58
- def self.run(rule, subject, topic)
59
- return rule.check.call(subject, topic) unless rule.db_pool
126
+ def self.run(rule, subject, topics)
127
+ return rule.check.call(subject, topics) unless rule.db_pool
60
128
 
61
- Monk::Persistence::Pg.pool(rule.db_pool).call(Policy, :check, rule.check, subject, topic)
129
+ Monk::Persistence::Pg.pool(rule.db_pool).call(Policy, :check, rule.check, subject, topics)
62
130
  end
63
131
  private_class_method :run
64
132
 
65
- def self.log_pool_failure(rule, topic, error)
66
- Monk::Log.error(
67
- "Monk::Live: denied #{topic} (rule #{rule.pattern}): its pool #{rule.db_pool.inspect} failed: " \
68
- "#{error.class}: #{error.message}",
69
- )
133
+ def self.log_pool_failure(rule, what, error)
134
+ log_denial(rule, what, "its pool #{rule.db_pool.inspect} failed: #{error.class}: #{error.message}")
135
+ end
136
+ private_class_method :log_pool_failure
137
+
138
+ def self.log_denial(rule, what, reason)
139
+ Monk::Log.error("Monk::Live: denied #{what} (rule #{rule.pattern}): #{reason}")
70
140
  rescue StandardError
71
141
  nil
72
142
  end
73
- private_class_method :log_pool_failure
143
+ private_class_method :log_denial
74
144
 
75
145
  def self.valid_wildcard?(pattern)
76
146
  pattern.count("*").zero? || (pattern.count("*") == 1 && pattern.end_with?("*"))
@@ -84,12 +84,21 @@ module Monk
84
84
  topics.all? { |topic| topic.is_a?(String) && topic.valid_encoding? }
85
85
  end
86
86
 
87
- # The new topics go to the registry in one ask, not one each: at a
88
- # reconnect wave's rate, one ask per topic is most of the registry
89
- # Ractor's work.
87
+ # One policy pass for the message's new topics, so a batch rule runs
88
+ # once (one query, not one per topic), and the new topics go to the
89
+ # registry in one ask: at a reconnect wave's rate, one ask per topic
90
+ # is most of the registry Ractor's work. The cap comes after the
91
+ # check, in the message's order: a denied topic takes no slot.
90
92
  def subscribe(topics)
93
+ fresh = topics.reject { |topic| @topics.key?(topic) }.grep(TOPIC_FORMAT)
94
+ permitted = fresh.empty? ? Set.new : Policy.allowed_topics(@rules, @connection.subject, fresh)
91
95
  added = {}
92
- allowed, denied = topics.partition { |topic| try_subscribe?(topic, added) }
96
+ allowed, denied = topics.partition do |topic|
97
+ next true if @topics.key?(topic) || added.key?(topic)
98
+ next false unless permitted.include?(topic) && @topics.size + added.size < @max_topics
99
+
100
+ added[topic] = topic.to_sym
101
+ end
93
102
  unless added.empty?
94
103
  @registry.register_many(added.values, @port)
95
104
  @topics.merge!(added)
@@ -97,18 +106,6 @@ module Monk
97
106
  reply(op: "subscribed", topics: allowed, denied: denied)
98
107
  end
99
108
 
100
- def try_subscribe?(topic, added)
101
- return true if @topics.key?(topic) || added.key?(topic)
102
- return false unless permitted?(topic) && @topics.size + added.size < @max_topics
103
-
104
- added[topic] = topic.to_sym
105
- true
106
- end
107
-
108
- def permitted?(topic)
109
- TOPIC_FORMAT.match?(topic) && Policy.allowed?(@rules, @connection.subject, topic)
110
- end
111
-
112
109
  def unsubscribe(topics)
113
110
  removed = topics.select { |topic| @topics.key?(topic) }
114
111
  keys = removed.filter_map { |topic| @topics.delete(topic) }
data/lib/monk/live.rb CHANGED
@@ -81,8 +81,11 @@ module Monk
81
81
  # `anonymous: true`. The block must be Ractor-shareable. db_pool:
82
82
  # names a Monk::Persistence::Pg pool to run the block in, for a rule
83
83
  # that queries the database; the WebSocket process must start it.
84
- def authorize(pattern, anonymous: false, db_pool: nil, &block)
85
- @rules = Ractor.make_shareable([*@rules, Policy.build_rule(pattern, anonymous, block, db_pool)])
84
+ # batch: true makes the block decide a subscribe message's matching
85
+ # topics in one call, { |subject, topics| allowed_topics }, for a rule
86
+ # that queries on a page with many topics of one kind.
87
+ def authorize(pattern, anonymous: false, db_pool: nil, batch: false, &block)
88
+ @rules = Ractor.make_shareable([*@rules, Policy.build_rule(pattern, anonymous, block, db_pool:, batch:)])
86
89
  end
87
90
 
88
91
  def authorized?(subject, topic) = Policy.allowed?(rules, subject, topic)
@@ -1,6 +1,6 @@
1
1
  source "https://rubygems.org"
2
2
 
3
- gem "monkrb", "~> 0.29", require: "monk"
3
+ gem "monkrb", "~> 0.30", require: "monk"
4
4
  gem "rackup"
5
5
  gem "webrick"
6
6
  gem "kino"
data/lib/monk/version.rb CHANGED
@@ -5,5 +5,5 @@ module Monk
5
5
  # class of bug .freeze! guards against for routes/error handlers/models,
6
6
  # just on a top-level constant that every worker Ractor reads on boot
7
7
  # (found live under kino: GET /hello 500'd until this was frozen).
8
- VERSION = "0.29.0".freeze
8
+ VERSION = "0.30.0".freeze
9
9
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: monkrb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.29.0
4
+ version: 0.30.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Matteo Folin