Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/registry-schedulingctl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ workspace = true
registry-rstack-dev.workspace = true
registry-cli-report.workspace = true
anyhow.workspace = true
chrono.workspace = true
clap.workspace = true
registry-cli-api.workspace = true
registry-platform-audit.workspace = true
Expand All @@ -45,7 +46,6 @@ zeroize.workspace = true
# already demand. Asking for it here instead would turn it on for every build
# holding both crates, and the runtime's own database suite would then be
# compiled and run by shards that have no server to offer it.
chrono.workspace = true
registry-platform-provision = { workspace = true, features = ["test-support"] }
tokio-postgres.workspace = true

Expand Down
95 changes: 88 additions & 7 deletions crates/registry-schedulingctl/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@

//! Project loading and the offline init, check, test, and explain reports.
//!
//! Everything here runs without a network, a database, or a clock: the
//! authored policy, its records, and its fixtures are read from the project
//! directory through the shared reader, checked and replayed through the
//! pure core, and rendered as one JSON report per command. A refused project
//! is the reader's own report, every diagnostic at its position.
//! Init dates a new starter from today's UTC date. The other offline commands
//! read the policy, records, and fixtures through the shared reader and pure
//! core without reading the clock. A refused project is the reader's own
//! report, every diagnostic at its position.

use registry_platform_config::DeclaredPosture;
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use chrono::{NaiveDate, Utc};
use registry_platform_config::package::{plan_package, write_package};
use registry_platform_config::{sha256_uri, UNAVAILABLE_CODE};
use registry_platform_yaml::{Decoded, Diagnostic, Report, Source};
Expand All @@ -37,6 +37,10 @@ const FIXTURES_DIRECTORY: &str = "fixtures";
const NO_FIXTURES_CODE: &str = "scheduling.fixture.none";

pub(super) fn init(project: &Path, template: &str) -> Result<Value> {
init_on(project, template, Utc::now().date_naive())
}

fn init_on(project: &Path, template: &str, today: NaiveDate) -> Result<Value> {
let Some(files) = templates::template_files(template) else {
anyhow::bail!(
"unknown template {template:?}; available templates: standalone-exact-time, standalone-arrival-window, resource-reservations"
Expand All @@ -58,7 +62,8 @@ pub(super) fn init(project: &Path, template: &str) -> Result<Value> {
fs::create_dir(staging.path().join(FIXTURES_DIRECTORY))?;
let mut created = Vec::new();
for (relative, contents) in &files {
fs::write(staging.path().join(relative), contents)?;
let contents = templates::date_file(template, relative, contents, today);
fs::write(staging.path().join(relative), contents.as_bytes())?;
created.push((*relative).to_owned());
}
let staging_path = staging.keep();
Expand Down Expand Up @@ -856,13 +861,89 @@ fn absolute_lexical(path: &Path) -> std::io::Result<PathBuf> {
mod tests {
use super::*;
use registry_scheduling::config::RuntimeConfig;
use registry_scheduling_core::location_open_intervals;

#[test]
fn fresh_starters_publish_supply_after_the_original_example_dates() {
let root = tempfile::tempdir().unwrap();
let posture = registry_scheduling::config::DEFAULT_POSTURE;
for day in ["2027-01-01", "2028-02-29", "2037-11-02"] {
let today = day.parse::<chrono::NaiveDate>().unwrap();
let now = today.and_hms_opt(0, 0, 0).unwrap().and_utc();
for (template, expected_cases) in [
("standalone-exact-time", 8),
("standalone-arrival-window", 6),
("resource-reservations", 11),
] {
let project = root.path().join(day).join(template);
init_on(&project, template, today).unwrap();
let context = format!("{day} {template}");
let checked = check(&project, false, posture).unwrap();
assert_eq!(checked["diagnostics"], json!([]), "{context}");
let replay = test(&project, posture).unwrap();
let mut case_count = 0;
for fixture in replay["fixtures"].as_array().unwrap() {
assert_eq!(fixture["status"], "passed", "{context}: {fixture}");
for case in fixture["cases"].as_array().unwrap() {
assert_eq!(case["status"], "pass", "{context}: {case}");
case_count += 1;
}
}
assert_eq!(case_count, expected_cases, "{context}");

let authored = read_project(&project, true, posture).unwrap();
let policy = authored.policy.unwrap().value;
let facts = authored.facts.unwrap();
for offering in &policy.offerings {
let location = facts.location(&offering.location).unwrap();
let intervals =
location_open_intervals(&policy, &location.id, &location.timezone, &[])
.unwrap();
assert!(
intervals.iter().any(|open| open.end > now),
"{context}: {}",
offering.id
);
if let Some(arrival) = &offering.arrival {
let window = offering.served_windows(&facts.windows).next().unwrap();
assert!(window.start > now + chrono::TimeDelta::days(1), "{context}");
assert!(
window.start
< now + chrono::TimeDelta::days(i64::from(arrival.horizon_days)),
"{context}"
);
}
}
}
}
}

#[test]
fn init_reproduces_the_committed_examples_on_their_reference_date() {
let root = tempfile::tempdir().unwrap();
for template in [
"standalone-exact-time",
"standalone-arrival-window",
"resource-reservations",
] {
let project = root.path().join(template);
init_on(&project, template, templates::EXAMPLE_DATE).unwrap();
for (relative, bytes) in templates::template_files(template).unwrap() {
assert_eq!(
fs::read(project.join(relative)).unwrap(),
bytes.as_bytes(),
"{template}/{relative}"
);
}
}
}

/// A tempdir holding one freshly initialized template project, plus the
/// paths the tempdir keeps alive.
fn initialized(template: &str) -> (tempfile::TempDir, PathBuf) {
let root = tempfile::tempdir().unwrap();
let project = root.path().join("project");
init(&project, template).unwrap();
init_on(&project, template, templates::EXAMPLE_DATE).unwrap();
(root, project)
}

Expand Down
117 changes: 115 additions & 2 deletions crates/registry-schedulingctl/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,121 @@
//! Each template is a working project: its policy passes the check with zero
//! findings and its fixtures replay all-Pass offline, which the tests prove
//! end to end. The files are the committed examples under
//! `products/scheduling/examples`, so the two cannot drift, and every file
//! carries its schema modeline on its first line.
//! `products/scheduling/examples`, dated as of a common reference day.
//! Init moves their date groups together so the live supply is usable and
//! each fixture still proves the same scenario. Every file carries its
//! schema modeline on its first line.

use std::borrow::Cow;

use chrono::{Datelike, Days, NaiveDate, Weekday};

#[cfg(test)]
pub(super) const EXAMPLE_DATE: NaiveDate = example_date(10, 1);
const EXAMPLE_COUNTER: NaiveDate = example_date(10, 5);
const EXAMPLE_ARRIVAL: NaiveDate = example_date(10, 10);
const EXAMPLE_FOLD: NaiveDate = example_date(11, 1);

const fn example_date(month: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(2026, month, day).expect("valid starter reference date")
}

pub(super) fn date_file<'a>(
template: &str,
relative: &str,
contents: &'a str,
today: NaiveDate,
) -> Cow<'a, str> {
let counter_shift = || {
// The example opens on the Thursday before the Monday fixture. Shift
// by whole weeks and choose a Monday whose opening has begun today.
let monday = on_or_after(today - Days::new(2), Weekday::Mon);
monday - EXAMPLE_COUNTER
};
let fold_shift = || next_new_york_fold(today) - EXAMPLE_FOLD;
match (template, relative) {
("standalone-exact-time", "scheduling.yaml") => {
let counter = counter_shift();
let fold = fold_shift();
shift_dates(contents, |date| {
date + if date == EXAMPLE_FOLD { fold } else { counter }
})
}
("standalone-exact-time", "fixtures/counter-stations.yaml") => {
let shift = counter_shift();
shift_dates(contents, |date| date + shift)
}
("standalone-exact-time", "records.yaml" | "fixtures/fold-day-rebooking.yaml")
| ("resource-reservations", "records.yaml" | "fixtures/named-intervals.yaml") => {
let shift = fold_shift();
shift_dates(contents, |date| date + shift)
}
(
"standalone-arrival-window",
"scheduling.yaml"
| "records.yaml"
| "fixtures/household-morning.yaml"
| "fixtures/household-afternoon.yaml",
) => {
// Both named blocks need to be on the same Saturday, far enough
// ahead for their lead time and the example cancellation cutoff.
let saturday = on_or_after(today + Days::new(7), Weekday::Sat);
let shift = saturday - EXAMPLE_ARRIVAL;
shift_dates(contents, |date| date + shift)
}
("resource-reservations", "scheduling.yaml") => {
let year = next_new_york_fold(today).year();
// Cover the fixture's November fold and the live dates leading up
// to it, including when the fold will land in the next year.
shift_dates(contents, |date| {
let shifted = date.with_year(year).expect("valid opening date");
if date == example_date(1, 1) {
shifted.min(today)
} else {
shifted
}
})
}
_ => Cow::Borrowed(contents),
}
}

fn on_or_after(date: NaiveDate, weekday: Weekday) -> NaiveDate {
date + Days::new(u64::from(weekday.days_since(date.weekday())))
}

fn next_new_york_fold(today: NaiveDate) -> NaiveDate {
// America/New_York returns to standard time on the first Sunday in November.
let fold = |year| {
let november = NaiveDate::from_ymd_opt(year, 11, 1).expect("valid November date");
on_or_after(november, Weekday::Sun)
};
let this_year = fold(today.year());
if this_year > today {
this_year
} else {
fold(today.year() + 1)
}
}

/// Move ISO date prefixes in the built-in YAML, including the dates in UTC
/// timestamps. Keep the emitted file formatting and all clock times intact.
fn shift_dates(contents: &str, shift: impl Fn(NaiveDate) -> NaiveDate) -> Cow<'_, str> {
let date_char = |c: char| c.is_ascii_digit() || c == '-';
let mut output = String::with_capacity(contents.len());
for token in contents.split_inclusive(|c| !date_char(c)) {
let date = token.trim_end_matches(|c| !date_char(c));
if date.len() == 10 {
if let Ok(parsed) = NaiveDate::parse_from_str(date, "%Y-%m-%d") {
output.push_str(&shift(parsed).format("%Y-%m-%d").to_string());
output.push_str(&token[date.len()..]);
continue;
}
}
output.push_str(token);
}
Cow::Owned(output)
}

/// The example directory one template's files are read from.
macro_rules! example {
Expand Down
69 changes: 44 additions & 25 deletions docs/site/src/content/docs/configure/scheduling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,36 +36,50 @@ openings:
weekdays: [mon, tue, wed, thu, fri]
startTime: "09:00"
endTime: "12:30"
effectiveFrom: "2026-10-01"
effectiveUntil: "2026-12-31"
effectiveFrom: "<first-date>"
effectiveUntil: "<last-date>"
```

Times are wall-clock times at the location, read in the time zone its location record names, so
the counter opens at 09:00 Bangkok time on weekdays. The opening ends on `effectiveUntil`; from
2027 this offering publishes no starts until you extend that date and deploy the change.
Times are local to the time zone in the location record. The counter opens at 09:00 Bangkok time
on weekdays. Read `effectiveFrom` and `effectiveUntil`
in your file for the dates `init` generated when you created the project. Both dates are
inclusive. To publish starts after `effectiveUntil`, set a new approved range and deploy the
change. A single opening can span at most 3,650 days between its first and last dates.

{/* Evidence: crates/registry-schedulingctl/src/templates.rs, date_file();
crates/registry-scheduling-core/src/policy.rs, PatternSpanTooLarge. */}

## Close a public holiday

Every opening names a [holiday set](../../reference/glossary/#holiday-set), and a date in that set
closes the opening for the whole day. The starter's set closes nothing yet. Close Tuesday 13
October 2026:

```diff test-edit title="scheduling/scheduling.yaml"
office-holidays:
revision: 1
+ dates:
+ - "2026-10-13"
label: Public holidays observed by the registry offices.
```
closes the opening for the whole day. Use Python 3 to add the Tuesday after the counter fixture's
Monday `now` to `office-holidays.dates`. Add a booking case for 09:00 Bangkok time that day.
This keeps the holiday inside the fixture's booking horizon and leaves its Monday cases intact.

Prove it with a case at the end of the counter fixture. A booking at 09:00 that day must be
refused:

```yaml title="scheduling/fixtures/counter-stations.yaml" test-append
```sh
python3 - <<'PY'
from datetime import datetime, timedelta
from pathlib import Path

project = Path("scheduling")
fixture = project / "fixtures/counter-stations.yaml"
fixture_text = fixture.read_text(encoding="utf-8")
fixture_now = next(line.split(": ", 1)[1] for line in fixture_text.splitlines()
if line.startswith("now: "))
holiday = datetime.strptime(fixture_now, "%Y-%m-%dT%H:%M:%SZ").date() + timedelta(days=1)

policy = project / "scheduling.yaml"
policy_text = policy.read_text(encoding="utf-8")
holiday_set = " office-holidays:\n revision: 1\n"
before, after = policy_text.split(holiday_set, 1)
if after.startswith(" dates:") or "the-holiday-is-not-served" in fixture_text:
raise SystemExit("The starter already has holiday dates or has recorded the holiday case.")
policy.write_text(f'{before}{holiday_set} dates:\n - "{holiday}"\n{after}', encoding="utf-8")
fixture.write_text(fixture_text + f"""\
- name: the-holiday-is-not-served
request:
offering: registry-update-30
start: 2026-10-13T02:00:00Z
start: {holiday}T02:00:00Z
party:
recipients: 1
attendees: 1
Expand All @@ -74,6 +88,8 @@ refused:
expect:
type: refused
code: schedule.unpublished
""", encoding="utf-8")
PY
```

```sh
Expand All @@ -96,15 +112,16 @@ does not establish source reachability or deployment readiness.
`schedule.unpublished` is the answer for any start the policy does not publish, whether the day
is a holiday, a weekend, or outside the opening hours.

A closure that affects one location for part of a day is not policy. It is an exception record in
`records.yaml`, which the operator applies to a running deployment without a new package:
A closure that affects one location for part of a day is an exception record in `records.yaml`.
The operator applies it to a running deployment without a new package. Read the `hall-prep`
exception in your starter for the date of the New York clock change the fixture exercises.

```yaml title="scheduling/records.yaml" test-excerpt="scheduling/records.yaml"
exceptions:
- id: hall-prep
location: new-york-hall
kind: closure
date: "2026-11-01"
date: "<fold-date>"
startTime: "00:15"
endTime: "00:45"
```
Expand Down Expand Up @@ -256,8 +273,10 @@ schedulingctl explain ./arrival --format json
}
```

The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`. A
`subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A
The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`.
The starter dates both windows on the same upcoming Saturday. After those windows pass, publish
new dated records for future bookings.
A `subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A
subquota is a ceiling, not a reservation: the other channel may still use units the first leaves
free.
A channel the policy declares but gives no subquota draws from the window's total alone, and a request naming an undeclared channel is refused.
Expand Down
4 changes: 4 additions & 0 deletions products/platform/journeys/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@ Threshold outcomes are report-only in CI. The functional ratchet controls
journey acceptance, and comparison code errors fail the harness. Promote
uses its functional ratchet.

In `rstack-dev`, the run log and `cells.tsv` mark the hook step `unexercised`
when the journey has no hook delivery to check. The cell still runs its later
steps, including retention and cleanup.

## Running the static check

The check reads these files and a few source files. It starts no container and
Expand Down
Loading