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
//! Handler executor: inventory dispatch loop for `#[photon::subscribe]` handlers.
//!
//! [`ExecutorController::start`] is invoked by [`Photon::start_executor`]. It auto-discovers
//! [`photon_backend::HandlerDescriptor`] entries submitted by the proc macro, subscribes to each
//! topic with durable checkpoint replay, and dispatches through [`photon_core::IdentityFactory`].
//!
//! Call [`ExecutorController::shutdown`] then [`ExecutorController::join`] for graceful teardown.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use futures::StreamExt;
use photon_backend::{
consumer_group::instance_id_from_env,
consumer_group::static_assigned_shards,
consumer_group::{ConsumerGroupCoordinator, GroupMember, StaticGroupCoordinator},
delivery::DlqRecordParams,
delivery_mode::ShardConfig,
instrumentation::FailureReason,
HandlerDescriptor, HandlerRegistry, PhotonError, Result,
};
use photon_core::IdentityFactory;
use tokio::task::{JoinHandle, JoinSet};
use tokio_util::sync::CancellationToken;
use crate::Photon;
/// Controls background handler dispatch tasks started by [`Photon::start_executor`].
pub struct ExecutorController {
started: AtomicBool,
cancel: CancellationToken,
tasks: std::sync::Mutex<Vec<JoinHandle<()>>>,
}
impl Default for ExecutorController {
fn default() -> Self {
Self {
started: AtomicBool::new(false),
cancel: CancellationToken::new(),
tasks: std::sync::Mutex::new(Vec::new()),
}
}
}
impl ExecutorController {
/// Spawn subscription loops for every inventory-registered handler.
///
/// # Panics
///
/// Panics if an internal lock is poisoned.
///
/// # Errors
///
/// Returns an error if the executor was already started on this controller.
///
/// # Contract
///
/// - Start is one-shot per controller; restart requires a new [`Photon`] build.
/// - Outer loops respect [`Self::shutdown`]; in-flight handler tasks are awaited in
/// [`Self::join`].
pub fn start(
&self,
photon: &Photon,
identity: &Arc<dyn IdentityFactory>,
) -> Result<()> {
if self
.started
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
return Err(PhotonError::Internal(
"Photon executor already started".into(),
));
}
let registry = HandlerRegistry::auto_discover();
if registry.is_empty() {
return Ok(());
}
let mut tasks = Vec::new();
for handler in registry.iter() {
let cancel = self.cancel.child_token();
let task = if handler.is_consumer_group() {
spawn_group_handler_loop(photon.clone(), Arc::clone(identity), handler, cancel)
} else {
spawn_handler_loop(photon.clone(), Arc::clone(identity), handler, cancel)
};
tasks.push(task);
}
*self.tasks.lock().unwrap() = tasks;
Ok(())
}
/// Signal all handler loops to stop accepting new events.
///
/// # Contract
///
/// - Idempotent: repeated calls are no-ops.
/// - Does not wait for in-flight handlers; call [`Self::join`] afterward.
pub fn shutdown(&self) {
self.cancel.cancel();
}
/// Await outer subscription loops (and their in-flight handler tasks).
///
/// # Contract
///
/// - Call [`Self::shutdown`] first for prompt exit from stream loops.
/// - Drains stored outer [`JoinHandle`]s; each loop drains its own in-flight [`JoinSet`]
/// before exiting.
/// - Safe to call when no tasks were started (no-op).
///
/// # Panics
///
/// Panics if an internal lock is poisoned.
pub async fn join(&self) {
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
for task in tasks {
let _ = task.await;
}
}
}
const fn failure_reason(err: &PhotonError) -> FailureReason {
match err {
PhotonError::Identity(_) => FailureReason::IdentityBuild,
_ => FailureReason::HandlerError,
}
}
fn shard_count_for_handler(photon: &Photon, handler: &'static HandlerDescriptor) -> u32 {
handler
.group_shard_count
.or_else(|| {
photon
.registry()
.get(handler.topic_name)
.and_then(|d| d.shard_config)
.map(|c| c.shard_count)
})
.unwrap_or(ShardConfig::DEFAULT_SHARD_COUNT)
}
fn spawn_group_handler_loop(
photon: Photon,
identity: Arc<dyn IdentityFactory>,
handler: &'static HandlerDescriptor,
cancel: CancellationToken,
) -> JoinHandle<()> {
let topic = handler.topic_name;
let group_id = handler.consumer_group.unwrap_or("");
let invoke = handler.invoke;
let services = Arc::clone(&photon.runtime().executor_services);
let coordinator = StaticGroupCoordinator;
tokio::spawn(async move {
let shard_count = shard_count_for_handler(&photon, handler);
let instance_id = instance_id_from_env().unwrap_or_else(|| "0".into());
let assigned = coordinator
.register(GroupMember {
group_id: group_id.to_string(),
instance_id: instance_id.clone(),
topic_name: topic.to_string(),
shard_count,
})
.await
.unwrap_or_else(|_| static_assigned_shards(shard_count));
let mut after_seq_by_shard = HashMap::new();
for shard_id in &assigned {
let shard_key = photon_backend::shard_storage_key(*shard_id);
let seq = photon
.get_checkpoint_seq(group_id, topic, Some(&shard_key))
.await
.ok()
.flatten()
.unwrap_or(0);
after_seq_by_shard.insert(*shard_id, Some(seq));
}
let mut stream =
photon.subscribe_consumer_group(topic, &assigned, after_seq_by_shard);
let mut inflight = JoinSet::new();
loop {
tokio::select! {
biased;
() = cancel.cancelled() => break,
event_result = stream.next() => {
let Some(event_result) = event_result else { break };
match event_result {
Ok(event) => {
let permit = services.worker_pool.acquire().await;
let identity = Arc::clone(&identity);
let services = Arc::clone(&services);
let group = group_id.to_string();
inflight.spawn(async move {
let _permit = permit;
let event_id = event.event_id.clone();
let topic_name = event.topic_name.clone();
let topic_key = event.topic_key.clone();
let seq = event.seq;
let dispatch = invoke(identity.as_ref(), &event);
match dispatch.await {
Ok(()) => {
if let Err(e) = services
.checkpoint_coalescer
.record(&group, &topic_name, topic_key.as_deref(), seq)
.await
{
let _ = services.dlq.record(&DlqRecordParams {
event_id: &event_id,
topic_name: &topic_name,
topic_key: topic_key.as_deref(),
seq,
subscription_name: Some(&group),
reason: FailureReason::CheckpointError,
error: e.to_string(),
});
}
}
Err(e) => {
let _ = services.dlq.record(&DlqRecordParams {
event_id: &event_id,
topic_name: &topic_name,
topic_key: topic_key.as_deref(),
seq,
subscription_name: Some(&group),
reason: failure_reason(&e),
error: e.to_string(),
});
}
}
});
}
Err(e) => {
tracing::warn!(
topic = topic,
group = group_id,
error = %e,
"consumer group subscription stream error"
);
}
}
}
}
}
while inflight.join_next().await.is_some() {}
})
}
fn spawn_handler_loop(
photon: Photon,
identity: Arc<dyn IdentityFactory>,
handler: &'static HandlerDescriptor,
cancel: CancellationToken,
) -> JoinHandle<()> {
let topic = handler.topic_name;
let subscription_name = handler.subscription_name;
let invoke = handler.invoke;
let services = Arc::clone(&photon.runtime().executor_services);
tokio::spawn(async move {
// Durable handlers always replay from a cursor. Missing checkpoint → start at 0
// (not live-only `None`), so publishes that land before the subscribe handshake
// are still delivered from storage.
let after_seq = Some(
photon
.get_checkpoint_seq(subscription_name, topic, None)
.await
.ok()
.flatten()
.unwrap_or(0),
);
let mut stream = photon.subscribe(topic, None, after_seq);
let mut inflight = JoinSet::new();
loop {
tokio::select! {
biased;
() = cancel.cancelled() => break,
event_result = stream.next() => {
let Some(event_result) = event_result else { break };
match event_result {
Ok(event) => {
let permit = services.worker_pool.acquire().await;
let identity = Arc::clone(&identity);
let services = Arc::clone(&services);
let sub_name = subscription_name.to_string();
inflight.spawn(async move {
let _permit = permit;
let event_id = event.event_id.clone();
let topic_name = event.topic_name.clone();
let topic_key = event.topic_key.clone();
let seq = event.seq;
let dispatch = invoke(identity.as_ref(), &event);
match dispatch.await {
Ok(()) => {
if let Err(e) = services
.checkpoint_coalescer
.record(&sub_name, &topic_name, topic_key.as_deref(), seq)
.await
{
let _ = services.dlq.record(&DlqRecordParams {
event_id: &event_id,
topic_name: &topic_name,
topic_key: topic_key.as_deref(),
seq,
subscription_name: Some(&sub_name),
reason: FailureReason::CheckpointError,
error: e.to_string(),
});
}
}
Err(e) => {
let _ = services.dlq.record(&DlqRecordParams {
event_id: &event_id,
topic_name: &topic_name,
topic_key: topic_key.as_deref(),
seq,
subscription_name: Some(&sub_name),
reason: failure_reason(&e),
error: e.to_string(),
});
}
}
});
}
Err(e) => {
tracing::warn!(
topic = topic,
subscription = subscription_name,
error = %e,
"handler subscription stream error"
);
}
}
}
}
}
while inflight.join_next().await.is_some() {}
})
}