feat(service): immutable snapshots, owning ServiceHandle, DAG lifecycle, and ServicePlugin split

This commit is contained in:
faumaray committed 2026-11-26 16:03:31 +03:00
1 parent 6b3dededac
commit 1474a69ab1
12 files changed
+2167 -137

No files matched your search

+944
View File
@@ -0,0 +1,944 @@
#include <Void/Service/Registry.hpp>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <exception>
#include <functional>
#include <queue>
#include <string_view>
#include <unordered_set>
namespace Void::Service
{
namespace detail
{
struct RetentionState {
mutable std::mutex mu{};
std::condition_variable cv{};
std::vector<RetentionEntry> entries{};
void notify_release() noexcept
{
std::lock_guard lk{mu};
cv.notify_all();
}
};
namespace
{
struct TokenGuard {
std::weak_ptr<RetentionState> state{};
~TokenGuard()
{
if (auto s = state.lock()) {
s->notify_release();
}
}
};
std::shared_ptr<const void>
make_retention_token(const std::shared_ptr<RetentionState>& state,
PublicationEpoch epoch,
std::string label)
{
auto tok = std::make_shared<TokenGuard>(TokenGuard{state});
{
std::lock_guard lk{state->mu};
std::erase_if(state->entries, [](const RetentionEntry& e) {
return e.token.expired();
});
state->entries.push_back(
RetentionEntry{epoch, tok, std::move(label)});
}
return tok;
}
bool has_in_parent_chain(const SnapshotData& snap,
std::type_index key,
std::size_t max_levels,
std::size_t depth = 0)
{
if (depth > max_levels) {
return false;
}
if (snap.services.contains(key)) {
return true;
}
if (snap.parent_snap) {
return has_in_parent_chain(*snap.parent_snap, key,
max_levels, depth + 1);
}
return false;
}
} // namespace
} // namespace detail
ServiceRegistry::ServiceRegistry()
: ServiceRegistry(ServiceLimits{},
Void::Time::SystemMonotonicClock::instance())
{
}
ServiceRegistry::ServiceRegistry(const ServiceRegistry* parent)
: ServiceRegistry(ServiceLimits{},
Void::Time::SystemMonotonicClock::instance())
{
if (parent != nullptr) {
auto snap = std::make_shared<detail::SnapshotData>();
snap->live_parent = parent;
m_active_snapshot = std::move(snap);
}
}
ServiceRegistry::ServiceRegistry(ServiceLimits limits,
const Void::Time::MonotonicClock& clock)
: m_limits(limits), m_clock(&clock),
m_retention_state(std::make_shared<detail::RetentionState>())
{
m_active_snapshot = std::make_shared<detail::SnapshotData>();
}
ServiceRegistry::~ServiceRegistry()
{
// Detach the active snapshot under m_snapshot_mu with m_stopping=true
// before destroying providers, so a provider destructor reentering the
// registry cannot increment the use_count of a half-destroyed SnapshotData.
std::shared_ptr<const detail::SnapshotData> last_snap;
{
std::lock_guard snap_lk{m_snapshot_mu};
m_stopping = true;
last_snap = std::move(m_active_snapshot);
}
last_snap.reset();
}
Void::Result::Result<std::unique_ptr<ServiceRegistry>>
ServiceRegistry::from_parent_snapshot(
ServiceSnapshot parent, ServiceLimits limits,
const Void::Time::MonotonicClock& clock)
{
if (!parent) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry: parent snapshot must not be empty"));
}
std::size_t depth = 1;
const detail::SnapshotData* cur = parent.m_data.get();
while (cur->parent_snap != nullptr) {
++depth;
if (depth > limits.max_parent_levels) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry: parent snapshot nesting exceeds max_parent_levels"));
}
cur = cur->parent_snap.get();
}
auto reg = std::make_unique<ServiceRegistry>(limits, clock);
auto snap = std::make_shared<detail::SnapshotData>();
snap->parent_snap = std::move(parent.m_data);
reg->m_active_snapshot = std::move(snap);
return reg;
}
void ServiceRegistry::refresh_parent(const ServiceRegistry& parent)
{
auto parent_snap = parent.snapshot();
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
auto next = std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->parent_snap = parent_snap.m_data;
next->live_parent = nullptr;
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return;
}
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
// old_snap released here outside all locks.
}
ServiceSnapshot ServiceRegistry::snapshot() const
{
std::lock_guard snap_lk{m_snapshot_mu};
return ServiceSnapshot{m_active_snapshot, m_limits.max_parent_levels};
}
std::shared_ptr<const detail::SnapshotData>
ServiceRegistry::acquire_snapshot() const
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return nullptr;
}
return m_active_snapshot;
}
void ServiceRegistry::provide_erased(std::type_index key,
std::shared_ptr<void> impl,
const void* object_key,
IService* service)
{
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
if (m_stopping) {
return;
}
auto next =
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->epoch = ++m_epoch;
if (!next->services.contains(key)) {
next->legacy_order.push_back(key);
}
next->services.insert_or_assign(
key, detail::SnapshotEntry{std::move(impl), service, {}});
// Rebuild lifecycle list in legacy registration order (deduping
// shared object instances if multiple interfaces point to one
// IService).
next->lifecycle_nodes.clear();
std::unordered_set<const void*> seen_objs;
for (const auto& k : next->legacy_order) {
const auto it = next->services.find(k);
if (it == next->services.end() || it->second.service == nullptr) {
continue;
}
const void* obj = static_cast<const void*>(it->second.service);
if (!seen_objs.insert(obj).second) {
continue;
}
next->lifecycle_nodes.push_back(detail::LifecycleNode{
.id = std::string{it->second.service->service_name()},
.object_key = obj,
.owner = it->second.impl,
.service = it->second.service,
.managed = dynamic_cast<IManagedService*>(it->second.service),
.seq = next->lifecycle_nodes.size(),
.dep_indices = {},
});
}
(void)object_key;
{
std::lock_guard snap_lk{m_snapshot_mu};
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
}
// old_snap (and any replaced provider whose external refs reached 0)
// destroys here AFTER releasing all registry locks.
}
bool ServiceRegistry::remove_erased(std::type_index key)
{
std::shared_ptr<const detail::SnapshotData> old_snap;
bool removed = false;
{
std::lock_guard write_lk{m_write_mu};
if (m_stopping || !m_active_snapshot->services.contains(key)) {
return false;
}
auto next =
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->epoch = ++m_epoch;
removed = next->services.erase(key) > 0;
std::erase(next->legacy_order, key);
next->lifecycle_nodes.clear();
std::unordered_set<const void*> seen_objs;
for (const auto& k : next->legacy_order) {
const auto it = next->services.find(k);
if (it == next->services.end() || it->second.service == nullptr) {
continue;
}
const void* obj = static_cast<const void*>(it->second.service);
if (!seen_objs.insert(obj).second) {
continue;
}
next->lifecycle_nodes.push_back(detail::LifecycleNode{
.id = std::string{it->second.service->service_name()},
.object_key = obj,
.owner = it->second.impl,
.service = it->second.service,
.managed = dynamic_cast<IManagedService*>(it->second.service),
.seq = next->lifecycle_nodes.size(),
.dep_indices = {},
});
}
{
std::lock_guard snap_lk{m_snapshot_mu};
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
}
return removed;
}
void ServiceRegistry::start_all()
{
auto snap = acquire_snapshot();
if (!snap) {
return;
}
// Snapshot copied; callbacks invoke strictly outside registry locks.
for (const auto& node : snap->lifecycle_nodes) {
if (node.service != nullptr) {
node.service->on_start();
}
}
}
void ServiceRegistry::stop_all()
{
std::shared_ptr<const detail::SnapshotData> snap;
{
std::lock_guard snap_lk{m_snapshot_mu};
snap = m_active_snapshot;
}
if (!snap) {
return;
}
for (auto it = snap->lifecycle_nodes.rbegin();
it != snap->lifecycle_nodes.rend(); ++it) {
if (it->service != nullptr) {
it->service->on_stop();
}
}
}
std::size_t ServiceRegistry::size() const
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_active_snapshot ? m_active_snapshot->services.size() : 0;
}
std::size_t ServiceRegistry::prune_and_count_retained_locked()
{
std::lock_guard lk{m_retention_state->mu};
std::erase_if(m_retention_state->entries,
[](const detail::RetentionEntry& e) {
return e.token.expired();
});
return m_retention_state->entries.size();
}
std::size_t ServiceRegistry::retained_generation_count() const
{
std::lock_guard lk{m_retention_state->mu};
std::size_t live = 0;
for (const auto& e : m_retention_state->entries) {
if (!e.token.expired()) {
++live;
}
}
return live;
}
PublicationEpoch ServiceRegistry::epoch() const noexcept
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_epoch;
}
bool ServiceRegistry::is_stopping() const noexcept
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_stopping;
}
std::size_t ServiceRegistry::add_observer(ObserverCallback cb)
{
std::lock_guard lk{m_observer_mu};
const std::size_t id = m_next_observer_id++;
m_observers.emplace_back(id, std::move(cb));
return id;
}
void ServiceRegistry::remove_observer(std::size_t id)
{
std::lock_guard lk{m_observer_mu};
std::erase_if(m_observers,
[id](const auto& pair) { return pair.first == id; });
}
void ServiceRegistry::notify_observers(const ServiceObservation& obs)
{
std::vector<ObserverCallback> copy;
{
std::lock_guard lk{m_observer_mu};
copy.reserve(m_observers.size());
for (const auto& [_, cb] : m_observers) {
if (cb) {
copy.push_back(cb);
}
}
}
for (const auto& cb : copy) {
try {
cb(obs);
} catch (...) {
}
}
}
Void::Result::Result<PreparedPublication>
ServiceRegistry::prepare_batch(ProviderSet set, ExpectedEpoch expected)
{
std::shared_ptr<const detail::SnapshotData> current_snap;
PublicationEpoch current_epoch = 0;
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::prepare_batch: registry is stopping"));
}
current_epoch = m_epoch;
current_snap = m_active_snapshot;
}
if (expected.has_value() && *expected != current_epoch) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::prepare_batch: expected epoch mismatch"));
}
const auto& items = set.items();
if (items.size() > m_limits.max_staged_changes ||
items.size() > m_limits.max_providers) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry::prepare_batch: staged provider limit exceeded"));
}
if (m_limits.max_retained_generations > 0 &&
retained_generation_count() >= m_limits.max_retained_generations) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::retention_limit,
"ServiceRegistry::prepare_batch: retained generation limit reached"));
}
auto staged = std::make_shared<detail::SnapshotData>();
staged->parent_snap = current_snap ? current_snap->parent_snap : nullptr;
staged->live_parent = current_snap ? current_snap->live_parent : nullptr;
// Validate interfaces, IDs, nulls, edge caps, and coalesce shared-object
// lifecycle aliases into single nodes.
std::unordered_map<std::type_index, std::size_t> iface_to_node;
std::unordered_map<const void*, std::size_t> obj_to_node;
std::unordered_map<std::string, const void*> id_to_obj;
std::vector<detail::LifecycleNode> raw_nodes;
std::size_t total_edges = 0;
for (const auto& item : items) {
if (!item.owner || item.object_key == nullptr) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::prepare_batch: null service provider"));
}
if (staged->services.contains(item.interface_type)) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::duplicate_interface,
"ServiceRegistry::prepare_batch: duplicate interface in batch"));
}
const void* canonical_obj =
item.service != nullptr
? static_cast<const void*>(item.service)
: item.object_key;
if (!item.id.empty()) {
const auto [it, inserted] =
id_to_obj.emplace(item.id, canonical_obj);
if (!inserted && it->second != canonical_obj) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::prepare_batch: conflicting service id '" +
item.id + "'"));
}
}
staged->services.emplace(
item.interface_type,
detail::SnapshotEntry{item.owner, item.service, item.id});
staged->legacy_order.push_back(item.interface_type);
total_edges += item.required_deps.size() + item.optional_deps.size();
if (total_edges > m_limits.max_dependency_edges) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry::prepare_batch: dependency edge limit exceeded"));
}
auto [oit, o_inserted] =
obj_to_node.emplace(canonical_obj, raw_nodes.size());
if (o_inserted) {
std::string node_id = item.id;
if (node_id.empty() && item.service != nullptr) {
node_id = std::string{item.service->service_name()};
}
raw_nodes.push_back(detail::LifecycleNode{
.id = std::move(node_id),
.object_key = canonical_obj,
.owner = item.owner,
.service = item.service,
.managed = item.managed,
.seq = raw_nodes.size(),
.dep_indices = {},
});
}
iface_to_node.emplace(item.interface_type, oit->second);
}
// Build DAG edges: dep_idx -> dependent_idx.
const std::size_t n = raw_nodes.size();
std::vector<std::vector<std::size_t>> adj(n);
std::vector<std::size_t> indegree(n, 0);
std::unordered_set<std::uint64_t> edge_dedup;
for (const auto& item : items) {
const std::size_t u = iface_to_node.at(item.interface_type);
auto add_dep = [&](std::type_index dep_iface,
bool required) -> Void::Result::Result<void> {
const auto dit = iface_to_node.find(dep_iface);
if (dit == iface_to_node.end()) {
bool in_parent = false;
if (staged->parent_snap) {
in_parent = detail::has_in_parent_chain(
*staged->parent_snap, dep_iface,
m_limits.max_parent_levels);
}
if (!in_parent && staged->live_parent != nullptr) {
if (auto ps = staged->live_parent->acquire_snapshot()) {
in_parent = ps->services.contains(dep_iface);
}
}
if (required && !in_parent) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_dependency,
"ServiceRegistry::prepare_batch: missing required dependency"));
}
return {};
}
const std::size_t dep = dit->second;
if (dep == u) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::cycle_detected,
"ServiceRegistry::prepare_batch: self-dependency cycle"));
}
const std::uint64_t edge_key =
(static_cast<std::uint64_t>(dep) << 32) |
static_cast<std::uint64_t>(u);
if (edge_dedup.insert(edge_key).second) {
adj[dep].push_back(u);
++indegree[u];
}
return {};
};
for (const auto& dep : item.required_deps) {
if (auto r = add_dep(dep, true); !r) {
return Void::Result::fail(std::move(r).error());
}
}
for (const auto& dep : item.optional_deps) {
if (auto r = add_dep(dep, false); !r) {
return Void::Result::fail(std::move(r).error());
}
}
}
// Deterministic Kahn topological sort breaking ties by registration seq.
std::priority_queue<std::size_t, std::vector<std::size_t>,
std::greater<std::size_t>>
ready;
for (std::size_t i = 0; i < n; ++i) {
if (indegree[i] == 0) {
ready.push(i);
}
}
std::vector<detail::LifecycleNode> sorted;
sorted.reserve(n);
while (!ready.empty()) {
const std::size_t u = ready.top();
ready.pop();
sorted.push_back(std::move(raw_nodes[u]));
for (const std::size_t v : adj[u]) {
if (--indegree[v] == 0) {
ready.push(v);
}
}
}
if (sorted.size() != n) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::cycle_detected,
"ServiceRegistry::prepare_batch: dependency cycle detected"));
}
staged->lifecycle_nodes = std::move(sorted);
PreparedPublication prep;
prep.expected_epoch = expected;
prep.snapshot = std::move(staged);
prep.valid = true;
prep.started = false;
prep.aborted = false;
return prep;
}
Void::Result::Result<void> ServiceRegistry::rollback_started_nodes(
const std::vector<detail::LifecycleNode>& nodes, std::size_t count,
const Void::Result::Error& primary_error)
{
std::string stop_errs;
for (std::size_t i = count; i > 0; --i) {
const auto& node = nodes[i - 1];
if (node.managed != nullptr) {
auto sr = node.managed->stop_checked();
if (!sr) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += sr.error().message();
}
} else if (node.service != nullptr) {
try {
node.service->on_stop();
} catch (const std::exception& ex) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += ex.what();
} catch (...) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += "unknown stop exception";
}
}
}
if (stop_errs.empty()) {
return Void::Result::fail(primary_error);
}
return Void::Result::fail(make_service_error(
static_cast<ServiceErrorCode>(primary_error.code().value),
primary_error.message() + " (rollback stop errors: " + stop_errs +
")"));
}
Void::Result::Result<void>
ServiceRegistry::start_staged(PreparedPublication& prepared,
Async::OperationOptions options)
{
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::start_staged: invalid or aborted publication"));
}
if (prepared.started) {
return {};
}
const auto& nodes = prepared.snapshot->lifecycle_nodes;
for (std::size_t i = 0; i < nodes.size(); ++i) {
if (options.stop.stop_requested()) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::cancelled,
"ServiceRegistry::start_staged: cancelled during startup"));
}
if (Async::is_deadline_expired(options, *m_clock)) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::timeout,
"ServiceRegistry::start_staged: deadline expired during startup"));
}
const auto& node = nodes[i];
if (node.managed != nullptr) {
auto sr = node.managed->start_checked();
if (!sr) {
node.managed->abort_start();
prepared.aborted = true;
return rollback_started_nodes(nodes, i, sr.error());
}
auto rr = node.managed->check_readiness();
if (!rr) {
node.managed->abort_start();
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::not_ready,
rr.error().message()));
}
} else if (node.service != nullptr) {
try {
node.service->on_start();
} catch (const std::exception& ex) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::start_failed,
ex.what()));
} catch (...) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::start_failed,
"ServiceRegistry: service on_start threw"));
}
}
}
prepared.started = true;
return {};
}
Void::Result::Result<PublicationEpoch>
ServiceRegistry::publish(PreparedPublication&& prepared)
{
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::publish: invalid or aborted publication"));
}
PublicationEpoch new_epoch = 0;
std::size_t provider_count = 0;
std::size_t retained = 0;
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::publish: registry is stopping"));
}
if (prepared.expected_epoch.has_value() &&
*prepared.expected_epoch != m_epoch) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::publish: expected epoch conflict"));
}
}
if (m_limits.max_retained_generations > 0 &&
prune_and_count_retained_locked() >=
m_limits.max_retained_generations) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::retention_limit,
"ServiceRegistry::publish: retained generation limit reached"));
}
new_epoch = ++m_epoch;
prepared.snapshot->epoch = new_epoch;
prepared.snapshot->gen_token = detail::make_retention_token(
m_retention_state, new_epoch,
"generation#" + std::to_string(new_epoch));
provider_count = prepared.snapshot->services.size();
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::publish: registry is stopping"));
}
old_snap = std::exchange(m_active_snapshot,
std::move(prepared.snapshot));
}
retained = prune_and_count_retained_locked();
m_started = prepared.started;
}
prepared.valid = false;
// Retire old snapshot strictly outside locks, then notify observers.
old_snap.reset();
notify_observers(ServiceObservation{
.epoch = new_epoch,
.provider_count = provider_count,
.retained_generations = retained,
.duration_ns = 0,
.rollback = false,
.detail = "published",
});
return new_epoch;
}
Void::Result::Result<PublicationEpoch>
ServiceRegistry::start_and_publish(ProviderSet set,
ExpectedEpoch expected,
Async::OperationOptions options)
{
const auto t0 = m_clock->now();
auto prep = prepare_batch(std::move(set), expected);
if (!prep) {
return Void::Result::fail(std::move(prep).error());
}
auto staged = std::move(*prep);
if (auto sr = start_staged(staged, options); !sr) {
const auto dt = static_cast<std::uint64_t>(
std::max<std::int64_t>(0, (m_clock->now() - t0).count()));
notify_observers(ServiceObservation{
.epoch = epoch(),
.provider_count = 0,
.retained_generations = retained_generation_count(),
.duration_ns = dt,
.rollback = true,
.detail = sr.error().message(),
});
return Void::Result::fail(std::move(sr).error());
}
auto snapshot_copy = staged.snapshot;
auto pub = publish(std::move(staged));
if (!pub) {
return Void::Result::fail(
rollback_started_nodes(snapshot_copy->lifecycle_nodes,
snapshot_copy->lifecycle_nodes.size(),
pub.error())
.error());
}
return pub;
}
Void::Result::Result<void>
ServiceRegistry::start(Async::OperationOptions options)
{
auto snap = acquire_snapshot();
if (!snap) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::start: registry is stopping"));
}
const auto& nodes = snap->lifecycle_nodes;
for (std::size_t i = 0; i < nodes.size(); ++i) {
if (options.stop.stop_requested()) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::cancelled,
"ServiceRegistry::start: cancelled"));
}
if (Async::is_deadline_expired(options, *m_clock)) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::timeout,
"ServiceRegistry::start: timed out"));
}
const auto& node = nodes[i];
if (node.managed != nullptr) {
auto sr = node.managed->start_checked();
if (!sr) {
node.managed->abort_start();
return rollback_started_nodes(nodes, i, sr.error());
}
auto rr = node.managed->check_readiness();
if (!rr) {
node.managed->abort_start();
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::not_ready,
rr.error().message()));
}
} else if (node.service != nullptr) {
try {
node.service->on_start();
} catch (const std::exception& ex) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::start_failed,
ex.what()));
} catch (...) {
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::start_failed,
"ServiceRegistry::start: on_start threw"));
}
}
}
std::lock_guard write_lk{m_write_mu};
m_started = true;
return {};
}
Void::Result::Result<ShutdownReport>
ServiceRegistry::close_and_join(Async::OperationOptions options)
{
std::shared_ptr<const detail::SnapshotData> active_to_stop;
{
std::lock_guard snap_lk{m_snapshot_mu};
m_stopping = true;
active_to_stop = std::exchange(
m_active_snapshot, std::make_shared<detail::SnapshotData>());
}
ShutdownReport report;
if (active_to_stop) {
for (auto it = active_to_stop->lifecycle_nodes.rbegin();
it != active_to_stop->lifecycle_nodes.rend(); ++it) {
const auto& node = *it;
const std::string label =
!node.id.empty() ? node.id : std::string{"<service>"};
if (node.managed != nullptr) {
auto sr = node.managed->stop_checked();
if (!sr) {
report.stop_errors.push_back(std::move(sr).error());
} else {
report.stopped_services.push_back(label);
}
} else if (node.service != nullptr) {
try {
node.service->on_stop();
report.stopped_services.push_back(label);
} catch (const std::exception& ex) {
report.stop_errors.push_back(make_service_error(
ServiceErrorCode::stop_failed, ex.what()));
} catch (...) {
report.stop_errors.push_back(make_service_error(
ServiceErrorCode::stop_failed,
"ServiceRegistry::close_and_join: on_stop threw"));
}
}
}
}
active_to_stop.reset();
// Check retained generation pins; wait up to deadline only when using the
// real monotonic clock and an explicit deadline.
const bool can_wait_deadline =
options.deadline.has_value() &&
m_clock == &Void::Time::SystemMonotonicClock::instance();
std::unique_lock lk{m_retention_state->mu};
auto collect_live = [&]() {
std::erase_if(m_retention_state->entries,
[](const detail::RetentionEntry& e) {
return e.token.expired();
});
return m_retention_state->entries.empty();
};
if (!collect_live() && can_wait_deadline && !options.stop.stop_requested()) {
while (!collect_live() && !options.stop.stop_requested()) {
const auto now = m_clock->now();
if (now >= *options.deadline) {
break;
}
const auto rem = *options.deadline - now;
m_retention_state->cv.wait_for(
lk, std::chrono::duration_cast<std::chrono::milliseconds>(
rem));
}
}
for (const auto& entry : m_retention_state->entries) {
if (!entry.token.expired()) {
report.incomplete_owners.push_back(entry.label);
}
}
return report;
}
} // namespace Void::Service
+2 -1
View File
@@ -1,3 +1,4 @@
void_add_module(Service
INTERNAL_DEPS Core Functional LogState
INTERNAL_DEPS Core Functional Time Async LogState
EXCLUDE_HEADERS Void/Service/PluginService.hpp
)
+4
View File
@@ -0,0 +1,4 @@
void_add_module(ServicePlugin
INTERNAL_DEPS Service Plugin LogState
EXTRA_HEADERS Void/Service/PluginService.hpp
)