Module: Lich::Common::Events
- Defined in:
- documented/common/events.rb
Overview
Events - the shared notice board for script-to-script notifications.
One process-wide registry of topic -> subscribers. An emitter says what just happened; it does not know or care who is listening:
Events.emit('go2.status', Go2.status)
A listener pins a note saying "when anyone says go2.status, run this":
Events.on('go2.status', name: 'eohunter') { |topic, status|
@need_heal = true if status.phase == :blocked
}
Design (extracted from the former Combat::Observers and from HookRegistry, the two places this was previously re-solved):
* Topics are dotted strings ('combat.damage', 'go2.status'). A
subscription may name a topic exactly, a family with a trailing
wildcard ('combat.*' matches 'combat.damage' but not 'combat'), or
everything with '*'. Symbols are accepted and stringified.
* Named registration is idempotent: subscribing again under the same
name replaces the previous handler instead of stacking, so script
restarts and interactive ;e testing are safe. An unnamed
subscription gets a generated name (returned by {on}).
* Every subscription records the registering script (Script.current)
as its owner. When that script dies, its persist: false subscriptions
(the default) are removed by the {ScriptDeath} handler, so a crashed
supervisor cannot leave a ghost listener. persist: true keeps a
subscription past its owner's exit (a daemon that re-registers on
boot should still off itself in before_dying).
* Delivery is synchronous on the emitter's thread. Handlers must be
cheap and non-blocking, and must never send game commands (fput,
Spell#cast, PSMS.use) - set a flag or queue work for your own script
thread. A raising handler is isolated and logged; it never breaks
other handlers or the emitter.
* Deliberately not here: async delivery, queues, history, persistence.
A consumer that wants its own thread pushes onto its own queue.
State versus events: keep a read model (Go2.status, the Creature registry) for "what is true now" and poll it. Emit events for the edges that polling cannot see - transitions, transients, the moment something changed. Payloads should be the read model's own object or a small Hash.
Defined Under Namespace
Classes: Subscription
Class Method Summary collapse
-
.any_for?(topic) ⇒ Boolean
Whether any subscription would receive
topic. -
.cleanup_on_death(owner_id) ⇒ Integer
ScriptDeath hook: drop the dying script's persist: false subscriptions.
-
.clear!(prefix = nil) ⇒ Integer
Remove every subscription, or only those listening to a topic family when
prefixis given (e.g. 'combat.'). -
.emit(topic, payload = nil) ⇒ Integer
Deliver
payloadto every subscriber whose pattern matchestopic. -
.list ⇒ Array<Array>
Subscriptions as a table: name, topics, owner script, persist flag.
-
.names ⇒ Array<String>
Names of the current subscriptions.
-
.off(name_or_block) ⇒ Boolean
Remove a subscription by the name Events.on returned, or by the block that was registered.
- .off_change(block) ⇒ void
-
.on(*topics, name: nil, persist: false) {|topic, payload| ... } ⇒ String
Subscribe to one or more topics.
-
.on_change(prefix: nil, &block) ⇒ Proc
A block run after a registration change (on, off, clear!, owner death).
Class Method Details
.any_for?(topic) ⇒ Boolean
Whether any subscription would receive topic. Emitters with an
expensive payload can skip building it when nobody is listening.
155 156 157 158 |
# File 'documented/common/events.rb', line 155 def any_for?(topic) topic = normalize(topic) @mutex.synchronize { @subs.each_value.any? { |s| matches?(s, topic) } } end |
.cleanup_on_death(owner_id) ⇒ Integer
ScriptDeath hook: drop the dying script's persist: false subscriptions. Keyed on object_id so a same-named sibling script is unaffected.
216 217 218 219 220 221 222 223 224 225 226 |
# File 'documented/common/events.rb', line 216 def cleanup_on_death(owner_id) return 0 if owner_id.nil? # core registrations have no owner removed = @mutex.synchronize do doomed = @subs.values.select { |s| s.owner_id == owner_id && !s.persist } doomed.each { |s| @subs.delete(s.name) } doomed end changed(removed) unless removed.empty? removed.length end |
.clear!(prefix = nil) ⇒ Integer
Remove every subscription, or only those listening to a topic family
when prefix is given (e.g. 'combat.').
200 201 202 203 204 205 206 207 208 |
# File 'documented/common/events.rb', line 200 def clear!(prefix = nil) removed = @mutex.synchronize do doomed = prefix ? @subs.values.select { |s| touches?(s, prefix.to_s) } : @subs.values.dup doomed.each { |s| @subs.delete(s.name) } doomed end changed(removed) unless removed.empty? removed.length end |
.emit(topic, payload = nil) ⇒ Integer
Deliver payload to every subscriber whose pattern matches topic.
Synchronous, on the caller's thread; subscriber errors are logged and
swallowed so an emitter is never broken by a listener.
137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'documented/common/events.rb', line 137 def emit(topic, payload = nil) topic = normalize(topic) handlers = @mutex.synchronize { @subs.values.select { |s| matches?(s, topic) } } handlers.each do |sub| begin sub.block.call(topic, payload) rescue StandardError => e log "error: Events subscriber #{sub.name} (#{topic}): #{e.}\n\t#{e.backtrace&.first}" end end handlers.length end |
.list ⇒ Array<Array>
Subscriptions as a table: name, topics, owner script, persist flag.
185 186 187 |
# File 'documented/common/events.rb', line 185 def list @mutex.synchronize { @subs.values.map { |s| [s.name, s.topics.dup, s.owner_name, s.persist] } } end |
.names ⇒ Array<String>
Names of the current subscriptions.
191 192 193 |
# File 'documented/common/events.rb', line 191 def names @mutex.synchronize { @subs.keys.dup } end |
.off(name_or_block) ⇒ Boolean
Remove a subscription by the name on returned, or by the block that was registered.
Not synchronous with in-flight delivery: emit snapshots its handler list before calling any, so a handler removed while an emit is iterating can still run once more. Handlers that must not act after their owner starts shutting down should check their own state rather than rely on off having taken effect.
117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'documented/common/events.rb', line 117 def off(name_or_block) removed = @mutex.synchronize do if name_or_block.is_a?(Proc) key = @subs.find { |_, s| s.block.equal?(name_or_block) }&.first key ? @subs.delete(key) : nil else @subs.delete(name_or_block.to_s) end end changed([removed]) if removed !removed.nil? end |
.off_change(block) ⇒ void
This method returns an undefined value.
178 179 180 181 |
# File 'documented/common/events.rb', line 178 def off_change(block) @mutex.synchronize { @on_change.delete_if { |(_, b)| b.equal?(block) } } nil end |
.on(*topics, name: nil, persist: false) {|topic, payload| ... } ⇒ String
Subscribe to one or more topics.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'documented/common/events.rb', line 80 def on(*topics, name: nil, persist: false, &block) raise ArgumentError, 'Events.on requires a block' unless block patterns = topics.flatten.compact.map { |t| normalize(t) } patterns = ['*'] if patterns.empty? owner = current_script sub = Subscription.new( name: (name ? name.to_s : generated_name(owner)), topics: patterns.uniq.freeze, block: block, owner_id: owner&.object_id, owner_name: (owner&.name || 'Unknown'), persist: (persist ? true : false) ) replaced = @mutex.synchronize do old = @subs[sub.name] @subs[sub.name] = sub old end # A named re-registration may move to a different topic family; the # family it left needs its on_change too (Combat::Messages would # otherwise keep its hook installed with nobody listening). changed(replaced ? [replaced, sub] : [sub]) sub.name end |
.on_change(prefix: nil, &block) ⇒ Proc
A block run after a registration change (on, off, clear!, owner death). Lets a producer scan only for families somebody wants (the way Combat::Messages does). Errors are isolated like handlers.
168 169 170 171 172 173 174 |
# File 'documented/common/events.rb', line 168 def on_change(prefix: nil, &block) return nil unless block entry = [prefix&.to_s, block] @mutex.synchronize { @on_change << entry } block end |