bombay-entity 0.1.0

Local entity activation, lifecycle management, and stable typed routing.
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Concise asynchronous API over the local entity directory.

use std::mem;
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};
use std::task::{Context, Poll, Waker};

use crate::{
    ActivationId, DirectoryConfig, DirectoryError, DispatchId, DrainFailure, DrainStage,
    EffectInterpreter, EntityId, LifecyclePhase, LocalDirectory, Refusal, RetirementMode,
    TransitionEvidence,
};

/// Exact-incarnation capabilities returned by transactional activation.
pub struct Activated<E, L> {
    /// Delivery-only capability.
    pub endpoint: E,
    /// Affine retirement capability.
    pub lease: L,
}

/// Stage at which an ordered fence operation failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum FenceFailure {
    /// The fence was not enqueued.
    #[error("fence was not enqueued")]
    Enqueue,
    /// The fence was enqueued but not acknowledged.
    #[error("fence was enqueued but not acknowledged")]
    Acknowledgement,
}

/// Outcome of one [`EntityRuntime::passivate`] call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Passivation {
    /// Admission was closed at this call's lifecycle linearization point.
    Begun,
    /// No active incarnation exists to passivate.
    NotActive,
    /// A passivation was already in progress for the exact incarnation.
    AlreadyPassivating,
    /// The observed incarnation was superseded before the drain linearized.
    Superseded,
}

/// Runtime port implemented once by an actor runtime integration.
///
/// Actorpass can implement this port without exposing its addresses or
/// provisional activation types through the stable entity API.
pub trait LocalEntityRuntime<I, C>: Send + Sync + 'static {
    /// Cloneable exact-incarnation delivery capability.
    type Endpoint: Clone + Send + Sync + 'static;
    /// Affine exact-incarnation retirement capability.
    type Lease: Send + 'static;
    /// Transactional activation failure.
    type ActivationError: Send + 'static;

    /// Spawn work owned by the entity directory rather than a caller.
    ///
    /// The spawned task MUST be driven to completion: every lifecycle task
    /// ends by submitting its typed fact back through the directory. Dropping
    /// or canceling a task strands the entity — an activation task wedges the
    /// slot in `Activating`, a delivery task wedges a drain, and a retirement
    /// task leaks the directory entry.
    fn spawn(&self, task: impl Future<Output = ()> + Send + 'static);

    /// Prepare and transactionally activate an exact incarnation.
    fn activate(
        &self,
        entity_id: EntityId<I>,
        activation_id: ActivationId,
    ) -> impl Future<Output = Result<Activated<Self::Endpoint, Self::Lease>, Self::ActivationError>> + Send;

    /// Enqueue a command, returning ownership on failure.
    fn deliver(
        &self,
        endpoint: Self::Endpoint,
        command: C,
    ) -> impl Future<Output = Result<(), C>> + Send;

    /// Enqueue and await acknowledgement of an ordered processing fence.
    fn fence(
        &self,
        endpoint: Self::Endpoint,
    ) -> impl Future<Output = Result<(), FenceFailure>> + Send;

    /// Retire and await exact termination of one incarnation.
    fn retire(
        &self,
        lease: Self::Lease,
        retirement: RetirementMode,
    ) -> impl Future<Output = ()> + Send;
}

/// Failure from [`EntityRuntime::dispatch`] with command ownership preserved.
#[derive(Debug, thiserror::Error)]
pub enum DispatchFailure<C> {
    /// Lifecycle admission or delivery refused the command.
    #[error("lifecycle admission or delivery refused the command")]
    Refused {
        /// Original command.
        command: C,
        /// Exact refusal classification.
        reason: Refusal,
    },
    /// The non-reusable activation identity namespace is exhausted.
    #[error("activation identity namespace is exhausted")]
    ActivationIdsExhausted(C),
    /// The non-reusable dispatch identity namespace is exhausted.
    #[error("dispatch identity namespace is exhausted")]
    DispatchIdsExhausted(C),
}

struct PendingCommand<C> {
    command: C,
    completion: Arc<Completion<C>>,
}

struct Completion<C>(Mutex<CompletionState<C>>);

enum CompletionState<C> {
    Awaiting { waker: Option<Waker> },
    Ready(Result<(), DispatchFailure<C>>),
    Consumed,
}

impl<C> Completion<C> {
    fn new() -> Self {
        Self(Mutex::new(CompletionState::Awaiting { waker: None }))
    }

    fn complete(&self, result: Result<(), DispatchFailure<C>>) {
        let waker = {
            let mut state = self.0.lock().expect("completion lock poisoned");
            match &mut *state {
                CompletionState::Awaiting { .. } => {
                    match mem::replace(&mut *state, CompletionState::Ready(result)) {
                        CompletionState::Awaiting { waker } => waker,
                        _ => None,
                    }
                }
                CompletionState::Ready(_) | CompletionState::Consumed => return,
            }
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }

    /// Take the delivered result, or register the waker while still awaiting.
    fn poll_take(&self, waker: &Waker) -> Option<Result<(), DispatchFailure<C>>> {
        let mut state = self.0.lock().expect("completion lock poisoned");
        match &mut *state {
            CompletionState::Ready(_) => {
                match mem::replace(&mut *state, CompletionState::Consumed) {
                    CompletionState::Ready(result) => Some(result),
                    _ => None,
                }
            }
            CompletionState::Awaiting { waker: stored } => {
                *stored = Some(waker.clone());
                None
            }
            CompletionState::Consumed => None,
        }
    }

    /// Whether a delivered result was already consumed by the waiter.
    fn is_consumed(&self) -> bool {
        matches!(
            *self.0.lock().expect("completion lock poisoned"),
            CompletionState::Consumed
        )
    }
}

/// Local stable-routing facade used by applications.
pub struct EntityRuntime<I, C, R>
where
    R: LocalEntityRuntime<I, C>,
{
    inner: Arc<Runtime<I, C, R>>,
}

struct Runtime<I, C, R>
where
    R: LocalEntityRuntime<I, C>,
{
    directory: LocalDirectory<I, PendingCommand<C>, R::Endpoint, R::Lease>,
    actor_runtime: R,
}

impl<I, C, R> Clone for EntityRuntime<I, C, R>
where
    R: LocalEntityRuntime<I, C>,
{
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<I, C, R> EntityRuntime<I, C, R>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
    /// Construct stable local entity routing over an actor-runtime port.
    ///
    /// # Errors
    ///
    /// Returns [`DirectoryError::InvalidShardCount`] for a shard count that is
    /// not a power of two.
    pub fn new(config: DirectoryConfig, actor_runtime: R) -> Result<Self, DirectoryError<C>> {
        let directory =
            LocalDirectory::new(config).map_err(|error: DirectoryError<PendingCommand<C>>| {
                match error {
                    DirectoryError::InvalidShardCount => DirectoryError::InvalidShardCount,
                    DirectoryError::ActivationIdsExhausted(pending) => {
                        DirectoryError::ActivationIdsExhausted(pending.command)
                    }
                    DirectoryError::DispatchIdsExhausted(pending) => {
                        DirectoryError::DispatchIdsExhausted(pending.command)
                    }
                }
            })?;
        Ok(Self {
            inner: Arc::new(Runtime {
                directory,
                actor_runtime,
            }),
        })
    }

    /// Deliver a command through stable entity routing.
    ///
    /// Dropping this future cancels its command only while it remains a bounded
    /// activation waiter. The shared activation task remains directory-owned,
    /// and a command already moved into active delivery is not retracted.
    ///
    /// # Errors
    ///
    /// Returns a typed refusal or exhausted identity namespace with the
    /// original command.
    ///
    /// # Panics
    ///
    /// Panics after synchronization poison or violation of an internal
    /// directory identity invariant.
    pub async fn dispatch(
        &self,
        entity_id: EntityId<I>,
        command: C,
    ) -> Result<(), DispatchFailure<C>> {
        let completion = Arc::new(Completion::new());
        let pending = PendingCommand {
            command,
            completion: Arc::clone(&completion),
        };
        let dispatched = self
            .inner
            .directory
            .dispatch(entity_id.clone(), pending)
            .map_err(|error| match error {
                DirectoryError::InvalidShardCount => unreachable!("configuration was validated"),
                DirectoryError::ActivationIdsExhausted(pending) => {
                    DispatchFailure::ActivationIdsExhausted(pending.command)
                }
                DirectoryError::DispatchIdsExhausted(pending) => {
                    DispatchFailure::DispatchIdsExhausted(pending.command)
                }
            })?;
        let dispatch_id = dispatched.dispatch_id;
        let activation_id = dispatched.output.activation_id;
        self.inner
            .directory
            .interpret(dispatched.output, &self.inner);
        DispatchWait {
            completion,
            entity_id,
            activation_id,
            dispatch_id,
            runtime: Arc::downgrade(&self.inner),
        }
        .await
    }

    /// Begin graceful passivation if the entity currently has an active incarnation.
    ///
    /// Admission closes at this call's lifecycle linearization point. Fence and
    /// retirement work continues in directory-owned tasks.
    ///
    /// # Panics
    ///
    /// Panics if directory synchronization was poisoned.
    pub fn passivate(&self, entity_id: &EntityId<I>) -> Passivation {
        let Some(activation_id) = self.inner.directory.current_activation(entity_id) else {
            return Passivation::NotActive;
        };
        let output = self.inner.directory.begin_drain(entity_id, activation_id);
        let passivation = match output.evidence {
            TransitionEvidence::Traversed(_) => Passivation::Begun,
            TransitionEvidence::SelfLoop { phase, .. }
            | TransitionEvidence::Ignored { phase, .. } => match phase {
                LifecyclePhase::Active => Passivation::Superseded,
                LifecyclePhase::Draining | LifecyclePhase::Retiring => {
                    Passivation::AlreadyPassivating
                }
                LifecyclePhase::Inactive | LifecyclePhase::Activating => Passivation::NotActive,
            },
        };
        self.inner.directory.interpret(output, &self.inner);
        passivation
    }
}

struct DispatchWait<I, C, R>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
    completion: Arc<Completion<C>>,
    entity_id: EntityId<I>,
    activation_id: Option<ActivationId>,
    dispatch_id: DispatchId,
    runtime: Weak<Runtime<I, C, R>>,
}

impl<I, C, R> Unpin for DispatchWait<I, C, R>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
}

impl<I, C, R> Future for DispatchWait<I, C, R>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
    type Output = Result<(), DispatchFailure<C>>;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        match self.completion.poll_take(context.waker()) {
            Some(result) => Poll::Ready(result),
            None => Poll::Pending,
        }
    }
}

impl<I, C, R> Drop for DispatchWait<I, C, R>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
    fn drop(&mut self) {
        if self.completion.is_consumed() {
            return;
        }
        if let Some(runtime) = self.runtime.upgrade()
            && let Some(activation_id) = self.activation_id
        {
            let output =
                runtime
                    .directory
                    .cancel_waiter(&self.entity_id, activation_id, self.dispatch_id);
            runtime.directory.interpret(output, &runtime);
        }
    }
}

impl<I, C, R> EffectInterpreter<I, PendingCommand<C>, R::Endpoint, R::Lease>
    for Arc<Runtime<I, C, R>>
where
    I: Clone + Eq + std::hash::Hash + Send + Sync + 'static,
    C: Send + 'static,
    R: LocalEntityRuntime<I, C>,
{
    fn start_activation(&self, entity_id: EntityId<I>, activation_id: ActivationId) {
        let runtime = Arc::clone(self);
        self.actor_runtime.spawn(async move {
            let result = runtime
                .actor_runtime
                .activate(entity_id.clone(), activation_id)
                .await;
            let output = match result {
                Ok(activated) => runtime.directory.activation_succeeded(
                    &entity_id,
                    activation_id,
                    activated.endpoint,
                    activated.lease,
                ),
                // The finalized lifecycle algebra consumes only the fact of
                // failure; the typed activation error is the actor runtime's
                // own diagnostic boundary and is deliberately not propagated.
                Err(_activation_error) => runtime
                    .directory
                    .activation_failed(&entity_id, activation_id),
            };
            runtime.directory.interpret(output, &runtime);
        });
    }

    fn deliver(
        &self,
        entity_id: EntityId<I>,
        activation_id: ActivationId,
        dispatch_id: DispatchId,
        endpoint: R::Endpoint,
        pending: PendingCommand<C>,
    ) {
        let runtime = Arc::clone(self);
        self.actor_runtime.spawn(async move {
            let completion = pending.completion;
            let failure = match runtime
                .actor_runtime
                .deliver(endpoint, pending.command)
                .await
            {
                Ok(()) => {
                    completion.complete(Ok(()));
                    None
                }
                Err(command) => Some((
                    dispatch_id,
                    PendingCommand {
                        command,
                        completion,
                    },
                )),
            };
            let output = runtime
                .directory
                .delivery_resolved(&entity_id, activation_id, failure);
            runtime.directory.interpret(output, &runtime);
        });
    }

    fn reject(&self, _: DispatchId, pending: PendingCommand<C>, reason: Refusal) {
        pending.completion.complete(Err(DispatchFailure::Refused {
            command: pending.command,
            reason,
        }));
    }

    fn enqueue_fence(
        &self,
        entity_id: EntityId<I>,
        activation_id: ActivationId,
        endpoint: R::Endpoint,
    ) {
        let runtime = Arc::clone(self);
        self.actor_runtime.spawn(async move {
            let output = match runtime.actor_runtime.fence(endpoint).await {
                Ok(()) => runtime
                    .directory
                    .fence_acknowledged(&entity_id, activation_id),
                Err(failure) => runtime.directory.force_drain(
                    &entity_id,
                    activation_id,
                    DrainFailure {
                        stage: match failure {
                            FenceFailure::Enqueue => DrainStage::FenceEnqueue,
                            FenceFailure::Acknowledgement => DrainStage::FenceAcknowledgement,
                        },
                        outstanding_reservations: 0,
                    },
                ),
            };
            runtime.directory.interpret(output, &runtime);
        });
    }

    fn retire(
        &self,
        entity_id: EntityId<I>,
        activation_id: ActivationId,
        lease: R::Lease,
        retirement: RetirementMode,
    ) {
        let runtime = Arc::clone(self);
        self.actor_runtime.spawn(async move {
            runtime.actor_runtime.retire(lease, retirement).await;
            let output = runtime.directory.terminated(&entity_id, activation_id);
            runtime.directory.interpret(output, &runtime);
        });
    }
}