Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
2 : : // SPDX-License-Identifier: Apache-2.0
3 : :
4 : : #include <hpactor/actor/lifecycle_actor.hpp>
5 : : #include <hpactor/types/types.hpp>
6 : :
7 : : namespace hpactor {
8 : :
9 : 0 : void LifecycleActor::on_fail(error /*err*/) {
10 : : // Default no-op; subclasses override for failure-specific cleanup
11 : 0 : }
12 : :
13 : 100 : bool LifecycleActor::transition(LifecycleState to) {
14 : 100 : LifecycleState from = state();
15 : :
16 : : // Validate that `to` is in this state's transition list
17 : 100 : const auto& def = kStateMachine[static_cast<int>(from)];
18 : 100 : bool legal = false;
19 : 121 : for (uint8_t i = 0; i < def.num_transitions; ++i) {
20 : 119 : if (def.transitions[i] == to) {
21 : 98 : legal = true;
22 : 98 : break;
23 : : }
24 : : }
25 : 100 : if (!legal)
26 : 2 : return false;
27 : :
28 : : // CAS: only change if still in `from`
29 : 98 : uint8_t expected = static_cast<uint8_t>(from);
30 : 98 : uint8_t desired = static_cast<uint8_t>(to);
31 : 196 : if (!state_.compare_exchange_strong(expected, desired, std::memory_order_acq_rel,
32 : : std::memory_order_acquire)) {
33 : 0 : return false;
34 : : }
35 : :
36 : : // Post-transition: invoke the hook for this transition.
37 : : // on_fail() uses the stored failure_reason_ (set by caller before
38 : : // transition).
39 : 98 : if (to == LifecycleState::kActive && (from == LifecycleState::kStarting ||
40 : : from == LifecycleState::kRecovering)) {
41 : 37 : on_start();
42 : 61 : } else if (to == LifecycleState::kDraining) {
43 : 17 : on_drain();
44 : 44 : } else if (to == LifecycleState::kStopping) {
45 : 20 : on_stop();
46 : 24 : } else if (to == LifecycleState::kStopped) {
47 : 20 : on_deactivate();
48 : 4 : } else if (to == LifecycleState::kFailed) {
49 : 2 : on_fail(failure_reason_);
50 : 2 : } else if (to == LifecycleState::kStarting &&
51 : 0 : (from == LifecycleState::kFailed || from == LifecycleState::kStopped)) {
52 : 1 : on_restart();
53 : 1 : } else if (to == LifecycleState::kRecovering) {
54 : 1 : on_recover();
55 : : }
56 : :
57 : 98 : return true;
58 : : }
59 : :
60 : : } // namespace hpactor
|