feat(scheduler): implement P3 S-SCHEDULER-01..04 Scheduler engine, calendar/DST, and SchedulerStorage durable store
This commit is contained in:
1 parent
ec8c0bd40a
commit
aaeab50758
15 files changed
+4694
No files matched your search
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
struct CivilMinute {
|
||||
std::int32_t year{1970};
|
||||
std::uint32_t month{1}; // 1..12
|
||||
std::uint32_t day{1}; // 1..31
|
||||
std::uint32_t hour{0}; // 0..23
|
||||
std::uint32_t minute{0}; // 0..59
|
||||
std::uint32_t weekday{4}; // 0=Sunday .. 6=Saturday
|
||||
};
|
||||
|
||||
/// Convert civil UTC components to minutes since 1970-01-01T00:00Z.
|
||||
[[nodiscard]] std::int64_t
|
||||
civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
|
||||
std::uint32_t day, std::uint32_t hour,
|
||||
std::uint32_t minute) noexcept;
|
||||
|
||||
/// Convert minutes since 1970-01-01T00:00Z to civil components + weekday.
|
||||
[[nodiscard]] CivilMinute
|
||||
epoch_minute_to_civil(std::int64_t epoch_minute) noexcept;
|
||||
|
||||
/// Explicit DST transition rule for deterministic timezone resolution
|
||||
/// without relying on ambient OS tzdata behavior.
|
||||
struct DstTransitionRule {
|
||||
std::string name{};
|
||||
std::int32_t standard_offset_minutes{0};
|
||||
std::int32_t dst_offset_minutes{0};
|
||||
/// Spring-forward gap window in local wall minutes `[start, end)`.
|
||||
std::optional<std::int64_t> gap_start_local_min{};
|
||||
std::optional<std::int64_t> gap_end_local_min{};
|
||||
/// Fall-back fold window in local wall minutes `[start, end)`.
|
||||
/// Minutes in `[start, end)` happen twice: fold 0 at `dst_offset`,
|
||||
/// fold 1 at `standard_offset`.
|
||||
std::optional<std::int64_t> fold_start_local_min{};
|
||||
std::optional<std::int64_t> fold_end_local_min{};
|
||||
};
|
||||
|
||||
struct ResolvedSlot {
|
||||
std::int64_t utc_ms{0};
|
||||
std::uint8_t fold_index{0};
|
||||
};
|
||||
|
||||
/// Explicit timezone registry. Recognizes `"UTC"`, `"Z"`, fixed numeric
|
||||
/// offsets (`+HH:MM`, `-HH:MM`, `UTC+HH:MM`, `UTC-HH:MM`), and explicitly
|
||||
/// registered `DstTransitionRule` zones. Unknown zones fail with
|
||||
/// `UnsupportedTimezone` (never silent UTC fallback).
|
||||
class TimezoneRegistry final
|
||||
{
|
||||
public:
|
||||
|
||||
TimezoneRegistry() = default;
|
||||
|
||||
void register_dst_zone(DstTransitionRule rule);
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
validate_timezone(std::string_view tz) const;
|
||||
|
||||
[[nodiscard]] Result<std::vector<ResolvedSlot>>
|
||||
resolve_local_minute(std::string_view tz,
|
||||
std::int64_t local_epoch_minute,
|
||||
DstGapPolicy gap_policy,
|
||||
DstFoldPolicy fold_policy) const;
|
||||
|
||||
/// Approximate local epoch minute range covering `[utc_min_lo,
|
||||
/// utc_min_hi]` for `tz`.
|
||||
[[nodiscard]] Result<std::pair<std::int64_t, std::int64_t>>
|
||||
local_minute_bounds(std::string_view tz,
|
||||
std::int64_t utc_min_lo,
|
||||
std::int64_t utc_min_hi) const;
|
||||
|
||||
private:
|
||||
|
||||
std::map<std::string, DstTransitionRule, std::less<>> m_dst_zones{};
|
||||
};
|
||||
|
||||
struct MaterializedSlots {
|
||||
std::vector<ResolvedSlot> slots{};
|
||||
std::int64_t next_cursor_utc_ms{0};
|
||||
bool more_pending{false};
|
||||
};
|
||||
|
||||
/// 5-field cron-like calendar expression (`minute hour day month weekday`)
|
||||
/// supporting `*`, lists, ranges, and steps. Both day-of-month and weekday
|
||||
/// constraints apply.
|
||||
class CalendarExpression final
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Result<CalendarExpression>
|
||||
parse(std::string_view expression);
|
||||
|
||||
[[nodiscard]] bool matches(const CivilMinute& cm) const noexcept;
|
||||
|
||||
/// Next matching local epoch minute strictly >= `from_local_min`,
|
||||
/// capped by `max_local_min`.
|
||||
[[nodiscard]] std::optional<std::int64_t>
|
||||
next_matching_minute(std::int64_t from_local_min,
|
||||
std::int64_t max_local_min) const noexcept;
|
||||
|
||||
/// Latest matching local epoch minute <= `from_local_min` and
|
||||
/// >= `min_local_min`. Allows O(1) coalescing across millions of
|
||||
/// missed minutes.
|
||||
[[nodiscard]] std::optional<std::int64_t>
|
||||
prev_matching_minute(std::int64_t from_local_min,
|
||||
std::int64_t min_local_min) const noexcept;
|
||||
|
||||
[[nodiscard]] Result<MaterializedSlots>
|
||||
materialize_range(const CalendarSpec& spec,
|
||||
const TimezoneRegistry& tz_registry,
|
||||
std::int64_t after_utc_ms,
|
||||
std::int64_t up_to_utc_ms,
|
||||
MisfirePolicy misfire,
|
||||
std::size_t max_catch_up) const;
|
||||
|
||||
private:
|
||||
|
||||
std::uint64_t m_minutes{0}; // bits 0..59
|
||||
std::uint32_t m_hours{0}; // bits 0..23
|
||||
std::uint32_t m_days{0}; // bits 1..31
|
||||
std::uint32_t m_months{0}; // bits 1..12
|
||||
std::uint32_t m_weekdays{0}; // bits 0..6 (0 = Sunday)
|
||||
};
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
#include <Void/Scheduler/Store.hpp>
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
struct SchedulerOptions {
|
||||
std::string owner_id{"scheduler-default"};
|
||||
std::shared_ptr<JobStore> store{};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
TimezoneRegistry timezones{};
|
||||
SchedulerLimits limits{};
|
||||
RandomU64Fn rng{};
|
||||
ObservationHook observer{};
|
||||
};
|
||||
|
||||
/// Pure, thread-free timer/calendar job scheduler with pluggable durable
|
||||
/// persistence (`InMemoryJobStore` or `SchedulerStorage::StorageJobStore`).
|
||||
class Scheduler final
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Result<Scheduler>
|
||||
create(SchedulerOptions options = {});
|
||||
|
||||
Scheduler(Scheduler&&) noexcept;
|
||||
Scheduler& operator=(Scheduler&&) noexcept;
|
||||
Scheduler(const Scheduler&) = delete;
|
||||
Scheduler& operator=(const Scheduler&) = delete;
|
||||
~Scheduler() noexcept;
|
||||
|
||||
[[nodiscard]] Result<void> register_handler(std::string handler_id,
|
||||
HandlerFn handler);
|
||||
|
||||
[[nodiscard]] Result<std::uint64_t>
|
||||
add_job(JobSpec spec,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Increment revision and atomically record an old-revision
|
||||
/// invalidation watermark. Failed updates leave prior policy intact.
|
||||
[[nodiscard]] Result<std::uint64_t>
|
||||
update_job(JobSpec spec,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Write a job tombstone, stop new admission, and signal stop to
|
||||
/// active handlers for the job.
|
||||
[[nodiscard]] Result<void>
|
||||
remove_job(std::string_view job_id,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Run one bounded scheduling pass: materialize due occurrences
|
||||
/// under misfire/catch-up/retention limits and dispatch ready
|
||||
/// occurrences outside scheduler/store locks. Returns count of
|
||||
/// occurrences executed in this pass.
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
tick(Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Execute at most one ready occurrence from the monotonic min-heap
|
||||
/// outside scheduler/store locks.
|
||||
[[nodiscard]] Result<bool>
|
||||
dispatch_one(Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Stop materialization/dispatch, signal stop to active handlers,
|
||||
/// and wait up to `options.deadline` for live handlers to exit.
|
||||
/// Never erases running records or abandons active frames.
|
||||
[[nodiscard]] Result<ShutdownReport>
|
||||
close_and_join(Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Result<std::vector<JobRecord>> list_jobs() const;
|
||||
[[nodiscard]] Result<std::vector<OccurrenceRecord>>
|
||||
list_occurrences() const;
|
||||
[[nodiscard]] Result<void>
|
||||
acknowledge_dead(const OccurrenceId& id);
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
prune_completed(std::size_t max_count = 256);
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count = 256);
|
||||
[[nodiscard]] Result<StoreStats> stats() const;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit Scheduler(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,105 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
/// Persistence port for Scheduler state transitions.
|
||||
/// Implementations guarantee atomic conditional commits (in-memory mutex
|
||||
/// or `Void::Storage::Engine` conditional batches).
|
||||
class JobStore
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~JobStore() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
acquire_ownership(std::string_view owner_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> release_ownership() = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> put_job(const JobRecord& job) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
update_job(const JobRecord& updated,
|
||||
std::uint64_t expected_revision) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
tombstone_job(std::string_view job_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<JobRecord>>
|
||||
load_jobs() const = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<OccurrenceRecord>>
|
||||
load_occurrences() const = 0;
|
||||
|
||||
/// Atomically insert new occurrences (enforcing unique
|
||||
/// `(job, revision, intended_utc_ms, fold_index)` dedup and
|
||||
/// retention cap) AND advance the job's cursor/sequence.
|
||||
[[nodiscard]] virtual Result<std::size_t> materialize_occurrences(
|
||||
std::string_view job_id, std::uint64_t expected_revision,
|
||||
std::int64_t new_cursor_utc_ms,
|
||||
std::int64_t new_cursor_monotonic_ns, bool cursor_initialized,
|
||||
bool one_shot_materialized, std::uint64_t next_sequence,
|
||||
const std::vector<OccurrenceRecord>& records) = 0;
|
||||
|
||||
/// Atomically verify job is not tombstoned, check old-revision
|
||||
/// invalidation watermark, and transition `Pending -> Running`
|
||||
/// bumping `attempt`.
|
||||
[[nodiscard]] virtual Result<OccurrenceRecord>
|
||||
claim_occurrence(const OccurrenceId& id,
|
||||
std::uint32_t expected_attempt) = 0;
|
||||
|
||||
/// Atomically transition `Running -> Completed` and optionally
|
||||
/// advance a FixedDelay job's monotonic cursor.
|
||||
[[nodiscard]] virtual Result<void> complete_occurrence(
|
||||
const OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t completed_utc_ms,
|
||||
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
|
||||
std::nullopt) = 0;
|
||||
|
||||
/// Atomically transition `Running -> Pending` (retry) or
|
||||
/// `Running -> Dead` (exhausted).
|
||||
[[nodiscard]] virtual Result<void> fail_occurrence(
|
||||
const OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t next_due_monotonic_ns,
|
||||
std::int64_t next_due_utc_ms, bool mark_dead,
|
||||
std::string diagnostic_category) = 0;
|
||||
|
||||
/// Return a `Running` occurrence to `Pending` during host shutdown
|
||||
/// without consuming a retry attempt.
|
||||
[[nodiscard]] virtual Result<void>
|
||||
requeue_on_shutdown(const OccurrenceId& id,
|
||||
std::uint32_t attempt) = 0;
|
||||
|
||||
/// Startup recovery: return every `Running` record to `Pending`
|
||||
/// preserving its exact `OccurrenceId` and attempt counter.
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
recover_running_occurrences() = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
acknowledge_dead(const OccurrenceId& id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
prune_completed(std::int64_t before_utc_ms,
|
||||
std::size_t max_count) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<StoreStats> stats() const = 0;
|
||||
};
|
||||
|
||||
/// Default in-memory `JobStore` implementation requiring zero `Storage`
|
||||
/// dependency.
|
||||
[[nodiscard]] std::shared_ptr<JobStore>
|
||||
make_in_memory_job_store(SchedulerLimits limits = {});
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,339 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class SchedulerErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidArgument = 1,
|
||||
InvalidRule = 2,
|
||||
UnsupportedTimezone = 3,
|
||||
NotFound = 4,
|
||||
Conflict = 5,
|
||||
Overloaded = 6,
|
||||
RetentionFull = 7,
|
||||
PersistenceError = 8,
|
||||
UnknownOutcome = 9,
|
||||
HandlerFailed = 10,
|
||||
Cancelled = 11,
|
||||
Closed = 12,
|
||||
SelfJoin = 13,
|
||||
OwnershipLocked = 14,
|
||||
CorruptRecord = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_scheduler_error(SchedulerErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SchedulerErrorCode::None:
|
||||
case SchedulerErrorCode::HandlerFailed:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SchedulerErrorCode::InvalidArgument:
|
||||
case SchedulerErrorCode::InvalidRule:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SchedulerErrorCode::UnsupportedTimezone:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SchedulerErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SchedulerErrorCode::Conflict:
|
||||
case SchedulerErrorCode::UnknownOutcome:
|
||||
case SchedulerErrorCode::SelfJoin:
|
||||
case SchedulerErrorCode::OwnershipLocked:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SchedulerErrorCode::Overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case SchedulerErrorCode::RetentionFull:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SchedulerErrorCode::PersistenceError:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case SchedulerErrorCode::CorruptRecord:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SchedulerErrorCode::Cancelled:
|
||||
case SchedulerErrorCode::Closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kSchedulerErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct OccurrenceId {
|
||||
std::string job_id{};
|
||||
std::uint64_t revision{0};
|
||||
std::uint64_t sequence{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const OccurrenceId&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] std::string to_idempotency_key() const
|
||||
{
|
||||
return job_id + "#" + std::to_string(revision) + "#" +
|
||||
std::to_string(sequence);
|
||||
}
|
||||
};
|
||||
|
||||
enum class MisfirePolicy : std::uint8_t {
|
||||
Skip = 0,
|
||||
CoalesceLatest = 1,
|
||||
CatchUpBounded = 2,
|
||||
};
|
||||
|
||||
enum class OverlapPolicy : std::uint8_t {
|
||||
Forbid = 0,
|
||||
QueueOne = 1,
|
||||
AllowBounded = 2,
|
||||
};
|
||||
|
||||
enum class DstGapPolicy : std::uint8_t {
|
||||
Skip = 0,
|
||||
NextValid = 1,
|
||||
};
|
||||
|
||||
enum class DstFoldPolicy : std::uint8_t {
|
||||
First = 0,
|
||||
Second = 1,
|
||||
Twice = 2,
|
||||
};
|
||||
|
||||
enum class ScheduleKind : std::uint8_t {
|
||||
OneShot = 0,
|
||||
FixedDelay = 1,
|
||||
FixedRate = 2,
|
||||
Calendar = 3,
|
||||
};
|
||||
|
||||
struct RetryPolicy {
|
||||
std::uint32_t max_attempts{5};
|
||||
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
|
||||
std::chrono::milliseconds max_delay{std::chrono::minutes{5}};
|
||||
std::uint32_t multiplier{2};
|
||||
};
|
||||
|
||||
struct CalendarSpec {
|
||||
std::string expression{};
|
||||
std::string timezone{"UTC"};
|
||||
std::uint32_t tz_data_version{1};
|
||||
DstGapPolicy gap_policy{DstGapPolicy::Skip};
|
||||
DstFoldPolicy fold_policy{DstFoldPolicy::First};
|
||||
};
|
||||
|
||||
struct Schedule {
|
||||
ScheduleKind kind{ScheduleKind::OneShot};
|
||||
std::int64_t start_utc_ms{0};
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
due_monotonic{};
|
||||
std::chrono::milliseconds interval{0};
|
||||
CalendarSpec calendar{};
|
||||
|
||||
[[nodiscard]] static Schedule
|
||||
one_shot_monotonic(Void::Time::MonotonicClock::time_point due)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::OneShot;
|
||||
s.due_monotonic = due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule one_shot_utc(std::int64_t utc_ms)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::OneShot;
|
||||
s.start_utc_ms = utc_ms;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule fixed_delay(
|
||||
std::chrono::milliseconds delay,
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
first_due = std::nullopt)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::FixedDelay;
|
||||
s.interval = delay;
|
||||
s.due_monotonic = first_due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule fixed_rate(
|
||||
std::chrono::milliseconds period,
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
first_due = std::nullopt)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::FixedRate;
|
||||
s.interval = period;
|
||||
s.due_monotonic = first_due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule calendar_schedule(CalendarSpec spec)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::Calendar;
|
||||
s.calendar = std::move(spec);
|
||||
return s;
|
||||
}
|
||||
};
|
||||
|
||||
struct JobSpec {
|
||||
std::string id{};
|
||||
Schedule schedule{};
|
||||
std::string handler_id{};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::vector<std::byte> payload{};
|
||||
MisfirePolicy misfire{MisfirePolicy::CoalesceLatest};
|
||||
OverlapPolicy overlap{OverlapPolicy::Forbid};
|
||||
std::uint32_t max_concurrent{1};
|
||||
RetryPolicy retry{};
|
||||
};
|
||||
|
||||
enum class OccurrenceStatus : std::uint8_t {
|
||||
Pending = 0,
|
||||
Running = 1,
|
||||
Completed = 2,
|
||||
Dead = 3,
|
||||
Cancelled = 4,
|
||||
};
|
||||
|
||||
struct JobRecord {
|
||||
std::uint32_t format_version{1};
|
||||
JobSpec spec{};
|
||||
std::uint64_t revision{1};
|
||||
/// Unstarted occurrences with `revision < invalidated_before_revision`
|
||||
/// are logically cancelled and cannot be claimed.
|
||||
std::uint64_t invalidated_before_revision{1};
|
||||
bool tombstoned{false};
|
||||
std::int64_t cursor_utc_ms{0};
|
||||
std::int64_t cursor_monotonic_ns{0};
|
||||
bool cursor_initialized{false};
|
||||
bool one_shot_materialized{false};
|
||||
std::uint64_t next_sequence{1};
|
||||
};
|
||||
|
||||
struct OccurrenceRecord {
|
||||
std::uint32_t format_version{1};
|
||||
OccurrenceId id{};
|
||||
std::int64_t intended_utc_ms{0};
|
||||
std::int64_t due_monotonic_ns{0};
|
||||
std::uint8_t fold_index{0};
|
||||
OccurrenceStatus status{OccurrenceStatus::Pending};
|
||||
std::uint32_t attempt{0};
|
||||
std::string handler_id{};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::vector<std::byte> payload{};
|
||||
std::string diagnostic_category{};
|
||||
std::int64_t completed_utc_ms{0};
|
||||
bool dead_acknowledged{false};
|
||||
};
|
||||
|
||||
struct SchedulerLimits {
|
||||
std::size_t max_jobs{10000};
|
||||
std::size_t max_retained_occurrences{100000};
|
||||
std::size_t max_payload_bytes{64ULL * 1024};
|
||||
std::size_t max_loaded_payload_bytes{16ULL * 1024 * 1024};
|
||||
std::size_t max_ready_dispatches{256};
|
||||
std::size_t max_active_handlers{32};
|
||||
std::size_t max_catch_up_per_job_per_pass{100};
|
||||
std::size_t max_retries_per_turn{64};
|
||||
std::size_t max_durable_batch_bytes{1024ULL * 1024};
|
||||
std::chrono::milliseconds completed_retention{
|
||||
std::chrono::hours{24 * 7}};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
bool complete{true};
|
||||
std::vector<OccurrenceId> live_occurrences{};
|
||||
};
|
||||
|
||||
struct StoreStats {
|
||||
std::size_t jobs{0};
|
||||
std::size_t pending{0};
|
||||
std::size_t running{0};
|
||||
std::size_t completed{0};
|
||||
std::size_t dead{0};
|
||||
std::size_t cancelled{0};
|
||||
std::size_t total_retained{0};
|
||||
bool retention_saturated{false};
|
||||
};
|
||||
|
||||
enum class ObservationKind : std::uint8_t {
|
||||
Materialize = 0,
|
||||
Dispatch = 1,
|
||||
Complete = 2,
|
||||
Retry = 3,
|
||||
DeadLetter = 4,
|
||||
RetentionPause = 5,
|
||||
Recover = 6,
|
||||
};
|
||||
|
||||
struct ObservationEvent {
|
||||
ObservationKind kind{ObservationKind::Dispatch};
|
||||
std::size_t count{1};
|
||||
std::int64_t lag_ms{0};
|
||||
};
|
||||
|
||||
using ObservationHook = std::function<void(const ObservationEvent&)>;
|
||||
using RandomU64Fn = std::function<std::uint64_t()>;
|
||||
|
||||
struct OccurrenceContext {
|
||||
OccurrenceId id{};
|
||||
std::uint32_t attempt{1};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::int64_t intended_utc_ms{0};
|
||||
std::uint8_t fold_index{0};
|
||||
};
|
||||
|
||||
using HandlerFn = std::function<Result<void>(
|
||||
const OccurrenceContext&, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions)>;
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_ns(Void::Time::MonotonicClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Store.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Void::SchedulerStorage
|
||||
{
|
||||
struct StorageJobStoreOptions {
|
||||
Void::Scheduler::SchedulerLimits limits{};
|
||||
/// Key prefix namespace within the shared `Void::Storage::Engine`.
|
||||
std::string key_prefix{"sched:v1:"};
|
||||
/// Set true only when explicitly recovering after a process crash
|
||||
/// where the previous owner exited without calling
|
||||
/// `release_ownership()` (the underlying `Storage::Engine` OS lock
|
||||
/// guarantees single-process directory ownership).
|
||||
bool recover_stale_owner{false};
|
||||
};
|
||||
|
||||
/// Durable `Void::Scheduler::JobStore` backed by `Void::Storage::Engine`
|
||||
/// conditional `Batch` writes (`Durability::Sync`, 1 MiB batch cap,
|
||||
/// exclusive logical owner lock, unique civil-slot dedup index, and
|
||||
/// `UnknownOutcome` propagation).
|
||||
class StorageJobStore final : public Void::Scheduler::JobStore
|
||||
{
|
||||
public:
|
||||
|
||||
StorageJobStore(Void::Storage::Engine& engine,
|
||||
StorageJobStoreOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
acquire_ownership(std::string_view owner_id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
release_ownership() override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
put_job(const Void::Scheduler::JobRecord& job) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
update_job(const Void::Scheduler::JobRecord& updated,
|
||||
std::uint64_t expected_revision) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
tombstone_job(std::string_view job_id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
std::vector<Void::Scheduler::JobRecord>>
|
||||
load_jobs() const override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
std::vector<Void::Scheduler::OccurrenceRecord>>
|
||||
load_occurrences() const override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
materialize_occurrences(
|
||||
std::string_view job_id, std::uint64_t expected_revision,
|
||||
std::int64_t new_cursor_utc_ms,
|
||||
std::int64_t new_cursor_monotonic_ns,
|
||||
bool cursor_initialized, bool one_shot_materialized,
|
||||
std::uint64_t next_sequence,
|
||||
const std::vector<Void::Scheduler::OccurrenceRecord>&
|
||||
records) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
Void::Scheduler::OccurrenceRecord>
|
||||
claim_occurrence(const Void::Scheduler::OccurrenceId& id,
|
||||
std::uint32_t expected_attempt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void> complete_occurrence(
|
||||
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t completed_utc_ms,
|
||||
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
|
||||
std::nullopt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void> fail_occurrence(
|
||||
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t next_due_monotonic_ns,
|
||||
std::int64_t next_due_utc_ms, bool mark_dead,
|
||||
std::string diagnostic_category) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
requeue_on_shutdown(const Void::Scheduler::OccurrenceId& id,
|
||||
std::uint32_t attempt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
recover_running_occurrences() override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
acknowledge_dead(const Void::Scheduler::OccurrenceId& id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
prune_completed(std::int64_t before_utc_ms,
|
||||
std::size_t max_count) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<Void::Scheduler::StoreStats>
|
||||
stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
Void::Storage::Engine* m_engine{nullptr};
|
||||
StorageJobStoreOptions m_options{};
|
||||
std::string m_owner_id{};
|
||||
};
|
||||
|
||||
} // namespace Void::SchedulerStorage
|
||||
@@ -0,0 +1,632 @@
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Howard Hinnant's exact civil-from-days / days-from-civil algorithms.
|
||||
[[nodiscard]] constexpr std::int64_t
|
||||
days_from_civil(std::int32_t y, std::uint32_t m,
|
||||
std::uint32_t d) noexcept
|
||||
{
|
||||
const std::int64_t y_adj = static_cast<std::int64_t>(y) - (m <= 2);
|
||||
const std::int64_t era =
|
||||
(y_adj >= 0 ? y_adj : y_adj - 399) / 400;
|
||||
const auto yoe =
|
||||
static_cast<std::uint64_t>(y_adj - era * 400); // [0, 399]
|
||||
const std::uint64_t doy =
|
||||
(153U * (m + (m > 2 ? static_cast<std::uint32_t>(-3) : 9U)) +
|
||||
2U) /
|
||||
5U +
|
||||
d - 1U; // [0, 365]
|
||||
const std::uint64_t doe =
|
||||
yoe * 365U + yoe / 4U - yoe / 100U + doy; // [0, 146096]
|
||||
return era * 146097 + static_cast<std::int64_t>(doe) - 719468;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool is_leap_year(std::int32_t y) noexcept
|
||||
{
|
||||
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t
|
||||
days_in_month(std::int32_t y, std::uint32_t m) noexcept
|
||||
{
|
||||
switch (m) {
|
||||
case 1:
|
||||
case 3:
|
||||
case 5:
|
||||
case 7:
|
||||
case 8:
|
||||
case 10:
|
||||
case 12:
|
||||
return 31U;
|
||||
case 4:
|
||||
case 6:
|
||||
case 9:
|
||||
case 11:
|
||||
return 30U;
|
||||
case 2:
|
||||
return is_leap_year(y) ? 29U : 28U;
|
||||
default:
|
||||
return 30U;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::int32_t>
|
||||
parse_fixed_offset_minutes(std::string_view tz) noexcept
|
||||
{
|
||||
if (tz == "UTC" || tz == "Z") {
|
||||
return 0;
|
||||
}
|
||||
if (tz.starts_with("UTC")) {
|
||||
tz.remove_prefix(3U);
|
||||
}
|
||||
if (tz.size() != 6U || (tz[0] != '+' && tz[0] != '-') ||
|
||||
tz[3] != ':') {
|
||||
return std::nullopt;
|
||||
}
|
||||
const int sign = tz[0] == '-' ? -1 : 1;
|
||||
std::uint32_t hh = 0;
|
||||
std::uint32_t mm = 0;
|
||||
auto r1 = std::from_chars(tz.data() + 1, tz.data() + 3, hh);
|
||||
auto r2 = std::from_chars(tz.data() + 4, tz.data() + 6, mm);
|
||||
if (r1.ec != std::errc{} || r1.ptr != tz.data() + 3 ||
|
||||
r2.ec != std::errc{} || r2.ptr != tz.data() + 6 || hh > 14U ||
|
||||
mm > 59U || (hh == 14U && mm > 0U)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return sign * static_cast<std::int32_t>(hh * 60U + mm);
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<std::uint64_t> parse_field(std::string_view field,
|
||||
std::uint32_t min_val,
|
||||
std::uint32_t max_val,
|
||||
bool map_7_to_0 = false)
|
||||
{
|
||||
if (field.empty()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar empty field"));
|
||||
}
|
||||
std::uint64_t mask = 0;
|
||||
std::size_t pos = 0;
|
||||
while (pos <= field.size()) {
|
||||
const std::size_t comma = field.find(',', pos);
|
||||
const std::string_view part =
|
||||
comma == std::string_view::npos
|
||||
? field.substr(pos)
|
||||
: field.substr(pos, comma - pos);
|
||||
if (part.empty()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar empty list item"));
|
||||
}
|
||||
|
||||
std::string_view range_part = part;
|
||||
std::uint32_t step = 1;
|
||||
if (const std::size_t slash = part.find('/');
|
||||
slash != std::string_view::npos) {
|
||||
range_part = part.substr(0, slash);
|
||||
const std::string_view step_sv = part.substr(slash + 1);
|
||||
if (step_sv.empty() || step_sv.find('/') !=
|
||||
std::string_view::npos) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar invalid step syntax"));
|
||||
}
|
||||
auto sr = std::from_chars(
|
||||
step_sv.data(), step_sv.data() + step_sv.size(), step);
|
||||
if (sr.ec != std::errc{} ||
|
||||
sr.ptr != step_sv.data() + step_sv.size() ||
|
||||
step == 0U) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar step must be positive"));
|
||||
}
|
||||
}
|
||||
|
||||
std::uint32_t lo = min_val;
|
||||
std::uint32_t hi = max_val;
|
||||
const std::uint32_t parse_max = map_7_to_0 ? 7U : max_val;
|
||||
|
||||
if (range_part == "*") {
|
||||
lo = min_val;
|
||||
hi = max_val;
|
||||
} else if (const std::size_t dash = range_part.find('-');
|
||||
dash != std::string_view::npos) {
|
||||
const std::string_view a_sv = range_part.substr(0, dash);
|
||||
const std::string_view b_sv = range_part.substr(dash + 1);
|
||||
if (a_sv.empty() || b_sv.empty() ||
|
||||
b_sv.find('-') != std::string_view::npos) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar invalid range syntax"));
|
||||
}
|
||||
auto r1 = std::from_chars(
|
||||
a_sv.data(), a_sv.data() + a_sv.size(), lo);
|
||||
auto r2 = std::from_chars(
|
||||
b_sv.data(), b_sv.data() + b_sv.size(), hi);
|
||||
if (r1.ec != std::errc{} ||
|
||||
r1.ptr != a_sv.data() + a_sv.size() ||
|
||||
r2.ec != std::errc{} ||
|
||||
r2.ptr != b_sv.data() + b_sv.size() || lo < min_val ||
|
||||
hi > parse_max || lo > hi) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar range bounds invalid"));
|
||||
}
|
||||
} else {
|
||||
std::uint32_t val = 0;
|
||||
auto rv = std::from_chars(
|
||||
range_part.data(),
|
||||
range_part.data() + range_part.size(), val);
|
||||
if (rv.ec != std::errc{} ||
|
||||
rv.ptr != range_part.data() + range_part.size() ||
|
||||
val < min_val || val > parse_max) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar field value out of range"));
|
||||
}
|
||||
lo = val;
|
||||
hi = (part.find('/') != std::string_view::npos) ? max_val
|
||||
: val;
|
||||
}
|
||||
|
||||
for (std::uint32_t v = lo; v <= hi; v += step) {
|
||||
const std::uint32_t bit =
|
||||
(map_7_to_0 && v == 7U) ? 0U : v;
|
||||
mask |= (1ULL << bit);
|
||||
if (hi - v < step) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (comma == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = comma + 1;
|
||||
}
|
||||
if (mask == 0ULL) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar field matched zero values"));
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::int64_t civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
|
||||
std::uint32_t day, std::uint32_t hour,
|
||||
std::uint32_t minute) noexcept
|
||||
{
|
||||
const std::int64_t days = days_from_civil(year, month, day);
|
||||
return days * 1440LL + static_cast<std::int64_t>(hour) * 60LL +
|
||||
static_cast<std::int64_t>(minute);
|
||||
}
|
||||
|
||||
CivilMinute epoch_minute_to_civil(std::int64_t epoch_minute) noexcept
|
||||
{
|
||||
std::int64_t days = epoch_minute / 1440LL;
|
||||
std::int64_t rem = epoch_minute % 1440LL;
|
||||
if (rem < 0) {
|
||||
rem += 1440LL;
|
||||
--days;
|
||||
}
|
||||
const auto hour = static_cast<std::uint32_t>(rem / 60LL);
|
||||
const auto minute = static_cast<std::uint32_t>(rem % 60LL);
|
||||
|
||||
const std::int64_t z = days + 719468;
|
||||
const std::int64_t era = (z >= 0 ? z : z - 146096) / 146097;
|
||||
const auto doe =
|
||||
static_cast<std::uint64_t>(z - era * 146097); // [0, 146096]
|
||||
const std::uint64_t yoe =
|
||||
(doe - doe / 1460U + doe / 36524U - doe / 146096U) /
|
||||
365U; // [0, 399]
|
||||
const std::int64_t y = static_cast<std::int64_t>(yoe) + era * 400;
|
||||
const std::uint64_t doy =
|
||||
doe - (365U * yoe + yoe / 4U - yoe / 100U); // [0, 365]
|
||||
const std::uint64_t mp = (5U * doy + 2U) / 153U; // [0, 11]
|
||||
const auto d = static_cast<std::uint32_t>(
|
||||
doy - (153U * mp + 2U) / 5U + 1U); // [1, 31]
|
||||
const auto m =
|
||||
static_cast<std::uint32_t>(mp < 10U ? mp + 3U : mp - 9U); // [1, 12]
|
||||
const auto year = static_cast<std::int32_t>(y + (m <= 2U ? 1 : 0));
|
||||
|
||||
// 1970-01-01 was Thursday (4).
|
||||
std::int64_t wd = (days + 4LL) % 7LL;
|
||||
if (wd < 0) {
|
||||
wd += 7LL;
|
||||
}
|
||||
|
||||
return CivilMinute{
|
||||
.year = year,
|
||||
.month = m,
|
||||
.day = d,
|
||||
.hour = hour,
|
||||
.minute = minute,
|
||||
.weekday = static_cast<std::uint32_t>(wd),
|
||||
};
|
||||
}
|
||||
|
||||
// ── TimezoneRegistry ──────────────────────────────────────────────────────
|
||||
|
||||
void TimezoneRegistry::register_dst_zone(DstTransitionRule rule)
|
||||
{
|
||||
if (!rule.name.empty()) {
|
||||
m_dst_zones[rule.name] = std::move(rule);
|
||||
}
|
||||
}
|
||||
|
||||
Result<void> TimezoneRegistry::validate_timezone(std::string_view tz) const
|
||||
{
|
||||
if (parse_fixed_offset_minutes(tz).has_value() ||
|
||||
m_dst_zones.contains(tz)) {
|
||||
return {};
|
||||
}
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported or unknown timezone '" + std::string{tz} +
|
||||
"' (silent UTC fallback is forbidden)"));
|
||||
}
|
||||
|
||||
Result<std::vector<ResolvedSlot>> TimezoneRegistry::resolve_local_minute(
|
||||
std::string_view tz, std::int64_t local_epoch_minute,
|
||||
DstGapPolicy gap_policy, DstFoldPolicy fold_policy) const
|
||||
{
|
||||
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
|
||||
const std::int64_t utc_min =
|
||||
local_epoch_minute - static_cast<std::int64_t>(*fixed);
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
|
||||
}
|
||||
|
||||
auto it = m_dst_zones.find(tz);
|
||||
if (it == m_dst_zones.end()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
|
||||
}
|
||||
|
||||
const auto& rule = it->second;
|
||||
|
||||
// Check spring-forward gap window.
|
||||
if (rule.gap_start_local_min.has_value() &&
|
||||
rule.gap_end_local_min.has_value() &&
|
||||
local_epoch_minute >= *rule.gap_start_local_min &&
|
||||
local_epoch_minute < *rule.gap_end_local_min) {
|
||||
if (gap_policy == DstGapPolicy::Skip) {
|
||||
return std::vector<ResolvedSlot>{};
|
||||
}
|
||||
const std::int64_t shifted_utc_min =
|
||||
*rule.gap_end_local_min -
|
||||
static_cast<std::int64_t>(rule.dst_offset_minutes);
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = shifted_utc_min * 60000LL,
|
||||
.fold_index = 0,
|
||||
}};
|
||||
}
|
||||
|
||||
// Check fall-back fold window.
|
||||
if (rule.fold_start_local_min.has_value() &&
|
||||
rule.fold_end_local_min.has_value() &&
|
||||
local_epoch_minute >= *rule.fold_start_local_min &&
|
||||
local_epoch_minute < *rule.fold_end_local_min) {
|
||||
const std::int64_t first_utc_min =
|
||||
local_epoch_minute -
|
||||
static_cast<std::int64_t>(rule.dst_offset_minutes);
|
||||
const std::int64_t second_utc_min =
|
||||
local_epoch_minute -
|
||||
static_cast<std::int64_t>(rule.standard_offset_minutes);
|
||||
switch (fold_policy) {
|
||||
case DstFoldPolicy::First:
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = first_utc_min * 60000LL, .fold_index = 0}};
|
||||
case DstFoldPolicy::Second:
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = second_utc_min * 60000LL, .fold_index = 1}};
|
||||
case DstFoldPolicy::Twice:
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = first_utc_min * 60000LL,
|
||||
.fold_index = 0},
|
||||
ResolvedSlot{.utc_ms = second_utc_min * 60000LL,
|
||||
.fold_index = 1},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Outside gap/fold: determine whether DST or standard offset applies.
|
||||
bool in_dst = false;
|
||||
if (rule.gap_end_local_min.has_value() &&
|
||||
rule.fold_start_local_min.has_value()) {
|
||||
in_dst = (local_epoch_minute >= *rule.gap_end_local_min &&
|
||||
local_epoch_minute < *rule.fold_start_local_min);
|
||||
} else if (rule.gap_end_local_min.has_value()) {
|
||||
in_dst = (local_epoch_minute >= *rule.gap_end_local_min);
|
||||
}
|
||||
const std::int32_t off =
|
||||
in_dst ? rule.dst_offset_minutes : rule.standard_offset_minutes;
|
||||
const std::int64_t utc_min =
|
||||
local_epoch_minute - static_cast<std::int64_t>(off);
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
|
||||
}
|
||||
|
||||
Result<std::pair<std::int64_t, std::int64_t>>
|
||||
TimezoneRegistry::local_minute_bounds(std::string_view tz,
|
||||
std::int64_t utc_min_lo,
|
||||
std::int64_t utc_min_hi) const
|
||||
{
|
||||
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
|
||||
return std::pair{utc_min_lo + *fixed, utc_min_hi + *fixed};
|
||||
}
|
||||
auto it = m_dst_zones.find(tz);
|
||||
if (it == m_dst_zones.end()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
|
||||
}
|
||||
const std::int32_t min_off = std::min(it->second.standard_offset_minutes,
|
||||
it->second.dst_offset_minutes);
|
||||
const std::int32_t max_off = std::max(it->second.standard_offset_minutes,
|
||||
it->second.dst_offset_minutes);
|
||||
return std::pair{utc_min_lo + min_off - 120LL,
|
||||
utc_min_hi + max_off + 120LL};
|
||||
}
|
||||
|
||||
// ── CalendarExpression ────────────────────────────────────────────────────
|
||||
|
||||
Result<CalendarExpression>
|
||||
CalendarExpression::parse(std::string_view expression)
|
||||
{
|
||||
std::vector<std::string_view> tokens;
|
||||
std::size_t i = 0;
|
||||
while (i < expression.size()) {
|
||||
while (i < expression.size() &&
|
||||
(expression[i] == ' ' || expression[i] == '\t')) {
|
||||
++i;
|
||||
}
|
||||
if (i >= expression.size()) {
|
||||
break;
|
||||
}
|
||||
const std::size_t start = i;
|
||||
while (i < expression.size() && expression[i] != ' ' &&
|
||||
expression[i] != '\t') {
|
||||
++i;
|
||||
}
|
||||
tokens.push_back(expression.substr(start, i - start));
|
||||
}
|
||||
|
||||
if (tokens.size() != 5U) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::CalendarExpression requires exactly 5 fields "
|
||||
"(minute hour day month weekday)"));
|
||||
}
|
||||
|
||||
auto min_m = parse_field(tokens[0], 0, 59);
|
||||
if (!min_m.has_value()) return Void::Result::fail(min_m.error());
|
||||
auto hr_m = parse_field(tokens[1], 0, 23);
|
||||
if (!hr_m.has_value()) return Void::Result::fail(hr_m.error());
|
||||
auto day_m = parse_field(tokens[2], 1, 31);
|
||||
if (!day_m.has_value()) return Void::Result::fail(day_m.error());
|
||||
auto mon_m = parse_field(tokens[3], 1, 12);
|
||||
if (!mon_m.has_value()) return Void::Result::fail(mon_m.error());
|
||||
auto wd_m = parse_field(tokens[4], 0, 6, true);
|
||||
if (!wd_m.has_value()) return Void::Result::fail(wd_m.error());
|
||||
|
||||
CalendarExpression expr{};
|
||||
expr.m_minutes = *min_m;
|
||||
expr.m_hours = static_cast<std::uint32_t>(*hr_m);
|
||||
expr.m_days = static_cast<std::uint32_t>(*day_m);
|
||||
expr.m_months = static_cast<std::uint32_t>(*mon_m);
|
||||
expr.m_weekdays = static_cast<std::uint32_t>(*wd_m);
|
||||
return expr;
|
||||
}
|
||||
|
||||
bool CalendarExpression::matches(const CivilMinute& cm) const noexcept
|
||||
{
|
||||
return ((m_minutes & (1ULL << cm.minute)) != 0ULL) &&
|
||||
((m_hours & (1U << cm.hour)) != 0U) &&
|
||||
((m_days & (1U << cm.day)) != 0U) &&
|
||||
((m_months & (1U << cm.month)) != 0U) &&
|
||||
((m_weekdays & (1U << cm.weekday)) != 0U);
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> CalendarExpression::next_matching_minute(
|
||||
std::int64_t from_local_min, std::int64_t max_local_min) const noexcept
|
||||
{
|
||||
if (from_local_min > max_local_min) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::int64_t cur = from_local_min;
|
||||
// Guard iteration count against unsatisfiable combinations (e.g. Feb 31).
|
||||
for (int guard = 0; guard < 100000 && cur <= max_local_min; ++guard) {
|
||||
const CivilMinute cm = epoch_minute_to_civil(cur);
|
||||
if ((m_months & (1U << cm.month)) == 0U) {
|
||||
std::int32_t ny = cm.year;
|
||||
std::uint32_t nm = cm.month + 1U;
|
||||
if (nm > 12U) {
|
||||
nm = 1U;
|
||||
++ny;
|
||||
}
|
||||
cur = civil_to_epoch_minute(ny, nm, 1U, 0U, 0U);
|
||||
continue;
|
||||
}
|
||||
if ((m_days & (1U << cm.day)) == 0U ||
|
||||
(m_weekdays & (1U << cm.weekday)) == 0U) {
|
||||
// Jump to 00:00 of next day.
|
||||
const std::int64_t next_day_min =
|
||||
civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) +
|
||||
1440LL;
|
||||
cur = next_day_min;
|
||||
continue;
|
||||
}
|
||||
if ((m_hours & (1U << cm.hour)) == 0U) {
|
||||
const std::int64_t next_hr_min =
|
||||
civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
|
||||
0U) +
|
||||
60LL;
|
||||
cur = next_hr_min;
|
||||
continue;
|
||||
}
|
||||
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
|
||||
++cur;
|
||||
continue;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> CalendarExpression::prev_matching_minute(
|
||||
std::int64_t from_local_min, std::int64_t min_local_min) const noexcept
|
||||
{
|
||||
if (from_local_min < min_local_min) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::int64_t cur = from_local_min;
|
||||
for (int guard = 0; guard < 100000 && cur >= min_local_min; ++guard) {
|
||||
const CivilMinute cm = epoch_minute_to_civil(cur);
|
||||
if ((m_months & (1U << cm.month)) == 0U) {
|
||||
std::int32_t py = cm.year;
|
||||
std::uint32_t pm = cm.month - 1U;
|
||||
if (pm == 0U) {
|
||||
pm = 12U;
|
||||
--py;
|
||||
}
|
||||
cur = civil_to_epoch_minute(py, pm, days_in_month(py, pm), 23U,
|
||||
59U);
|
||||
continue;
|
||||
}
|
||||
if ((m_days & (1U << cm.day)) == 0U ||
|
||||
(m_weekdays & (1U << cm.weekday)) == 0U) {
|
||||
// Jump to 23:59 of previous day.
|
||||
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) -
|
||||
1LL;
|
||||
continue;
|
||||
}
|
||||
if ((m_hours & (1U << cm.hour)) == 0U) {
|
||||
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
|
||||
0U) -
|
||||
1LL;
|
||||
continue;
|
||||
}
|
||||
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
|
||||
--cur;
|
||||
continue;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Result<MaterializedSlots> CalendarExpression::materialize_range(
|
||||
const CalendarSpec& spec, const TimezoneRegistry& tz_registry,
|
||||
std::int64_t after_utc_ms, std::int64_t up_to_utc_ms,
|
||||
MisfirePolicy misfire, std::size_t max_catch_up) const
|
||||
{
|
||||
if (auto tz_ok = tz_registry.validate_timezone(spec.timezone);
|
||||
!tz_ok.has_value()) {
|
||||
return Void::Result::fail(tz_ok.error());
|
||||
}
|
||||
|
||||
MaterializedSlots out{};
|
||||
out.next_cursor_utc_ms = after_utc_ms;
|
||||
if (up_to_utc_ms <= after_utc_ms) {
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::int64_t utc_min_lo = after_utc_ms / 60000LL - 1LL;
|
||||
const std::int64_t utc_min_hi = up_to_utc_ms / 60000LL + 1LL;
|
||||
auto bounds =
|
||||
tz_registry.local_minute_bounds(spec.timezone, utc_min_lo, utc_min_hi);
|
||||
if (!bounds.has_value()) {
|
||||
return Void::Result::fail(bounds.error());
|
||||
}
|
||||
const auto [local_lo, local_hi] = *bounds;
|
||||
|
||||
if (misfire == MisfirePolicy::Skip) {
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
if (misfire == MisfirePolicy::CoalesceLatest) {
|
||||
// Scan backward from local_hi to coalesce arbitrarily many missed
|
||||
// slots (even millions) in bounded O(1) jumps!
|
||||
std::int64_t probe = local_hi;
|
||||
std::optional<ResolvedSlot> best{};
|
||||
while (probe >= local_lo) {
|
||||
auto found = prev_matching_minute(probe, local_lo);
|
||||
if (!found.has_value()) {
|
||||
break;
|
||||
}
|
||||
auto resolved = tz_registry.resolve_local_minute(
|
||||
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
|
||||
if (!resolved.has_value()) {
|
||||
return Void::Result::fail(resolved.error());
|
||||
}
|
||||
for (const auto& slot : *resolved) {
|
||||
if (slot.utc_ms > after_utc_ms &&
|
||||
slot.utc_ms <= up_to_utc_ms) {
|
||||
if (!best.has_value() ||
|
||||
slot.utc_ms > best->utc_ms ||
|
||||
(slot.utc_ms == best->utc_ms &&
|
||||
slot.fold_index > best->fold_index)) {
|
||||
best = slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (best.has_value()) {
|
||||
break;
|
||||
}
|
||||
probe = *found - 1LL;
|
||||
}
|
||||
if (best.has_value()) {
|
||||
out.slots.push_back(*best);
|
||||
}
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
// CatchUpBounded: scan forward up to `max_catch_up` slots, preserving
|
||||
// remaining cursor state when more slots remain!
|
||||
const std::size_t cap = max_catch_up > 0U ? max_catch_up : 1U;
|
||||
std::int64_t probe = local_lo;
|
||||
while (probe <= local_hi) {
|
||||
auto found = next_matching_minute(probe, local_hi);
|
||||
if (!found.has_value()) {
|
||||
break;
|
||||
}
|
||||
auto resolved = tz_registry.resolve_local_minute(
|
||||
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
|
||||
if (!resolved.has_value()) {
|
||||
return Void::Result::fail(resolved.error());
|
||||
}
|
||||
for (const auto& slot : *resolved) {
|
||||
if (slot.utc_ms > after_utc_ms && slot.utc_ms <= up_to_utc_ms) {
|
||||
if (out.slots.size() < cap) {
|
||||
out.slots.push_back(slot);
|
||||
out.next_cursor_utc_ms =
|
||||
std::max(out.next_cursor_utc_ms, slot.utc_ms);
|
||||
} else {
|
||||
out.more_pending = true;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
probe = *found + 1LL;
|
||||
}
|
||||
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Scheduler
|
||||
INTERNAL_DEPS Core Functional Time Async
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(SchedulerStorage
|
||||
INTERNAL_DEPS Scheduler Storage
|
||||
)
|
||||
@@ -323,6 +323,11 @@ if(_has_discovery)
|
||||
run_consumer(DiscoveryOnly "${install_prefix}" "DiscoveryOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_scheduler Scheduler Core Functional Time Async)
|
||||
if(_has_scheduler)
|
||||
run_consumer(SchedulerOnly "${install_prefix}" "SchedulerOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidSchedulerOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void REQUIRED CONFIG COMPONENTS Scheduler)
|
||||
|
||||
add_executable(scheduler_only main.cpp)
|
||||
target_link_libraries(scheduler_only PRIVATE Void::Scheduler)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME scheduler_only COMMAND scheduler_only)
|
||||
@@ -0,0 +1,41 @@
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Time::ManualClock mono{};
|
||||
auto sched = Void::Scheduler::Scheduler::create(
|
||||
Void::Scheduler::SchedulerOptions{.monotonic_clock = &mono});
|
||||
if (!sched.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
int ran = 0;
|
||||
if (!sched->register_handler(
|
||||
"ping",
|
||||
[&](const Void::Scheduler::OccurrenceContext&,
|
||||
std::span<const std::byte>,
|
||||
Void::Async::OperationOptions)
|
||||
-> Void::Scheduler::Result<void> {
|
||||
++ran;
|
||||
return {};
|
||||
})
|
||||
.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
Void::Scheduler::JobSpec spec{};
|
||||
spec.id = "j1";
|
||||
spec.handler_id = "ping";
|
||||
spec.schedule = Void::Scheduler::Schedule::one_shot_monotonic(mono.now());
|
||||
if (!sched->add_job(spec).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
auto count = sched->tick();
|
||||
if (!count.has_value() || *count != 1U || ran != 1) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!sched->close_and_join().has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
Void::Testing::Test scheduler_fake_clock_ordering_retries_and_dead_letter()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
// Deterministic RNG yielding 500ms full-jitter delay (500 % (1000+1) = 500).
|
||||
std::uint64_t rng_val = 500ULL;
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "unit-1",
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = [&]() { return rng_val; },
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
std::vector<std::string> order;
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"record",
|
||||
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
order.push_back(ctx.id.job_id);
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
int fail_calls = 0;
|
||||
OccurrenceId failed_id{};
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"always_fail",
|
||||
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
++fail_calls;
|
||||
failed_id = ctx.id;
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::HandlerFailed, "boom"));
|
||||
})
|
||||
.has_value());
|
||||
|
||||
// Add later job first, earlier job second -> heap must order by due_time.
|
||||
JobSpec late{};
|
||||
late.id = "job-late";
|
||||
late.handler_id = "record";
|
||||
late.schedule = Schedule::one_shot_monotonic(mono.now() + 5s);
|
||||
Void::Testing::require(sched->add_job(late).has_value());
|
||||
|
||||
JobSpec early{};
|
||||
early.id = "job-early";
|
||||
early.handler_id = "record";
|
||||
early.schedule = Schedule::one_shot_monotonic(mono.now() + 2s);
|
||||
Void::Testing::require(sched->add_job(early).has_value());
|
||||
|
||||
// Clock jumps past both -> must run early before late!
|
||||
Void::Testing::require(mono.advance(10s).has_value());
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 2ULL);
|
||||
Void::Testing::require(order.size() == 2U);
|
||||
Void::Testing::expect_eq(order[0], std::string{"job-early"});
|
||||
Void::Testing::expect_eq(order[1], std::string{"job-late"});
|
||||
|
||||
// Retry exhaustion -> Dead status keeping same OccurrenceId!
|
||||
JobSpec flaky{};
|
||||
flaky.id = "job-flaky";
|
||||
flaky.handler_id = "always_fail";
|
||||
flaky.schedule = Schedule::one_shot_monotonic(mono.now());
|
||||
flaky.retry.max_attempts = 3;
|
||||
flaky.retry.base_delay = 1s;
|
||||
flaky.retry.max_delay = 10s;
|
||||
flaky.retry.multiplier = 2;
|
||||
Void::Testing::require(sched->add_job(flaky).has_value());
|
||||
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
auto r = sched->tick();
|
||||
Void::Testing::require(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 1ULL);
|
||||
Void::Testing::require(mono.advance(10s).has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(fail_calls, 3);
|
||||
auto st = sched->stats();
|
||||
Void::Testing::require(st.has_value());
|
||||
Void::Testing::expect_eq(st->dead, 1ULL);
|
||||
|
||||
// Dead records cannot be pruned until explicitly acknowledged.
|
||||
auto prune0 = sched->prune_completed();
|
||||
Void::Testing::require(prune0.has_value());
|
||||
Void::Testing::expect_eq(*prune0, 0ULL);
|
||||
Void::Testing::require(sched->acknowledge_dead(failed_id).has_value());
|
||||
auto prune1 = sched->prune_completed();
|
||||
Void::Testing::require(prune1.has_value());
|
||||
Void::Testing::expect_eq(*prune1, 1ULL);
|
||||
|
||||
auto report = sched->close_and_join();
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(report->complete);
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_calendar_dst_misfire_and_unknown_tz()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
|
||||
TimezoneRegistry tz{};
|
||||
// Reject unknown timezone without silent UTC fallback.
|
||||
auto bad_tz = tz.validate_timezone("Mars/Olympus_Mons");
|
||||
Void::Testing::expect(!bad_tz.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_tz.error().code().value,
|
||||
static_cast<std::int32_t>(SchedulerErrorCode::UnsupportedTimezone));
|
||||
|
||||
// Fixed offset +02:00 works cleanly.
|
||||
Void::Testing::expect(tz.validate_timezone("UTC+02:00").has_value());
|
||||
|
||||
// Register deterministic DST zone:
|
||||
// Gap: 2026-03-08 02:00..03:00 local (spring forward -05:00 -> -04:00)
|
||||
// Fold: 2026-11-01 01:00..02:00 local (fall back -04:00 -> -05:00)
|
||||
DstTransitionRule rule{};
|
||||
rule.name = "Test/DST";
|
||||
rule.standard_offset_minutes = -300;
|
||||
rule.dst_offset_minutes = -240;
|
||||
rule.gap_start_local_min = civil_to_epoch_minute(2026, 3, 8, 2, 0);
|
||||
rule.gap_end_local_min = civil_to_epoch_minute(2026, 3, 8, 3, 0);
|
||||
rule.fold_start_local_min = civil_to_epoch_minute(2026, 11, 1, 1, 0);
|
||||
rule.fold_end_local_min = civil_to_epoch_minute(2026, 11, 1, 2, 0);
|
||||
tz.register_dst_zone(rule);
|
||||
|
||||
// Gap policy Skip omits 02:30 on 2026-03-08.
|
||||
const std::int64_t gap_min = civil_to_epoch_minute(2026, 3, 8, 2, 30);
|
||||
auto skipped = tz.resolve_local_minute("Test/DST", gap_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::First);
|
||||
Void::Testing::require(skipped.has_value());
|
||||
Void::Testing::expect(skipped->empty());
|
||||
|
||||
// Fold policy First yields fold_index=0; Twice yields both fold 0 and 1!
|
||||
const std::int64_t fold_min = civil_to_epoch_minute(2026, 11, 1, 1, 30);
|
||||
auto first_only = tz.resolve_local_minute("Test/DST", fold_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::First);
|
||||
Void::Testing::require(first_only.has_value());
|
||||
Void::Testing::require(first_only->size() == 1U);
|
||||
Void::Testing::expect_eq(first_only->front().fold_index,
|
||||
static_cast<std::uint8_t>(0));
|
||||
|
||||
auto twice = tz.resolve_local_minute("Test/DST", fold_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::Twice);
|
||||
Void::Testing::require(twice.has_value());
|
||||
Void::Testing::require(twice->size() == 2U);
|
||||
Void::Testing::expect_eq((*twice)[0].fold_index,
|
||||
static_cast<std::uint8_t>(0));
|
||||
Void::Testing::expect_eq((*twice)[1].fold_index,
|
||||
static_cast<std::uint8_t>(1));
|
||||
Void::Testing::expect_eq((*twice)[1].utc_ms - (*twice)[0].utc_ms,
|
||||
3600LL * 1000LL);
|
||||
|
||||
// CoalesceLatest over >2,000,000 missed minutes executes immediately in
|
||||
// bounded time and returns the single latest slot!
|
||||
auto every_min = CalendarExpression::parse("* * * * *");
|
||||
Void::Testing::require(every_min.has_value());
|
||||
const std::int64_t t0 =
|
||||
civil_to_epoch_minute(2020, 1, 1, 0, 0) * 60000LL;
|
||||
const std::int64_t t1 =
|
||||
civil_to_epoch_minute(2025, 1, 1, 0, 0) * 60000LL; // ~2.63M minutes!
|
||||
CalendarSpec cspec{.expression = "* * * * *", .timezone = "UTC"};
|
||||
auto coalesced = every_min->materialize_range(
|
||||
cspec, tz, t0, t1, MisfirePolicy::CoalesceLatest, 100);
|
||||
Void::Testing::require(coalesced.has_value());
|
||||
Void::Testing::require(coalesced->slots.size() == 1U);
|
||||
Void::Testing::expect_eq(coalesced->slots[0].utc_ms, t1);
|
||||
|
||||
// CatchUpBounded caps strictly at 100 slots/pass preserving cursor state!
|
||||
auto bounded = every_min->materialize_range(
|
||||
cspec, tz, t0, t1, MisfirePolicy::CatchUpBounded, 100);
|
||||
Void::Testing::require(bounded.has_value());
|
||||
Void::Testing::expect_eq(bounded->slots.size(), 100ULL);
|
||||
Void::Testing::expect(bounded->more_pending);
|
||||
Void::Testing::expect_eq(bounded->next_cursor_utc_ms,
|
||||
t0 + 100LL * 60000LL);
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_overlap_revision_edit_and_shutdown_timeout()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "unit-overlap",
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
std::mutex gate_mu;
|
||||
std::condition_variable gate_cv;
|
||||
bool entered = false;
|
||||
bool release = false;
|
||||
std::atomic<int> concurrent_now{0};
|
||||
std::atomic<int> max_concurrent_seen{0};
|
||||
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"slow",
|
||||
[&](const OccurrenceContext&, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
const int c = ++concurrent_now;
|
||||
int prev = max_concurrent_seen.load();
|
||||
while (c > prev &&
|
||||
!max_concurrent_seen.compare_exchange_weak(prev, c)) {
|
||||
}
|
||||
{
|
||||
std::lock_guard lk{gate_mu};
|
||||
entered = true;
|
||||
}
|
||||
gate_cv.notify_all();
|
||||
{
|
||||
std::unique_lock lk{gate_mu};
|
||||
gate_cv.wait(lk, [&] { return release; });
|
||||
}
|
||||
--concurrent_now;
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
JobSpec job{};
|
||||
job.id = "j-forbid";
|
||||
job.handler_id = "slow";
|
||||
job.schedule = Schedule::fixed_rate(1s, mono.now());
|
||||
job.misfire = MisfirePolicy::CatchUpBounded;
|
||||
job.overlap = OverlapPolicy::Forbid;
|
||||
Void::Testing::require(sched->add_job(job).has_value());
|
||||
|
||||
// Advance 3s -> materializes multiple due slots, but Overlap::Forbid must
|
||||
// never allow 2 concurrent executions of the same job.
|
||||
Void::Testing::require(mono.advance(2s).has_value());
|
||||
|
||||
std::thread worker([&] { (void)sched->tick(); });
|
||||
|
||||
{
|
||||
std::unique_lock lk{gate_mu};
|
||||
gate_cv.wait(lk, [&] { return entered; });
|
||||
}
|
||||
|
||||
// Second concurrent dispatch_one must be blocked by Overlap::Forbid!
|
||||
auto blocked = sched->dispatch_one();
|
||||
Void::Testing::require(blocked.has_value());
|
||||
Void::Testing::expect(!*blocked);
|
||||
Void::Testing::expect_eq(max_concurrent_seen.load(), 1);
|
||||
|
||||
// Invalid update_job must fail without mutating active policy.
|
||||
JobSpec bad_update = job;
|
||||
bad_update.schedule = Schedule::calendar_schedule(
|
||||
CalendarSpec{.expression = "bad cron", .timezone = "UTC"});
|
||||
Void::Testing::expect(!sched->update_job(bad_update).has_value());
|
||||
|
||||
// Valid update_job bumps revision to 2 and invalidates unstarted rev-1
|
||||
// pending occurrences!
|
||||
JobSpec good_update = job;
|
||||
good_update.payload = {std::byte{0x42}};
|
||||
auto rev2 = sched->update_job(good_update);
|
||||
Void::Testing::require(rev2.has_value());
|
||||
Void::Testing::expect_eq(*rev2, 2ULL);
|
||||
|
||||
// close_and_join with already-expired deadline returns incomplete report
|
||||
// listing the live occurrence instead of erasing running state!
|
||||
auto inc = sched->close_and_join(
|
||||
Void::Async::OperationOptions{.deadline = mono.now()});
|
||||
Void::Testing::require(inc.has_value());
|
||||
Void::Testing::expect(!inc->complete);
|
||||
Void::Testing::expect_eq(inc->live_occurrences.size(), 1ULL);
|
||||
|
||||
// Unblock active handler and join cleanly.
|
||||
{
|
||||
std::lock_guard lk{gate_mu};
|
||||
release = true;
|
||||
}
|
||||
gate_cv.notify_all();
|
||||
worker.join();
|
||||
|
||||
auto done = sched->close_and_join();
|
||||
Void::Testing::require(done.has_value());
|
||||
Void::Testing::expect(done->complete);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
#include <Void/SchedulerStorage/StorageJobStore.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
Void::Testing::Test scheduler_storage_durable_recovery_ownership_and_retention()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace Void::SchedulerStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_sched_store_"};
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
OccurrenceId first_id{};
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto store1 = std::make_shared<StorageJobStore>(*eng);
|
||||
auto store2 = std::make_shared<StorageJobStore>(*eng);
|
||||
|
||||
// Exclusive ownership lock rejects second owner!
|
||||
Void::Testing::require(store1->acquire_ownership("owner-A").has_value());
|
||||
auto second = store2->acquire_ownership("owner-B");
|
||||
Void::Testing::expect(!second.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
second.error().code().value,
|
||||
static_cast<std::int32_t>(SchedulerErrorCode::OwnershipLocked));
|
||||
Void::Testing::require(store1->release_ownership().has_value());
|
||||
|
||||
// Manually create a job & claim one occurrence (Pending -> Running),
|
||||
// then close engine WITHOUT completing to simulate a crash!
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "owner-A",
|
||||
.store = store1,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
JobSpec j{};
|
||||
j.id = "durable-job";
|
||||
j.handler_id = "h1";
|
||||
j.schedule = Schedule::one_shot_utc(to_utc_ms(civil.now()));
|
||||
Void::Testing::require(sched->add_job(j).has_value());
|
||||
|
||||
// Materialize without handler registered (stays Pending), then claim
|
||||
// directly through store to leave it durably Running across crash.
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 0ULL);
|
||||
|
||||
auto occs = store1->load_occurrences();
|
||||
Void::Testing::require(occs.has_value());
|
||||
Void::Testing::require(occs->size() == 1U);
|
||||
first_id = occs->front().id;
|
||||
|
||||
auto claimed = store1->claim_occurrence(first_id, 0);
|
||||
Void::Testing::require(claimed.has_value());
|
||||
Void::Testing::expect(claimed->status == OccurrenceStatus::Running);
|
||||
Void::Testing::expect_eq(claimed->attempt, 1U);
|
||||
|
||||
// Simulate crash: do NOT call complete_occurrence or
|
||||
// release_ownership; close engine cleanly for reopen.
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
|
||||
// Reopen after crash: recovery must return Running -> Pending preserving
|
||||
// the exact same OccurrenceId and execute at-least-once!
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto store = std::make_shared<StorageJobStore>(
|
||||
*eng, StorageJobStoreOptions{.recover_stale_owner = true});
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "owner-A-restarted",
|
||||
.store = store,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
OccurrenceId executed_id{};
|
||||
std::uint32_t executed_attempt = 0;
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"h1",
|
||||
[&](const OccurrenceContext& ctx,
|
||||
std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
executed_id = ctx.id;
|
||||
executed_attempt = ctx.attempt;
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 1ULL);
|
||||
Void::Testing::expect(executed_id == first_id);
|
||||
// Attempt incremented from 1 (pre-crash) -> 2 (post-crash redelivery)!
|
||||
Void::Testing::expect_eq(executed_attempt, 2U);
|
||||
|
||||
Void::Testing::require(sched->close_and_join().has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_storage_retention_cap_pauses_without_cursor_loss()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace Void::SchedulerStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_sched_ret_"};
|
||||
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
SchedulerLimits limits{};
|
||||
limits.max_retained_occurrences = 2;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
auto store = std::make_shared<StorageJobStore>(
|
||||
*eng, StorageJobStoreOptions{.limits = limits});
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "ret-owner",
|
||||
.store = store,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.limits = limits,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
JobSpec j{};
|
||||
j.id = "rate-job";
|
||||
j.handler_id = "h";
|
||||
j.schedule = Schedule::fixed_rate(1s, mono.now());
|
||||
j.misfire = MisfirePolicy::CatchUpBounded;
|
||||
Void::Testing::require(sched->add_job(j).has_value());
|
||||
|
||||
// Advance 3s -> 4 due slots exist, but retention cap is 2, so
|
||||
// materialization of all 4 is rejected WITHOUT advancing cursor!
|
||||
Void::Testing::require(mono.advance(3s).has_value());
|
||||
auto r = sched->tick();
|
||||
Void::Testing::require(r.has_value());
|
||||
auto jobs = sched->list_jobs();
|
||||
Void::Testing::require(jobs.has_value());
|
||||
Void::Testing::require(jobs->size() == 1U);
|
||||
Void::Testing::expect(!jobs->front().cursor_initialized);
|
||||
|
||||
Void::Testing::require(sched->close_and_join().has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
Reference in new issue
Block a user