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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! # Messaging Thread Pool
//!
//! A typed thread pool library for managing stateful, long-lived objects that communicate
//! via messages. Unlike traditional thread pools, objects in this pool are **pinned to their
//! assigned thread** for their entire lifetime, enabling the use of non-`Send`/`Sync` types
//! like `Rc<RefCell<T>>`.
//!
//! ## When to Use This Library
//!
//! Use `messaging_thread_pool` when you need:
//! - **Thread-bound state**: Objects that own `Rc`, `RefCell`, raw pointers, or FFI resources
//! - **Actor-like patterns**: Long-lived stateful objects with message-based APIs
//! - **Sequential consistency**: Messages to the same object processed in order, no races
//! - **Lock-free operations**: No `Mutex`/`RwLock` needed since each object has single-threaded access
//!
//! If your data is `Send + Sync` and you just need parallel computation, consider [`rayon`](https://docs.rs/rayon)
//! instead.
//!
//! ## Quick Start
//!
//! The recommended approach uses the `#[pool_item]` attribute macro to minimize boilerplate:
//!
//! ```rust
//! use messaging_thread_pool::{ThreadPool, IdTargeted, pool_item};
//!
//! // 1. Define your struct with an ID field
//! #[derive(Debug)]
//! pub struct Counter {
//! id: u64,
//! value: i64,
//! }
//!
//! impl IdTargeted for Counter {
//! fn id(&self) -> u64 { self.id }
//! }
//!
//! // 2. Use #[pool_item] on the impl block and #[messaging] on methods
//! #[pool_item]
//! impl Counter {
//! pub fn new(id: u64) -> Self {
//! Self { id, value: 0 }
//! }
//!
//! #[messaging(IncrementRequest, IncrementResponse)]
//! pub fn increment(&mut self, amount: i64) -> i64 {
//! self.value += amount;
//! self.value
//! }
//!
//! #[messaging(GetValueRequest, GetValueResponse)]
//! pub fn get_value(&self) -> i64 {
//! self.value
//! }
//! }
//!
//! // 3. Create a thread pool and interact with pool items
//! let pool = ThreadPool::<Counter>::new(4);
//!
//! // Create a counter with ID 1
//! pool.send_and_receive_once(CounterInit(1)).expect("pool available");
//!
//! // Increment it
//! let response: IncrementResponse = pool
//! .send_and_receive_once(IncrementRequest(1, 10))
//! .expect("pool available");
//! assert_eq!(response.result, 10);
//!
//! // Get current value
//! let response: GetValueResponse = pool
//! .send_and_receive_once(GetValueRequest(1))
//! .expect("pool available");
//! assert_eq!(response.result, 10);
//! ```
//!
//! ## Key Concepts
//!
//! ### Pool Items
//!
//! A **pool item** is any struct that implements the [`PoolItem`] trait. Each pool item:
//! - Has a unique `u64` ID within the pool
//! - Lives on a single thread (determined by `id % thread_count`)
//! - Receives messages sequentially via its `process_message` method
//!
//! The `#[pool_item]` macro generates the [`PoolItem`] implementation for you.
//!
//! ### Messages
//!
//! Communication with pool items happens through **request/response messages**:
//! - Each method marked with `#[messaging(RequestType, ResponseType)]` becomes a message endpoint
//! - The macro generates the request struct (with ID + method parameters) and response struct
//! - Messages are routed to the correct thread based on the target ID
//!
//! ### Thread Affinity
//!
//! Pool items are distributed across threads using `id % thread_count`. All messages
//! targeting the same ID go to the same thread, ensuring:
//! - No concurrent access to the same pool item
//! - Consistent ordering of message processing
//! - Warm CPU caches for frequently accessed items
//!
//! ## Using Non-Send/Sync Types
//!
//! The main advantage of this library is supporting thread-bound types. Here's an example
//! using `Rc<RefCell<T>>` for shared internal state:
//!
//! ```rust
//! use std::cell::RefCell;
//! use std::rc::Rc;
//! use messaging_thread_pool::{ThreadPool, IdTargeted, pool_item};
//!
//! #[derive(Debug, Clone)]
//! struct Helper {
//! data: Rc<RefCell<Vec<String>>>,
//! }
//!
//! #[derive(Debug)]
//! pub struct Session {
//! id: u64,
//! data: Rc<RefCell<Vec<String>>>,
//! helper: Helper,
//! }
//!
//! impl IdTargeted for Session {
//! fn id(&self) -> u64 { self.id }
//! }
//!
//! #[pool_item]
//! impl Session {
//! pub fn new(id: u64) -> Self {
//! let data = Rc::new(RefCell::new(Vec::new()));
//! let helper = Helper { data: data.clone() };
//! Self { id, data, helper }
//! }
//!
//! #[messaging(AddRequest, AddResponse)]
//! pub fn add(&self, item: String) {
//! // No locks needed - just borrow_mut!
//! self.helper.data.borrow_mut().push(item);
//! }
//! }
//! ```
//!
//! See [`samples::UserSession`] for a complete working example.
//!
//! ## Batch Operations
//!
//! For efficiency, send multiple requests at once using [`ThreadPool::send_and_receive`]:
//!
//! ```rust
//! # use messaging_thread_pool::{ThreadPool, samples::*};
//! let pool = ThreadPool::<Randoms>::new(4);
//!
//! // Create 100 items in parallel
//! pool.send_and_receive((0..100u64).map(RandomsAddRequest))
//! .expect("pool available")
//! .for_each(|response| assert!(response.result().is_ok()));
//!
//! // Query all of them
//! let sums: Vec<u128> = pool
//! .send_and_receive((0..100u64).map(SumRequest))
//! .expect("pool available")
//! .map(|r| r.sum())
//! .collect();
//! ```
//!
//! ## Testing with Mocks
//!
//! The [`SenderAndReceiver`] trait allows mocking the thread pool in tests:
//!
//! ```rust
//! use messaging_thread_pool::{SenderAndReceiver, SenderAndReceiverMock, samples::*};
//!
//! // Code that depends on a thread pool takes a generic parameter
//! fn sum_means<T: SenderAndReceiver<Randoms>>(pool: &T, ids: &[u64]) -> u128 {
//! pool.send_and_receive(ids.iter().map(|id| MeanRequest(*id)))
//! .expect("pool available")
//! .map(|r: MeanResponse| r.mean())
//! .sum()
//! }
//!
//! // In tests, use SenderAndReceiverMock
//! let mock = SenderAndReceiverMock::<Randoms, MeanRequest>::new_with_expected_requests(
//! vec![MeanRequest(1), MeanRequest(2)],
//! vec![
//! MeanResponse { id: 1, result: 100 },
//! MeanResponse { id: 2, result: 200 },
//! ],
//! );
//!
//! assert_eq!(sum_means(&mock, &[1, 2]), 300);
//! ```
//!
//! See [`samples`] for more comprehensive examples, and [`SenderAndReceiverMock`] for
//! mock configuration options.
//!
//! ## The `#[pool_item]` Macro
//!
//! The macro accepts optional parameters:
//!
//! ```rust,ignore
//! // Custom initialization request type (for complex constructors)
//! #[pool_item(Init = "MyCustomInitRequest")]
//!
//! // Custom shutdown handler
//! #[pool_item(Shutdown = "my_shutdown_method")]
//!
//! // Both
//! #[pool_item(Init = "MyCustomInitRequest", Shutdown = "my_shutdown_method")]
//! ```
//!
//! For details, see the macro documentation in [`macro@pool_item`].
//!
//! ## Legacy API
//!
//! The [`api_specification!`] macro is the older way to define pool items. New code should
//! use `#[pool_item]` instead, which is simpler and generates less boilerplate.
//!
//! ## Performance Considerations
//!
//! The message-passing overhead becomes significant for very short operations (<50ms).
//! This library is best suited for:
//! - CPU-bound work with moderate to long execution times
//! - Operations where thread affinity improves cache locality
//! - Stateful objects that would otherwise require complex locking
//!
//! ## Module Overview
//!
//! - [`ThreadPool`] - The main entry point for creating and managing pools
//! - [`PoolItem`] - Trait implemented by types managed in the pool
//! - [`IdTargeted`] - Trait for types that have an ID for routing
//! - [`SenderAndReceiver`] - Trait for abstracting pool communication (enables mocking)
//! - [`samples`] - Example implementations to learn from
//! - [`id_provider`] - Utilities for generating unique IDs
extern crate self as messaging_thread_pool;
use crateThreadEndpoint;
use RefCell;
use RwLock;
pub use pool_item;
pub use *;
pub use *;
pub use IdTargeted;
pub use *;
pub use RequestResponse;
pub use RequestWithResponse;
pub use *;
pub use *;
pub use *;
thread_local!
/// A pool of threads for managing stateful [`PoolItem`] instances.
///
/// `ThreadPool` is the main entry point for this library. It:
/// - Spawns a fixed number of worker threads
/// - Distributes pool items across threads based on their IDs
/// - Routes messages to the correct thread for processing
/// - Ensures sequential message processing per pool item (no concurrent access)
///
/// # Creating a Thread Pool
///
/// ```rust
/// use messaging_thread_pool::{ThreadPool, samples::Randoms};
///
/// // Create a pool with 4 worker threads
/// let pool = ThreadPool::<Randoms>::new(4);
///
/// // The pool is now ready to accept messages
/// assert_eq!(pool.thread_count(), 4);
/// ```
///
/// # Creating Pool Items
///
/// Pool items are created by sending initialization requests:
///
/// ```rust
/// use messaging_thread_pool::{ThreadPool, samples::*};
///
/// let pool = ThreadPool::<Randoms>::new(4);
///
/// // Create a single item with ID 0
/// pool.send_and_receive_once(RandomsAddRequest(0)).expect("pool available");
///
/// // Or create many at once (IDs 1-99, since 0 already exists)
/// pool.send_and_receive((1..100u64).map(RandomsAddRequest))
/// .expect("pool available")
/// .for_each(|response| assert!(response.result().is_ok()));
/// ```
///
/// # Sending Messages
///
/// Once items exist, send messages to interact with them:
///
/// ```rust
/// use messaging_thread_pool::{ThreadPool, samples::*};
///
/// let pool = ThreadPool::<Randoms>::new(4);
/// pool.send_and_receive_once(RandomsAddRequest(1)).expect("pool available");
///
/// // Send a single message
/// let response: MeanResponse = pool
/// .send_and_receive_once(MeanRequest(1))
/// .expect("pool available");
///
/// // Send multiple messages (processed in parallel across threads)
/// // First create items 0-9
/// pool.send_and_receive((0..10u64).filter(|id| *id != 1).map(RandomsAddRequest))
/// .expect("pool available")
/// .for_each(|_| {});
/// let responses: Vec<SumResponse> = pool
/// .send_and_receive((0..10u64).map(SumRequest))
/// .expect("pool available")
/// .collect();
/// ```
///
/// # Removing Items
///
/// Items can be removed explicitly:
///
/// ```rust
/// use messaging_thread_pool::{ThreadPool, samples::*, RemovePoolItemRequest};
///
/// let pool = ThreadPool::<Randoms>::new(4);
/// pool.send_and_receive_once(RandomsAddRequest(1)).expect("pool available");
///
/// let response = pool
/// .send_and_receive_once(RemovePoolItemRequest(1))
/// .expect("pool available");
/// assert!(response.item_existed());
/// ```
///
/// # Shutdown
///
/// The pool shuts down automatically when dropped, or explicitly via [`shutdown`](Self::shutdown):
///
/// ```rust
/// use messaging_thread_pool::{ThreadPool, samples::Randoms};
///
/// let pool = ThreadPool::<Randoms>::new(4);
/// // ... use the pool ...
///
/// // Explicit shutdown (returns shutdown responses from items)
/// let responses = pool.shutdown();
///
/// // Or just drop it (implicit shutdown)
/// // drop(pool);
/// ```
///
/// # Thread Distribution
///
/// Items are assigned to threads using `id % thread_count`. All messages for the same
/// ID go to the same thread. This ensures:
/// - No concurrent access to the same pool item
/// - Sequential message ordering per item
/// - Predictable data locality
///
/// # Thread Safety
///
/// `ThreadPool` is `Send + Sync` and implements [`SenderAndReceiver`], making it
/// suitable for:
/// - Sharing across multiple threads (e.g., via `Arc<ThreadPool<P>>`)
/// - Use in async contexts
/// - Nested thread pool patterns (see [`samples::RandomsBatch`])