1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//! Typed global broadcast event bus.
//!
//! This module provides a process-wide publish/subscribe system built on
//! [`tokio::sync::broadcast`]. Events are keyed by their Rust type — one channel
//! per type, created lazily on first access and shared for the lifetime of the process.
//!
//! ## Core types
//!
//! | Type | Role |
//! |------|------|
//! | [`EventChannel<E>`] | The underlying broadcast transport for event type `E` |
//! | [`EventHandler<E>`] | Trait implemented by types that react to events of type `E` |
//! | [`EventLoop<E>`] | Registers handlers and starts their background receive tasks |
//!
//! ## Usage pattern
//!
//! 1. Define an event type (typically an `enum`).
//! 2. Implement [`EventHandler<E>`] on each consumer struct, annotated with
//! [`#[asynchronous]`](crate::asynchronous).
//! 3. Register all handlers at startup via [`EventLoop::dispatch`].
//! 4. Publish events from anywhere with [`event::<E>().dispatch(…)`](event).
//!
//! ## Example
//!
//! ```no_run
//! use toys::event::{event, EventHandler, EventLoop};
//! use toys::asynchronous;
//! use std::sync::Arc;
//! use std::sync::atomic::{AtomicU64, Ordering};
//!
//! pub enum AppEvent { Increment(u64) }
//!
//! struct Counter {
//! value: AtomicU64,
//! }
//!
//! #[asynchronous]
//! impl EventHandler<AppEvent> for Counter {
//! async fn handle(self: Arc<Self>, event: AppEvent) {
//! if let AppEvent::Increment(n) = event {
//! self.value.fetch_add(n, Ordering::Relaxed);
//! }
//! }
//! }
//!
//! # tokio_test::block_on(async {
//! let counter = Arc::new(Counter { value: AtomicU64::new(0) });
//! // if you dont clone counter, it moves it.
//! let handles = EventLoop::<AppEvent>::new().dispatch(&[counter.clone()]).await;
//!
//! event::<AppEvent>().dispatch(AppEvent::Increment(1)).await.unwrap();
//! event::<AppEvent>().dispatch(AppEvent::Increment(30)).await.unwrap();
//!
//! // shut down the handler's background task
//! handles[0].1.send(()).unwrap();
//! handles[0].0.await.unwrap().unwrap();
//! println!("counter = {}", counter.value.load(Ordering::Relaxed));
//! # });
//! ```
//! Example Output:
//! ```
//! counter = 31
//! ```
use crateasynchronous;
use Result;
use ;
use HashMap;
use ;
use broadcast;
use ;
static EventTypeRegistry: =
new;
/// Return the process-global [`EventChannel`] for event type `Type`, creating it
/// on first call.
///
/// Every call with the same `Type` returns the same `Arc<EventChannel<Type>>`, so
/// all senders and all subscribers share one broadcast bus per event type.
///
/// Subscriptions are managed internally by [`EventHandler`] — call
/// [`EventLoop::dispatch`] to register a handler rather than subscribing directly.
///
/// # Type parameters
///
/// - `Type` — the event payload. Must be [`Clone`] + [`Send`] + [`Sync`] + `'static`
/// because it is broadcast across threads.
///
/// # Returns
///
/// `Arc<`[`EventChannel`]`<Type>>` whose [`dispatch`](EventChannel::dispatch) method
/// publishes an event to every active subscriber.
///
/// # Example
///
/// ```no_run
/// use toys::event::{event, EventHandler, EventLoop};
/// use toys::asynchronous;
/// use std::sync::Arc;
///
/// pub enum Events {
/// Tick,
/// Tock,
/// }
///
/// struct Listener;
///
/// #[asynchronous]
/// impl EventHandler<Events> for Listener {
/// async fn handle(self: Arc<Self>, event: Events) {
/// match event {
/// Events::Tick => println!("tick"),
/// Events::Tock => println!("tock"),
/// }
/// }
/// }
///
/// # tokio_test::block_on(async {
/// let listener = Arc::new(Listener);
/// // if you dont clone listener, it moves it.
/// EventLoop::<Events>::new().dispatch(&[listener.clone()]).await;
///
/// event::<Events>().dispatch(Events::Tick).await.unwrap();
/// event::<Events>().dispatch(Events::Tock).await.unwrap();
/// # });
/// ```
///
/// Example Output:
/// ```
/// tick
/// tock
/// ```
/// Broadcast transport for a single event type.
///
/// `EventChannel<Type>` is the underlying message bus for one event type. It holds a
/// [`tokio::sync::broadcast`] sender with a fixed capacity of 64 messages and exposes
/// only the ability to publish — subscriptions are managed by [`EventHandler`].
///
/// Obtain an instance via [`event::<Type>()`](event), which guarantees at most one
/// channel per type for the lifetime of the process.
/// Implemented by types that react to events of type `Type`.
///
/// Apply [`#[asynchronous]`](crate::asynchronous) to the `impl` block so the
/// `async fn handle` signature is correctly transformed. Then register an `Arc` of
/// your type with [`EventLoop::dispatch`] to start receiving events.
///
/// The trait provides a default `_generate` method that wires the subscription and
/// spawns a background receive task; you only need to implement [`handle`](Self::handle).
///
/// # Type parameters
///
/// - `Type` — the event enum or struct this handler reacts to.
///
/// # Example
///
/// ```no_run
/// use toys::event::{event, EventHandler, EventLoop};
/// use toys::asynchronous;
/// use std::sync::Arc;
///
/// pub enum Cmd { Greet(String) }
///
/// struct Greeter;
///
/// #[asynchronous]
/// impl EventHandler<Cmd> for Greeter {
/// async fn handle(self: Arc<Self>, event: Cmd) {
/// if let Cmd::Greet(name) = event {
/// println!("Hello, {name}!");
/// }
/// }
/// }
///
/// # tokio_test::block_on(async {
/// let g = Arc::new(Greeter) as Arc<dyn EventHandler<Cmd>>;
/// EventLoop::<Cmd>::new().dispatch(&[g]).await;
/// event::<Cmd>().dispatch(Cmd::Greet("world".into())).await.unwrap();
/// # });
/// ```
/// Registers [`EventHandler`] implementations and starts their background receive tasks.
///
/// `EventLoop<Type>` is the entry point for wiring one or more handlers into the
/// global event bus for a given event type. Each call to [`dispatch`](Self::dispatch)
/// spawns one Tokio task per handler; those tasks run until a quit signal is sent or
/// the program exits.
///
/// # Type parameters
///
/// - `Type` — the event type shared by all handlers registered with this loop.
///
/// # Example
///
/// ```no_run
/// use toys::event::{event, EventHandler, EventLoop};
/// use toys::asynchronous;
/// use std::sync::Arc;
///
/// pub enum Job { Run }
///
/// struct Worker;
///
/// #[asynchronous]
/// impl EventHandler<Job> for Worker {
/// async fn handle(self: Arc<Self>, _event: Job) {
/// println!("working");
/// }
/// }
///
/// # tokio_test::block_on(async {
/// let w = Arc::new(Worker) as Arc<dyn EventHandler<Job>>;
/// let handles = EventLoop::<Job>::new().dispatch(&[w]).await;
///
/// event::<Job>().dispatch(Job::Run).await.unwrap();
///
/// // graceful shutdown
/// handles[0].1.send(()).unwrap();
/// handles[0].0.await.unwrap().unwrap();
/// # });
/// ```