From 64c34dadd05d249ef5643c41d782069458a9ae80 Mon Sep 17 00:00:00 2001 From: T-Crypt <132922589+T-Crypt@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:45:06 -0700 Subject: [PATCH] feat(schedule): book each card's hours: runs, priority changes and downtime berthd keeps a schedule per card, up to 14 days ahead, in schedule.json. A run booking is an engine's turn: its waiter goes first, runs at the booking's priority, wins a tie against an unbooked holder, and keeps the card against everything but a hold until the booking ends. A priority booking moves an engine to another class for set hours. Downtime takes no new work and drains holders at the start; holds and trainings stay. Hours nobody booked run by priority, then arrival, as before. berth schedule shows what holds each card, the queue and the bookings, and books, moves and cancels them. The gateway's /v1/berth/schedule lets agents read the scheduler and book their own runs. The harbor gains a SCHEDULE tab with a 7-day board of 24-hour tracks, and a paired device books from it through berthd's socket. --- CHANGELOG.md | 13 + docs/gateway.md | 28 ++ docs/leasing.md | 45 ++++ internal/broker/booking.go | 135 ++++++++++ internal/broker/booking_test.go | 185 +++++++++++++ internal/broker/broker.go | 31 ++- internal/broker/override.go | 2 +- internal/broker/status.go | 1 + internal/cli/commands.go | 38 +++ internal/cli/daemon.go | 10 + internal/cli/schedule.go | 188 ++++++++++++++ internal/cli/schedule_test.go | 79 ++++++ internal/cli/unpark.go | 4 +- internal/gateway/gateway.go | 4 + internal/gateway/gateway_test.go | 8 +- internal/gateway/schedule.go | 171 ++++++++++++ internal/gateway/schedule_test.go | 112 ++++++++ internal/harbor/harbor.go | 3 +- internal/harbor/schedule_test.go | 60 +++++ internal/harbor/switchboard.go | 33 +++ internal/harbor/switchboard_test.go | 7 +- internal/harbor/web/harbor.css | 76 ++++++ internal/harbor/web/harbor.js | 13 +- internal/harbor/web/index.html | 74 +++++- internal/harbor/web/schedule.js | 388 ++++++++++++++++++++++++++++ internal/node/node.go | 8 + internal/proto/booking.go | 137 ++++++++++ internal/proto/proto.go | 38 ++- internal/schedule/schedule.go | 184 +++++++++++++ internal/schedule/schedule_test.go | 179 +++++++++++++ internal/schedule/when.go | 63 +++++ internal/server/bookings.go | 71 +++++ internal/server/server.go | 9 + internal/skill/SKILL.md | 2 + 34 files changed, 2374 insertions(+), 25 deletions(-) create mode 100644 internal/broker/booking.go create mode 100644 internal/broker/booking_test.go create mode 100644 internal/cli/schedule.go create mode 100644 internal/cli/schedule_test.go create mode 100644 internal/gateway/schedule.go create mode 100644 internal/gateway/schedule_test.go create mode 100644 internal/harbor/schedule_test.go create mode 100644 internal/harbor/web/schedule.js create mode 100644 internal/proto/booking.go create mode 100644 internal/schedule/schedule.go create mode 100644 internal/schedule/schedule_test.go create mode 100644 internal/schedule/when.go create mode 100644 internal/server/bookings.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ac6b26..7ada899 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ has a matching GitHub release whose body comes from its section below. ### Added +- A schedule for each card, up to 14 days ahead. `berth schedule` shows what holds each card, the waiters in grant + order and every booking. `berth schedule book` books an engine's run (it goes first, runs at the booking's + priority, and keeps the card against everything but a hold), a priority change for set hours, or downtime (no + new work, holders drain at the start). `move` and `cancel` change a booking, and `--days` and `--earliest` + repeat one or find free hours. Hours nobody booked run by priority, then arrival, as before. berthd keeps the + bookings in `schedule.json`. +- The gateway's `GET`, `POST`, `PATCH` and `DELETE /v1/berth/schedule` let agents and devices read the scheduler + and book, move or cancel their own runs. Downtime and priority changes stay the operator's. +- The harbor's SCHEDULE tab: what runs and waits now, a 7-day board of 24-hour tracks with every booking to the + minute, each engine's window and the live holder, and a list of bookings. A paired device books by clicking an + empty hour and moves or cancels a booking by clicking it. Each booking form says what the booking will do before + you save it. + - `berth train --as NAME [--gpu CARDS] -- CMD` runs a training or fine-tune that nothing automated can interrupt. It takes the whole of each card it names, waits for them with no deadline, and keeps them until the command exits. While it holds a card or waits for it, berthd refuses every other request on that card at once: gateway diff --git a/docs/gateway.md b/docs/gateway.md index 05a6d27..6651c1e 100644 --- a/docs/gateway.md +++ b/docs/gateway.md @@ -309,6 +309,34 @@ on the node (`card`, such as `gpu1`), its base URL on this gateway (`base`, `/ca `berth cordon` closed it, and the holders on that card alone. Each engine names the cards its entry runs on (`cards`), so a board for several cards can put each engine under its card. +## Book the card from an agent + +An agent, a timer or another device books its own run on the card's schedule (read +[Book the card](leasing.md#book-the-card)) with the node's key: + +```sh +K="Authorization: Bearer $(berth key)" +curl -s http://127.0.0.1:9799/v1/berth/schedule -H "$K" +curl -s http://127.0.0.1:9799/v1/berth/schedule -H "$K" \ + -d '{"who":"pi-pocket","engine":"pocket-train","start":"23:00","for":"5h","priority":"batch","days":7}' +curl -s -X PATCH http://127.0.0.1:9799/v1/berth/schedule/b4 -H "$K" -d '{"start":"01:00"}' +curl -s -X DELETE http://127.0.0.1:9799/v1/berth/schedule/b4 -H "$K" +``` + +- `GET` is the scheduler in one read: `now`, `running` (the leases that hold a card), `queued` (the waiters in + grant order) and `bookings` (every booking that has not ended, by start). A lease that a booking governs names it + in `booking`. +- `POST` books a run and answers `201` with `bookings`, the bookings it made. `start` takes what + `berth schedule --at` takes, and `for` is a length such as `5h` or `90m`. `days`, `earliest`, `card`, `priority` + and `note` are optional. A clash or an invalid booking is a `409` with the reason, such as + `run Sat 23:30-Sun 00:30 clashes with b1 (run for pi-pocket, Sat 23:00-Sun 04:00)`. +- `PATCH /v1/berth/schedule/ID` moves a run. It takes `start`, `for`, `priority` and `note`, keeps the rest and + keeps the ID. `DELETE` cancels a run. Both answer `200` with the booking. + +The gateway books, moves and cancels runs only. A priority change or downtime acts on everyone else's work, so it +is the operator's: `berth schedule`, or a paired device in the harbor. `PATCH` or `DELETE` on one is a `403`. Any +holder of the key can change any run; per-device ownership comes with device keys. + ## One URL per card On a node with several cards, each card has its own base URL on the gateway: `/cards/CARD/v1`, where `CARD` is diff --git a/docs/leasing.md b/docs/leasing.md index 21db6e0..79134b2 100644 --- a/docs/leasing.md +++ b/docs/leasing.md @@ -179,6 +179,51 @@ A bump puts the waiter ahead of everyone else in its priority class. To go ahead priority with `prio`. Holds and trainings cannot be changed here: a hold is a pin, not a place in the queue, and a training's place is fixed by the card's lock. Each change is a `lease.queue_override` event in `berth events`. +## Book the card + +The queue decides who goes next. A booking decides whose hours they are, up to 14 days ahead. A booking has one of +three kinds: + +- `run` is an engine's turn. While it lasts, the engine's waiter goes first in line and runs at the booking's + priority (foreground when the booking names none). It wins a tie against a holder that has no booking. Once it + holds the card, nothing but a hold drains it until the booking ends. A minimum turn (`min_turn`) still protects + the holder it takes over from. +- `priority` moves an engine to another class for set hours, such as llama-swap at batch while a training runs. It + claims no time on the card, so it may overlap a run. +- `down` is downtime. No new work starts, and holders drain at their usual boundary when it begins. A hold and a + training stay. + +An hour nobody booked runs by priority, then arrival. A booked engine that does not ask for the card leaves it to +everyone else, so a booking never keeps the card idle. + +```sh +berth schedule # what holds each card, the waiters in grant order, every booking +berth schedule book --who pi-pocket --engine pocket-train --at 23:00 --for 5h --days 7 --priority batch +berth schedule book --who training --engine sft --at "sun 18:00" --for 3h +berth schedule book --who operator --kind priority --engine llama-swap --priority batch --at "sun 18:00" --for 3h +berth schedule book --who operator --kind down --at "tue 04:00" --for 1h --note "driver update" +berth schedule move b4 --at 01:00 # new hours, same ID; --for, --priority and --note change those +berth schedule cancel b4 +``` + +`--at` takes `now`, `22:00` (the next time the clock reads it), `tue 22:00`, `2026-11-14 22:00` or RFC 3339, on the +node's clock. `--days 7` books the same hours on 7 days in a row, all of them or none. `--earliest` moves the +booking to the first free hours at or after `--at`. `--engine` takes an engine or a group, such as `llama-swap` +for every model it serves. + +Two runs or downtimes on one card may not overlap, and neither may two priority changes for the same engine. A +clash is refused with the booking it hits. A class set with `berth queue prio` wins over a booking, and a booking +never moves a hold or a training. + +berthd keeps the bookings in `schedule.json` in its state directory (`berth daemon --schedule`). Each change is a +`schedule.booked` event, and each class a booking moves, or moves back at its end, is a `lease.booking_priority` +event. A lease that a booking governs shows the booking's ID in `berth status --format json` (`booking`). + +The harbor's SCHEDULE tab shows the same scheduler. NOW lists what holds each card, the waiters and the booking in +force. 7 DAYS draws one 24-hour track per day with every booking to the minute, each engine's window and the live +holder. A paired device books by clicking an empty hour, and moves or cancels a booking by clicking it. Agents +book over the gateway: read [Book the card from an agent](gateway.md#book-the-card-from-an-agent). + ## Cordon a card On a node with several cards, `berth cordon gpu1` stops new grants on that card while the others keep serving, for diff --git a/internal/broker/booking.go b/internal/broker/booking.go new file mode 100644 index 0000000..e3d3640 --- /dev/null +++ b/internal/broker/booking.go @@ -0,0 +1,135 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package broker + +// The card's schedule. berthd's booking file says who has the card when, +// and the broker reads it on every tick. A run booking is an engine's turn: +// its waiter goes first, it runs at the booking's priority, and while it +// holds the card nothing but a hold drains it. A priority booking moves an +// engine to another class for its hours. Downtime takes no new work and +// drains its holders at the start. An hour nobody booked runs as it always +// did, by priority then arrival, so an unused booking leaves the card idle +// for nobody. + +import ( + "fmt" + "slices" + "time" + + "github.com/T-Crypt/berth/internal/proto" +) + +// SetBookings replaces the card's schedule with bs, and schedules the queue +// under it at once. +func (b *Broker) SetBookings(bs []proto.Booking) { + b.mu.Lock() + defer b.mu.Unlock() + b.bookings = slices.Clone(bs) + now := b.now() + b.closeForDowntime(now) + b.schedule(now) +} + +// booked is the booking that sets l's priority at now: a run, then a +// priority change, for its engine or its group. A hold, a training and a +// class the operator set by hand are not moved. +func (b *Broker) booked(l *lease, now time.Time) (proto.Booking, bool) { + if l.basePrio == Hold || l.training || l.operatorPrio { + return proto.Booking{}, false + } + for _, k := range []proto.BookingKind{proto.BookRun, proto.BookPriority} { + for _, name := range []string{l.engine, l.group} { + if name == "" { + continue + } + if x, ok := proto.BookingAt(b.bookings, k, name, now); ok { + return x, true + } + } + } + return proto.Booking{}, false +} + +// inRun is whether a run booking holds for l at now. +func (b *Broker) inRun(l *lease, now time.Time) bool { + x, ok := b.booked(l, now) + return ok && x.Kind == proto.BookRun +} + +// bookedPrio is the class a booking gives: its own, and foreground for a +// run that names none. +func bookedPrio(x proto.Booking) Priority { + if x.Priority == "" { + return Foreground + } + p, err := ParsePriority(x.Priority) + if err != nil { + return Foreground + } + return p +} + +// applyBookings sets every lease's class from the schedule at now: the +// booking's while one holds, its own when none does. Each move is an event. +// Called with b.mu held. +func (b *Broker) applyBookings(now time.Time) { + moved := false + for _, l := range slices.Concat(b.queue, mapValues(b.leases)) { + p, id := l.basePrio, "" + if x, ok := b.booked(l, now); ok { + p, id = bookedPrio(x), x.ID + } + if p == l.prio && id == l.booking { + continue + } + detail := fmt.Sprintf("priority %s -> %s: booking %s", l.prio, p, id) + if id == "" { + detail = fmt.Sprintf("priority %s -> %s: booking %s ended", l.prio, p, l.booking) + } + l.prio, l.booking, moved = p, id, true + b.emit(proto.Event{Kind: proto.EvBookingPrio, Lease: l.id, Engine: l.engine, Detail: detail}) + b.log.Info("booking priority", "lease", l.id, "engine", l.engine, "change", detail) + } + if moved { + b.sortQueue() + } +} + +// closeForDowntime drains the active holders, and evicts the parked ones, +// when downtime holds at now. A hold and a training keep the card. A lease +// already on its way out is not asked twice. Called with b.mu held. +func (b *Broker) closeForDowntime(now time.Time) { + d, ok := proto.BookingAt(b.bookings, proto.BookDown, "", now) + if !ok { + return + } + for _, l := range b.leases { + if l.prio == Hold || l.training { + continue + } + switch l.state { + case active: + b.drain(l, downWhy(d)) + case parked: + b.evict(l, downWhy(d)) + } + } +} + +// downWhy is what a waiter and a drained holder read during downtime. +func downWhy(d proto.Booking) string { + why := fmt.Sprintf("the card is down until %s (booking %s by %s", d.End.Format("Mon 15:04"), d.ID, d.Who) + if d.Note != "" { + why += ": " + d.Note + } + return why + ")" +} + +func mapValues[K comparable, V any](m map[K]V) []V { + out := make([]V, 0, len(m)) + for _, v := range m { + out = append(out, v) + } + return out +} diff --git a/internal/broker/booking_test.go b/internal/broker/booking_test.go new file mode 100644 index 0000000..edb6a89 --- /dev/null +++ b/internal/broker/booking_test.go @@ -0,0 +1,185 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package broker + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/T-Crypt/berth/internal/procs" + "github.com/T-Crypt/berth/internal/proto" +) + +// book is a booking on b's card from turnBase+from for length. +func book(_ *Broker, id string, k proto.BookingKind, engine, prio string, from, length time.Duration) proto.Booking { + return proto.Booking{ID: id, Card: "gpu0", Kind: k, Who: "test", Engine: engine, Priority: prio, + Start: turnBase.Add(from), End: turnBase.Add(from + length)} +} + +func leaseRow(t *testing.T, b *Broker, engine string) proto.Lease { + t.Helper() + st := b.Status() + for _, l := range append(st.Leases, st.Waiting...) { + if l.Engine == engine { + return l + } + } + t.Fatalf("no lease for %s in %+v", engine, st) + return proto.Lease{} +} + +// A run booking is the engine's turn: its batch waiter runs at foreground, +// so an interactive holder drains for it, and status names the booking. +func TestRunBookingLiftsItsWaiterAndDrainsALowerHolder(t *testing.T) { + b, _ := startTurnBroker(t, procs.Map{}) + b.SetBookings([]proto.Booking{book(b, "b1", proto.BookRun, "pi-pocket", "", -time.Minute, 5*time.Hour)}) + holder := must(t, acquire(b, Request{Engine: "comfyui", Priority: Interactive, Needs: 20 * GiB})) + + w := acquireW(b, Request{Engine: "pi-pocket", Priority: Batch, Needs: 20 * GiB}) + pending(t, w.ch) + if got, want := drained(t, holder), "pi-pocket (foreground) needs the card"; got != want { + t.Errorf("drain = %q, want %q", got, want) + } + if row := leaseRow(t, b, "pi-pocket"); row.Priority != "foreground" || row.Booking != "b1" { + t.Errorf("waiter = %s booking %q, want foreground booking b1", row.Priority, row.Booking) + } + holder.Release() + b.Tick(context.Background()) + granted(t, b, "pi-pocket", w.ch) +} + +// A tie is the holder's, except against the waiter's booked turn: a +// foreground holder with no booking drains for a run lifted to foreground. +func TestRunBookingWinsATie(t *testing.T) { + b, _ := startTurnBroker(t, procs.Map{}) + b.cfg.JuggleWindow = time.Hour + b.SetBookings([]proto.Booking{book(b, "b1", proto.BookRun, "sft", "", 0, time.Hour)}) + holder := must(t, acquire(b, Request{Engine: "chat", Priority: Foreground, Needs: 20 * GiB})) + w := acquireW(b, Request{Engine: "sft", Priority: Batch, Needs: 20 * GiB}) + pending(t, w.ch) + if got, want := drained(t, holder), "sft (foreground) needs the card"; got != want { + t.Errorf("drain = %q, want %q", got, want) + } +} + +// Inside its run booking a holder keeps the card against a foreground +// waiter; once the booking ends it is back to its own class and drains. +func TestRunBookingKeepsItsHolderUntilItEnds(t *testing.T) { + b, clk := startTurnBroker(t, procs.Map{}) + b.SetBookings([]proto.Booking{book(b, "b1", proto.BookRun, "train", "", 0, 3*time.Hour)}) + holder := must(t, acquire(b, Request{Engine: "train", Priority: Batch, Needs: 20 * GiB})) + + w := acquireW(b, Request{Engine: "game", Priority: Foreground, Needs: 20 * GiB}) + pending(t, w.ch) + select { + case why := <-holder.Drains(): + t.Fatalf("a booked holder was drained inside its booking: %s", why) + default: + } + if got, want := firstReason(t, w), "held by train [foreground, active]"; !strings.HasSuffix(got, want) { + t.Errorf("reason = %q, want it to end %q", got, want) + } + + clk.set(turnBase.Add(3 * time.Hour)) + b.Tick(context.Background()) + if got, want := drained(t, holder), "game (foreground) needs the card"; got != want { + t.Errorf("drain = %q, want %q", got, want) + } + if row := leaseRow(t, b, "train"); row.Priority != "batch" || row.Booking != "" { + t.Errorf("holder after the booking = %s booking %q, want batch and none", row.Priority, row.Booking) + } +} + +// A run booking puts its waiter ahead of an earlier foreground one. +func TestRunBookingGoesFirstInLine(t *testing.T) { + b, _ := startTurnBroker(t, procs.Map{}) + b.SetBookings([]proto.Booking{book(b, "b1", proto.BookRun, "pi-pocket", "batch", 0, time.Hour)}) + holder := must(t, acquire(b, Request{Engine: "hold", Priority: Hold, Needs: 20 * GiB})) + early := acquireW(b, Request{Engine: "chat", Priority: Foreground, Needs: 20 * GiB}) + pending(t, early.ch) + booked := acquireW(b, Request{Engine: "pi-pocket", Priority: Batch, Needs: 20 * GiB}) + pending(t, booked.ch) + if st := b.Status(); len(st.Waiting) != 2 || st.Waiting[0].Engine != "pi-pocket" { + t.Fatalf("queue = %+v, want pi-pocket first", st.Waiting) + } + holder.Release() + b.Tick(context.Background()) + granted(t, b, "pi-pocket", booked.ch) +} + +// A priority booking moves an engine's class for its hours and back after, +// with an event each way; the operator's own berth queue prio wins over it. +func TestPriorityBookingMovesTheClassAndBack(t *testing.T) { + b, clk := startTurnBroker(t, procs.Map{}) + b.SetBookings([]proto.Booking{book(b, "b2", proto.BookPriority, "dirk", "batch", time.Hour, time.Hour)}) + must(t, acquire(b, Request{Engine: "hold", Priority: Hold, Needs: 20 * GiB})) + w := acquireW(b, Request{Engine: "dirk", Priority: Foreground, Needs: 20 * GiB}) + pending(t, w.ch) + if row := leaseRow(t, b, "dirk"); row.Priority != "foreground" { + t.Fatalf("before the booking = %s, want foreground", row.Priority) + } + clk.set(turnBase.Add(90 * time.Minute)) + b.Tick(context.Background()) + if row := leaseRow(t, b, "dirk"); row.Priority != "batch" || row.Booking != "b2" { + t.Errorf("inside the booking = %s booking %q, want batch b2", row.Priority, row.Booking) + } + clk.set(turnBase.Add(2 * time.Hour)) + b.Tick(context.Background()) + if row := leaseRow(t, b, "dirk"); row.Priority != "foreground" || row.Booking != "" { + t.Errorf("after the booking = %s booking %q, want foreground and none", row.Priority, row.Booking) + } + evs, _, _ := b.Events(0, false) + var moves []string + for _, e := range evs { + if e.Kind == proto.EvBookingPrio { + moves = append(moves, e.Detail) + } + } + want := []string{"priority foreground -> batch: booking b2", "priority batch -> foreground: booking b2 ended"} + if len(moves) != 2 || moves[0] != want[0] || moves[1] != want[1] { + t.Errorf("events = %q, want %q", moves, want) + } + + clk.set(turnBase.Add(90 * time.Minute)) + id := leaseRow(t, b, "dirk").ID + if _, err := b.Queue(id, QueuePrio, "interactive"); err != nil { + t.Fatal(err) + } + b.Tick(context.Background()) + if row := leaseRow(t, b, "dirk"); row.Priority != "interactive" { + t.Errorf("after berth queue prio inside the booking = %s, want interactive", row.Priority) + } +} + +// Downtime drains its holder at the start, refuses new work with the +// booking's reason, and still lets a hold in. +func TestDowntimeDrainsAndTakesNoNewWork(t *testing.T) { + b, clk := startTurnBroker(t, procs.Map{}) + d := book(b, "b3", proto.BookDown, "", "", time.Hour, 30*time.Minute) + d.Who, d.Note = "operator", "driver update" + b.SetBookings([]proto.Booking{d}) + holder := must(t, acquire(b, Request{Engine: "chat", Priority: Interactive, Needs: 8 * GiB})) + + clk.set(turnBase.Add(time.Hour)) + b.Tick(context.Background()) + want := "the card is down until " + d.End.Format("Mon 15:04") + " (booking b3 by operator: driver update)" + if got := drained(t, holder); got != want { + t.Errorf("drain = %q, want %q", got, want) + } + holder.Release() + b.Tick(context.Background()) + + w := acquireW(b, Request{Engine: "chat", Priority: Foreground, Needs: 8 * GiB}) + pending(t, w.ch) + if got := firstReason(t, w); got != "next in line: "+want { + t.Errorf("waiter reason = %q, want %q", got, want) + } + must(t, acquire(b, Request{Engine: "game", Priority: Hold, Needs: 8 * GiB})) + + clk.set(turnBase.Add(90 * time.Minute)) + b.Tick(context.Background()) + granted(t, b, "chat", w.ch) +} diff --git a/internal/broker/broker.go b/internal/broker/broker.go index 64fbafb..b35af23 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -291,10 +291,17 @@ type lease struct { parkTTL time.Duration // 0 = the node's window proto.Window // zero = no window prio Priority - needs uint64 - state state - pid int - pidStart uint64 + // basePrio is the class the lease asked for, or the operator set; prio + // differs from it while a booking holds (booking.go). + basePrio Priority + // booking is the ID of the booking that sets prio now, "" when none. + booking string + // operatorPrio: berth queue prio set the class, and no booking moves it. + operatorPrio bool + needs uint64 + state state + pid int + pidStart uint64 // goneTicks counts the consecutive ticks that saw the attached pid // gone (no process with its start time); the reaper needs two, so a // pid lookup hiccup on one tick cannot free a live lease. @@ -431,6 +438,7 @@ func newLease(id string, r Request, now time.Time) *lease { engine: r.Engine, group: r.Group, prio: r.Priority, + basePrio: r.Priority, needs: r.Needs, pinned: r.Pinned, training: r.Training, @@ -514,6 +522,7 @@ type Broker struct { verdicts map[string]verdict // loser engine key -> the juggle it lost batches map[string]*batch // berth batch: engine or group -> its batch cordoned bool // berth cordon: grant only holds + bookings []proto.Booking // this card's schedule (SetBookings) parkOff bool // berth park off: drains stop their engine, nothing parks // tracked is the claim watcher's last scan: a process (and every child) // a track claim names. Its card memory is the claim's, never a stowaway. @@ -970,6 +979,7 @@ func (b *Broker) Tick(ctx context.Context) { } b.claimed = claimed b.closeWindows(now) + b.closeForDowntime(now) b.evictParked(now) b.schedule(now) } @@ -1125,6 +1135,7 @@ func (b *Broker) allowed(name string) bool { // holders to drain for the first waiter that does not fit. Nobody behind a // blocked waiter jumps it, so a big request is not starved by small ones. func (b *Broker) schedule(now time.Time) { + b.applyBookings(now) if b.cardState != "" { // The card does not serve the node, so nothing new is granted, and // every waiter reads the same reason. The VFIO hold itself keeps @@ -1258,7 +1269,11 @@ func (b *Broker) grant(w *lease, now time.Time) { // latest bump (berth queue bump), then by arrival on the node. b.mu must be // held. func (b *Broker) sortQueue() { + now := b.now() sort.SliceStable(b.queue, func(i, j int) bool { + if ri, rj := b.inRun(b.queue[i], now), b.inRun(b.queue[j], now); ri != rj { + return ri + } if b.queue[i].prio != b.queue[j].prio { return b.queue[i].prio > b.queue[j].prio } @@ -1465,6 +1480,9 @@ func (b *Broker) evaluate(w *lease, now time.Time) (bool, string, []*lease) { if b.cordoned && w.prio != Hold { return false, "the card is cordoned; berth uncordon lets new work in", nil } + if d, ok := proto.BookingAt(b.bookings, proto.BookDown, "", now); ok && w.prio != Hold && !w.training { + return false, downWhy(d), nil + } if !w.window.Contains(now) { // Its own hours decide this waiter alone: no holder is a victim, // because nothing it drains would put it inside its window. @@ -1533,7 +1551,7 @@ func (b *Broker) evaluate(w *lease, now time.Time) (bool, string, []*lease) { // for it to become parked (or fall back to a drain); evicting // it mid-park would throw the park away. pending = append(pending, h) - case h.pinned || h.prio > w.prio: + case h.pinned || h.prio > w.prio, w.prio != Hold && b.inRun(h, now) && !b.inRun(w, now): blockers = append(blockers, h) case w.prio != Hold && h.inTurn(now): // A minimum turn: the holder keeps the card until its turn @@ -1548,7 +1566,8 @@ func (b *Broker) evaluate(w *lease, now time.Time) (bool, string, []*lease) { keptWhy = batchWhy(k, bt) continue case h.prio == w.prio: - if keep, why := b.keeps(h, w, now); keep { + // A tie is the holder's, unless it is the waiter's booked turn. + if keep, why := b.keeps(h, w, now); keep && (!b.inRun(w, now) || b.inRun(h, now)) { kept, keptWhy = append(kept, h), why continue } diff --git a/internal/broker/override.go b/internal/broker/override.go index 4788dc8..b6fcac9 100644 --- a/internal/broker/override.go +++ b/internal/broker/override.go @@ -60,7 +60,7 @@ func (b *Broker) Queue(id string, action QueueAction, prio string) (string, erro return "", fmt.Errorf("priority %q: use batch, interactive or foreground", prio) } detail = fmt.Sprintf("priority %s -> %s by the operator", w.prio, p) - w.prio = p + w.prio, w.basePrio, w.operatorPrio, w.booking = p, p, true, "" b.sortQueue() case QueueDrop: select { diff --git a/internal/broker/status.go b/internal/broker/status.go index 9a4e485..a5acc92 100644 --- a/internal/broker/status.go +++ b/internal/broker/status.go @@ -87,6 +87,7 @@ func (b *Broker) Status() proto.Status { GTTUsed: l.gttUsed(), GTTContested: l.contestedGTT, Contested: l.contested, Age: now.Sub(since).Seconds(), Pinned: l.pinned, Window: l.window.String(), + Booking: l.booking, Training: l.training, } if l.state == parked { diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 25badbd..ea4243b 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -416,6 +416,44 @@ lease.queue_override event (berth events).`, Formats: []Format{FormatHuman, FormatJSON, FormatYAML}, Run: runQueue, }, + { + Name: "schedule", + Summary: "the card's scheduler: what runs, what waits, what is booked; book, move or cancel", + Args: "[book --who W --at T --for D [--engine E] [--kind run|priority|down] [--priority P] [--days N] [--earliest] [--note N] | move ID [--at T] [--for D] | cancel ID] [--socket P] [--format F]", + Help: `Without arguments, show the scheduler: the leases that hold a card, the +waiters in the order berthd grants them, and every booking that has not +ended. The harbor draws the same bookings on its 7-day board. + +A booking gives a card's hours to someone: + + run the engine's turn. Its waiter goes first, it runs at the + booking's priority (foreground when none is given), and while + it holds the card nothing but a hold drains it. + priority the engine runs at another class for these hours, like batch + during a training. It claims no time on the card. + down downtime. No new work starts and holders drain at the start; a + hold and a training stay. + +An hour nobody booked runs as always, by priority then arrival, and a booked +engine that does not show up leaves the card to everyone else. Two runs or +downtimes on one card may not overlap. --earliest moves a booking to the +first free hours at or after --at, and --days books the same hours on +consecutive days. --engine also takes a group, like llama-swap. A class set +with berth queue prio wins over a booking. + + berth schedule book --who pi-pocket --engine pi-train --at 23:00 --for 5h --days 7 --priority batch + berth schedule book --who operator --kind down --at "sun 04:00" --for 1h --note "driver update" + berth schedule book --who operator --kind priority --engine llama-swap --priority batch --at 13:00 --for 3h + berth schedule move b4 --at 01:00 + berth schedule cancel b4 + +Times are the node's clock. Agents use the same scheduler over the gateway: +GET, POST and DELETE /v1/berth/schedule (docs/gateway.md). Each change is a +schedule.booked event and each class a booking moves is a +lease.booking_priority event (berth events).`, + Formats: []Format{FormatHuman, FormatJSON, FormatYAML}, + Run: runSchedule, + }, { Name: "reclaim", Summary: "what a stuck lease left on the card; --yes stops it", diff --git a/internal/cli/daemon.go b/internal/cli/daemon.go index 131f8d9..32a7b84 100644 --- a/internal/cli/daemon.go +++ b/internal/cli/daemon.go @@ -29,6 +29,7 @@ import ( "github.com/T-Crypt/berth/internal/procs" "github.com/T-Crypt/berth/internal/proto" "github.com/T-Crypt/berth/internal/runs" + "github.com/T-Crypt/berth/internal/schedule" "github.com/T-Crypt/berth/internal/server" "github.com/T-Crypt/berth/internal/suite" ) @@ -50,6 +51,7 @@ func runDaemon(c *Context) int { cfgPath := fs.String("config", config.DefaultPath(), "berth.toml: engines to read, /metrics listener ($BERTH_CONFIG); missing = none") countersFile := fs.String("counters", defaultStateFile("counters.json"), "keeps the collisions board across restarts; \"\" = start at zero every time") devicesFile := fs.String("devices", defaultStateFile("harbor-devices.json"), "devices paired to act from the harbor (berth pair); \"\" = pairing off") + scheduleFile := fs.String("schedule", defaultStateFile("schedule.json"), "the cards' bookings (berth schedule): runs, priority changes, downtime; \"\" = no schedule") usageFile := fs.String("usage", defaultStateFile("usage.json"), "card-hours per engine, the default juggle ranking; \"\" = memory only") footprintFile := fs.String("footprint", defaultStateFile("footprint.json"), "VRAM measured per engine across restarts, the estimate behind EST. VRAM; \"\" = memory only") if code, done := c.Parse(fs); done { @@ -287,6 +289,14 @@ func runDaemon(c *Context) int { if *devicesFile != "" { x.Pair = &pair.Store{Path: *devicesFile} } + if *scheduleFile != "" { + s, err := schedule.Open(*scheduleFile) + if err != nil { + return c.fail(Systemf("schedule: %v", err).WithHint("fix or move %s; berthd keeps the cards' bookings there", *scheduleFile)) + } + x.Schedule = s + n.SetBookings(s.List(time.Now())) + } if err := server.Serve(ctx, ln, n, x, log); err != nil { return c.fail(Systemf("serve: %v", err)) } diff --git a/internal/cli/schedule.go b/internal/cli/schedule.go new file mode 100644 index 0000000..e063e26 --- /dev/null +++ b/internal/cli/schedule.go @@ -0,0 +1,188 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package cli + +import ( + "fmt" + "slices" + "text/tabwriter" + "time" + + "github.com/T-Crypt/berth/internal/proto" + "github.com/T-Crypt/berth/internal/schedule" + "github.com/T-Crypt/berth/internal/server" +) + +type scheduleView struct { + b proto.ScheduleBoard + cards int +} + +func (v scheduleView) Data() any { return v.b } + +func (v scheduleView) Human(c *Context, ok bool) error { + tw := tabwriter.NewWriter(c.Out, 0, 4, 2, ' ', 0) + card := func(s string) string { return claimCardCol(v.cards, s) } + fmt.Fprint(tw, "RUNNING\t"+card("CARD")+"ENGINE\tPRIORITY\tSTATE\tFOR\tBOOKING\n") + if len(v.b.Running) == 0 { + fmt.Fprint(tw, "-\t"+card("")+"nothing holds a card\t\t\t\t\n") + } + for _, l := range v.b.Running { + fmt.Fprintf(tw, "%s\t%s%s\t%s\t%s\t%s\t%s\n", l.ID, card(l.Card), l.Holder(), l.Priority, l.State, age(l.Age), dash(l.Booking)) + } + fmt.Fprint(tw, "\nQUEUED\t"+card("CARD")+"ENGINE\tPRIORITY\tWAITING\tBOOKING\t\n") + if len(v.b.Queued) == 0 { + fmt.Fprint(tw, "-\t"+card("")+"nobody is waiting\t\t\t\t\n") + } + for i, l := range v.b.Queued { + fmt.Fprintf(tw, "%d. %s\t%s%s\t%s\t%s\t%s\t\n", i+1, l.ID, card(l.Card), l.Holder(), l.Priority, age(l.Age), dash(l.Booking)) + } + fmt.Fprint(tw, "\nBOOKED\t"+card("CARD")+"KIND\tWHO\tENGINE\tPRIORITY\tWHEN\tNOTE\n") + if len(v.b.Bookings) == 0 { + fmt.Fprint(tw, "-\t"+card("")+"nothing booked; berth schedule book --help\t\t\t\t\t\n") + } + for _, x := range v.b.Bookings { + when := x.Start.Format("Mon Jan 2 15:04") + "-" + x.End.Format("15:04") + if x.End.YearDay() != x.Start.YearDay() { + when = x.Start.Format("Mon Jan 2 15:04") + "-" + x.End.Format("Mon 15:04") + } + if x.Holds(v.b.Now) { + when += " (now)" + } + fmt.Fprintf(tw, "%s\t%s%s\t%s\t%s\t%s\t%s\t%s\n", x.ID, card(x.Card), x.Kind, x.Who, dash(x.Engine), dash(x.Priority), when, x.Note) + } + return tw.Flush() +} + +type bookingsView struct { + op string + bs []proto.Booking +} + +func (v bookingsView) Data() any { return v.bs } + +func (v bookingsView) Human(c *Context, ok bool) error { + verb := map[string]string{proto.OpBook: "booked", proto.OpUnbook: "cancelled", proto.OpRebook: "moved"}[v.op] + for _, x := range v.bs { + c.Printf("%s %s %s: %s for %s, %s-%s\n", c.Style.OK(markOK), verb, x.ID, x.Kind, x.Who, + x.Start.Format("Mon Jan 2 15:04"), x.End.Format("Mon 15:04")) + } + return nil +} + +func runSchedule(c *Context) int { + fs := c.FlagSet() + sock := fs.String("socket", defaultSocket(), "berthd socket ($BERTH_SOCKET)") + kind := fs.String("kind", "run", "book: run (the engine's turn), priority (change its class) or down (downtime)") + who := fs.String("who", "", "book: who the booking is for: a device, an agent, a person") + engine := fs.String("engine", "", "book: the engine or group the booking is for (not for down)") + prio := fs.String("priority", "", "book: batch, interactive or foreground (run default foreground; priority needs one)") + atFlag := fs.String("at", "", "book, move: the start: now, 22:00, tue 22:00, 2026-11-14 22:00") + forFlag := fs.Duration("for", 0, "book, move: how long, like 5h or 90m") + days := fs.Int("days", 1, "book: the same hours on this many days in a row") + earliest := fs.Bool("earliest", false, "book: take the first free hours at or after --at") + card := fs.String("card", "", "book: the card (default the first)") + note := fs.String("note", "", "book, move: a note the board shows") + if code, done := c.ParseInterspersed(fs); done { + return code + } + usage := "usage: berth schedule | berth schedule book --who W --at T --for D [--engine E] [--kind run|priority|down] | berth schedule move ID --at T [--for D] | berth schedule cancel ID" + now := time.Now() + var msg proto.Msg + switch args := c.Args; { + case len(args) == 0: + msg = proto.Msg{Op: proto.OpStatus} + case len(args) == 1 && args[0] == "book": + start, err := schedule.ParseAt(*atFlag, now) + if err != nil || *forFlag <= 0 { + return c.fail(Failf("berth schedule book needs --at and --for").WithHint("%s", usage)) + } + b := proto.Booking{Card: *card, Kind: proto.BookingKind(*kind), Who: *who, Engine: *engine, Priority: *prio, + Start: start, End: start.Add(*forFlag), Note: *note} + if err := b.Check(now); err != nil { + return c.fail(Failf("%v", err).WithHint("%s", usage)) + } + msg = proto.Msg{Op: proto.OpBook, Booking: &b, Days: *days, Earliest: *earliest} + case len(args) == 2 && args[0] == "move": + msg = proto.Msg{Op: proto.OpRebook} + case len(args) == 2 && args[0] == "cancel": + msg = proto.Msg{Op: proto.OpUnbook, Booking: &proto.Booking{ID: args[1]}} + default: + return c.fail(Failf("berth schedule: unexpected arguments %q", args).WithHint("%s", usage)) + } + + st, code := scheduleStatus(c, *sock) + if st == nil { + return code + } + if msg.Op == proto.OpStatus { + return c.Write(scheduleView{b: proto.BoardOf(st, now), cards: scheduledCards(st)}, nil) + } + if msg.Op == proto.OpRebook { + i := slices.IndexFunc(st.Bookings, func(x proto.Booking) bool { return x.ID == c.Args[1] }) + if i < 0 { + return c.fail(Failf("no booking %s on the schedule", c.Args[1]).WithHint("berth schedule lists them")) + } + b := st.Bookings[i] + length := b.End.Sub(b.Start) + if *atFlag != "" { + start, err := schedule.ParseAt(*atFlag, now) + if err != nil { + return c.fail(Failf("%v", err)) + } + b.Start = start + } + if *forFlag > 0 { + length = *forFlag + } + b.End = b.Start.Add(length) + if *prio != "" { + b.Priority = *prio + } + if *note != "" { + b.Note = *note + } + msg.Booking = &b + } + m, code := askBerthd(c, *sock, msg) + if m == nil { + return code + } + if m.Op == proto.OpRefused { + return c.fail(Failf("%s", m.Reason).WithHint("berth schedule shows the board")) + } + if m.Op != msg.Op { + return c.fail(Systemf("berthd answered %q: it may be older than berth schedule", m.Op).WithHint("restart berthd on this build")) + } + return c.Write(bookingsView{op: msg.Op, bs: m.Bookings}, nil) +} + +func scheduleStatus(c *Context, sock string) (*proto.Status, int) { + m, code := askBerthd(c, sock, proto.Msg{Op: proto.OpStatus}) + if m == nil { + return nil, code + } + if m.Status == nil { + return nil, c.fail(Systemf("no status from berthd: empty reply")) + } + return m.Status, ExitOK +} + +// askBerthd sends one message and reads one reply; nil means it failed and +// the int is the exit code. +func askBerthd(c *Context, sock string, msg proto.Msg) (*proto.Msg, int) { + conn, raw, err := server.Dial(sock) + if err != nil { + return nil, c.fail(Systemf("berthd unreachable on %s: %v", sock, err)) + } + defer raw.Close() + if err := conn.Send(msg); err != nil { + return nil, c.fail(Systemf("berthd on %s: %v", sock, err)) + } + m, err := conn.Recv() + if err != nil { + return nil, c.fail(Systemf("no reply from berthd: %v", err)) + } + return &m, ExitOK +} diff --git a/internal/cli/schedule_test.go b/internal/cli/schedule_test.go new file mode 100644 index 0000000..6b26994 --- /dev/null +++ b/internal/cli/schedule_test.go @@ -0,0 +1,79 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package cli + +import ( + "encoding/json" + "path/filepath" + "strings" + "testing" + + "github.com/T-Crypt/berth/internal/proto" + "github.com/T-Crypt/berth/internal/schedule" + "github.com/T-Crypt/berth/internal/server" +) + +// Booking, listing, moving and cancelling on a real berthd: the board shows +// the booking, a clash is refused with what it hits, and a booked waiter is +// queued first at the booking's class. +func TestScheduleAgainstADaemon(t *testing.T) { + isolate(t) + s, err := schedule.Open(filepath.Join(t.TempDir(), "schedule.json")) + if err != nil { + t.Fatal(err) + } + sock := startDaemonWith(t, server.Extras{Schedule: s}) + + code, out, errOut := runCLI(t, "schedule", "book", "--who", "pi-pocket", "--engine", "pocket", "--priority", "batch", + "--at", "now", "--for", "5h", "--socket", sock) + if code != 0 || !strings.Contains(out, "booked b1: run for pi-pocket") { + t.Fatalf("book (exit %d): %s %s", code, out, errOut) + } + code, _, errOut = runCLI(t, "schedule", "book", "--who", "op", "--kind", "down", "--at", "now", "--for", "1h", "--socket", sock) + if code != 1 || !strings.Contains(errOut, "clashes with b1 (run for pi-pocket") { + t.Fatalf("clash (exit %d): %s", code, errOut) + } + + holder := ask(t, sock, proto.Msg{Engine: "holder", Priority: "foreground", Pinned: true}) + if m, err := holder.Recv(); err != nil || m.Op != proto.OpGranted { + t.Fatalf("holder: %+v, %v", m, err) + } + ask(t, sock, proto.Msg{Engine: "chat", Priority: "foreground", Wait: 30}) + waitUntil(t, func() bool { return len(queueJSON(t, sock)) == 1 }) + ask(t, sock, proto.Msg{Engine: "pocket", Priority: "interactive", Wait: 30}) + waitUntil(t, func() bool { return len(queueJSON(t, sock)) == 2 }) + + code, out, errOut = runCLI(t, "schedule", "--socket", sock, "--format", "json") + if code != 0 { + t.Fatalf("schedule (exit %d): %s", code, errOut) + } + var board proto.ScheduleBoard + if err := json.Unmarshal([]byte(out), &board); err != nil { + t.Fatalf("%v: %s", err, out) + } + if len(board.Running) != 1 || board.Running[0].Engine != "holder" { + t.Errorf("running = %+v, want holder", board.Running) + } + if len(board.Queued) != 2 || board.Queued[0].Engine != "pocket" || board.Queued[0].Priority != "batch" || board.Queued[0].Booking != "b1" { + t.Errorf("queued = %+v, want pocket first at batch under b1", board.Queued) + } + if len(board.Bookings) != 1 || board.Bookings[0].ID != "b1" { + t.Errorf("bookings = %+v, want b1", board.Bookings) + } + + code, out, errOut = runCLI(t, "schedule", "move", "b1", "--at", "23:59", "--socket", sock) + if code != 0 || !strings.Contains(out, "moved b1") { + t.Fatalf("move (exit %d): %s %s", code, out, errOut) + } + waitUntil(t, func() bool { return queueJSON(t, sock)[0].Engine == "chat" }) + + code, out, errOut = runCLI(t, "schedule", "cancel", "b1", "--socket", sock) + if code != 0 || !strings.Contains(out, "cancelled b1") { + t.Fatalf("cancel (exit %d): %s %s", code, out, errOut) + } + code, out, _ = runCLI(t, "schedule", "--socket", sock) + if code != 0 || !strings.Contains(out, "nothing booked") || !strings.Contains(out, "RUNNING") { + t.Fatalf("board after cancel (exit %d): %s", code, out) + } +} diff --git a/internal/cli/unpark.go b/internal/cli/unpark.go index 952716e..f95be27 100644 --- a/internal/cli/unpark.go +++ b/internal/cli/unpark.go @@ -89,9 +89,9 @@ func parkCall(sock string, req proto.Msg, want string) (proto.Msg, *Error) { return m, nil } -func nonNil(s []string) []string { +func nonNil[T any](s []T) []T { if s == nil { - return []string{} + return []T{} } return s } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d724424..d187d24 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -234,6 +234,10 @@ func (g *Gateway) Handler() http.Handler { mux.HandleFunc("POST /v1/berth/batch", g.apiBatch) mux.HandleFunc("POST /v1/berth/yield", g.apiYield) mux.HandleFunc("POST /v1/berth/load", g.apiLoad) + mux.HandleFunc("GET /v1/berth/schedule", g.scheduleRead) + mux.HandleFunc("POST /v1/berth/schedule", g.scheduleBook) + mux.HandleFunc("PATCH /v1/berth/schedule/{id}", g.scheduleMove) + mux.HandleFunc("DELETE /v1/berth/schedule/{id}", g.scheduleCancel) for _, p := range []string{"/v1/chat/completions", "/v1/completions", "/v1/embeddings"} { mux.HandleFunc("POST "+p, g.forward) mux.HandleFunc("POST /cards/{card}"+p, g.onCard(g.forward)) diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 2779394..e9e2dd0 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -277,6 +277,12 @@ func daemon(t *testing.T) (string, *broker.Broker) { // daemonWith is daemon with cfg's fields on top of the test defaults. func daemonWith(t *testing.T, cfg broker.Config) (string, *broker.Broker) { + t.Helper() + return daemonServing(t, cfg, server.Extras{}) +} + +// daemonServing is daemonWith serving x as well (a schedule, say). +func daemonServing(t *testing.T, cfg broker.Config, x server.Extras) (string, *broker.Broker) { t.Helper() sock := filepath.Join(t.TempDir(), "berth.sock") log := slog.New(slog.NewTextHandler(io.Discard, nil)) @@ -289,7 +295,7 @@ func daemonWith(t *testing.T, cfg broker.Config) (string, *broker.Broker) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) go b.Run(ctx) - go func() { _ = server.Serve(ctx, ln, node.One(b), server.Extras{}, log) }() + go func() { _ = server.Serve(ctx, ln, node.One(b), x, log) }() // Cleanups run last first, so this runs before the cancel above. An // engine a test's gateway started may still be up; stopping the daemon // under it makes its berth run write an unprotected-run record beside diff --git a/internal/gateway/schedule.go b/internal/gateway/schedule.go new file mode 100644 index 0000000..5d02a9a --- /dev/null +++ b/internal/gateway/schedule.go @@ -0,0 +1,171 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package gateway + +// The scheduler over HTTP, for agents and devices that hold the node's key. +// GET /v1/berth/schedule is the board: what holds a card, the waiters in +// grant order, and the bookings. POST books a run, PATCH /{id} moves one and +// DELETE /{id} cancels one. A priority change and downtime act on everyone +// else's work, so they stay the operator's: berth schedule or a paired +// harbor device. + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "slices" + "time" + + "github.com/T-Crypt/berth/internal/proto" + "github.com/T-Crypt/berth/internal/schedule" + "github.com/T-Crypt/berth/internal/server" +) + +// bookBody is a booking as a client writes it. Start takes what berth +// schedule --at takes, RFC 3339 included; For is a Go duration, "5h". +type bookBody struct { + Who string `json:"who"` + Engine string `json:"engine"` + Priority string `json:"priority,omitempty"` + Start string `json:"start"` + For string `json:"for"` + Days int `json:"days,omitempty"` + Earliest bool `json:"earliest,omitempty"` + Card string `json:"card,omitempty"` + Note string `json:"note,omitempty"` +} + +func (g *Gateway) scheduleRead(w http.ResponseWriter, r *http.Request) { + st := g.nodeStatus() + if st == nil { + apiError(w, http.StatusServiceUnavailable, "berthd is not answering; no schedule to show") + return + } + writeJSON(w, http.StatusOK, proto.BoardOf(st, time.Now())) +} + +func (g *Gateway) scheduleBook(w http.ResponseWriter, r *http.Request) { + var in bookBody + if !readBody(w, r, &in) { + return + } + now := time.Now() + start, err := schedule.ParseAt(in.Start, now) + length, lerr := time.ParseDuration(in.For) + if err != nil || lerr != nil || length <= 0 { + apiError(w, http.StatusBadRequest, `the body must be JSON like {"who":"pi-pocket","engine":"NAME","start":"23:00","for":"5h"}`) + return + } + b := proto.Booking{Card: in.Card, Kind: proto.BookRun, Who: in.Who, Engine: in.Engine, Priority: in.Priority, + Start: start, End: start.Add(length), Note: in.Note} + g.scheduleAsk(w, proto.Msg{Op: proto.OpBook, Booking: &b, Days: in.Days, Earliest: in.Earliest}, http.StatusCreated) +} + +// runBooking is the run booking with the path's ID, or false after the +// reply says why not. +func (g *Gateway) runBooking(w http.ResponseWriter, r *http.Request) (proto.Booking, bool) { + st := g.nodeStatus() + if st == nil { + apiError(w, http.StatusServiceUnavailable, "berthd is not answering; the schedule is unchanged") + return proto.Booking{}, false + } + id := r.PathValue("id") + i := slices.IndexFunc(st.Bookings, func(b proto.Booking) bool { return b.ID == id }) + switch { + case i < 0: + apiError(w, http.StatusNotFound, fmt.Sprintf("no booking %s on the schedule", id)) + return proto.Booking{}, false + case st.Bookings[i].Kind != proto.BookRun: + apiError(w, http.StatusForbidden, fmt.Sprintf("%s is a %s booking: only the operator changes it (berth schedule, or the harbor)", id, st.Bookings[i].Kind)) + return proto.Booking{}, false + } + return st.Bookings[i], true +} + +func (g *Gateway) scheduleMove(w http.ResponseWriter, r *http.Request) { + b, ok := g.runBooking(w, r) + if !ok { + return + } + var in bookBody + if !readBody(w, r, &in) { + return + } + length := b.End.Sub(b.Start) + if in.Start != "" { + start, err := schedule.ParseAt(in.Start, time.Now()) + if err != nil { + apiError(w, http.StatusBadRequest, err.Error()) + return + } + b.Start = start + } + if in.For != "" { + d, err := time.ParseDuration(in.For) + if err != nil || d <= 0 { + apiError(w, http.StatusBadRequest, fmt.Sprintf("for %q is not a length like 5h", in.For)) + return + } + length = d + } + b.End = b.Start.Add(length) + if in.Priority != "" { + b.Priority = in.Priority + } + if in.Note != "" { + b.Note = in.Note + } + g.scheduleAsk(w, proto.Msg{Op: proto.OpRebook, Booking: &b}, http.StatusOK) +} + +func (g *Gateway) scheduleCancel(w http.ResponseWriter, r *http.Request) { + b, ok := g.runBooking(w, r) + if !ok { + return + } + g.scheduleAsk(w, proto.Msg{Op: proto.OpUnbook, Booking: &proto.Booking{ID: b.ID}}, http.StatusOK) +} + +// scheduleAsk sends one booking change to berthd and answers with the +// bookings it changed, or 409 with berthd's reason. +func (g *Gateway) scheduleAsk(w http.ResponseWriter, msg proto.Msg, ok int) { + conn, raw, err := server.Dial(g.Socket) + if err != nil { + apiError(w, http.StatusServiceUnavailable, "berthd is not answering; the schedule is unchanged") + return + } + defer raw.Close() + if err := conn.Send(msg); err != nil { + apiError(w, http.StatusServiceUnavailable, "berthd: "+err.Error()) + return + } + m, err := conn.Recv() + switch { + case err != nil: + apiError(w, http.StatusServiceUnavailable, "no schedule reply from berthd: "+err.Error()) + case m.Op == proto.OpRefused: + apiError(w, http.StatusConflict, m.Reason) + case m.Op != msg.Op: + apiError(w, http.StatusServiceUnavailable, fmt.Sprintf("berthd answered %q: restart it on this build", m.Op)) + default: + writeJSON(w, ok, map[string][]proto.Booking{"bookings": m.Bookings}) + } +} + +func readBody(w http.ResponseWriter, r *http.Request, v any) bool { + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<16)) + if err != nil || json.Unmarshal(body, v) != nil { + apiError(w, http.StatusBadRequest, "the body must be JSON") + return false + } + return true +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(v) +} diff --git a/internal/gateway/schedule_test.go b/internal/gateway/schedule_test.go new file mode 100644 index 0000000..83168d9 --- /dev/null +++ b/internal/gateway/schedule_test.go @@ -0,0 +1,112 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +//go:build unix + +package gateway + +import ( + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/T-Crypt/berth/internal/broker" + "github.com/T-Crypt/berth/internal/proto" + "github.com/T-Crypt/berth/internal/schedule" + "github.com/T-Crypt/berth/internal/server" +) + +func scheduleGateway(t *testing.T) (*httptest.Server, *schedule.Store) { + t.Helper() + s, err := schedule.Open(filepath.Join(t.TempDir(), "schedule.json")) + if err != nil { + t.Fatal(err) + } + sock, _ := daemonServing(t, broker.Config{}, server.Extras{Schedule: s}) + g := &Gateway{Socket: sock, Key: testKey, Log: slog.New(slog.NewTextHandler(io.Discard, nil))} + srv := httptest.NewServer(g.Handler()) + t.Cleanup(srv.Close) + return srv, s +} + +func decode[T any](t *testing.T, resp *http.Response) T { + t.Helper() + defer resp.Body.Close() + var v T + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + t.Fatal(err) + } + return v +} + +// An agent books its run, reads it on the board, moves it and cancels it; +// a clash is a 409 naming the booking it hits. +func TestScheduleRoutes(t *testing.T) { + srv, _ := scheduleGateway(t) + resp := call(t, "POST", srv.URL+"/v1/berth/schedule", `{"who":"pi-pocket","engine":"pocket","start":"23:00","for":"5h","priority":"batch"}`) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("book = %d %s", resp.StatusCode, readAll(resp)) + } + made := decode[map[string][]proto.Booking](t, resp)["bookings"] + if len(made) != 1 || made[0].ID != "b1" || made[0].Card != "gpu0" || made[0].End.Sub(made[0].Start) != 5*time.Hour { + t.Fatalf("booked = %+v", made) + } + + resp = call(t, "POST", srv.URL+"/v1/berth/schedule", `{"who":"train","engine":"sft","start":"23:30","for":"1h"}`) + if body := readAll(resp); resp.StatusCode != http.StatusConflict || !strings.Contains(body, "clashes with b1") { + t.Fatalf("clash = %d %s", resp.StatusCode, body) + } + + board := decode[proto.ScheduleBoard](t, call(t, "GET", srv.URL+"/v1/berth/schedule", "")) + if len(board.Bookings) != 1 || board.Bookings[0].Who != "pi-pocket" || board.Running == nil || board.Queued == nil { + t.Fatalf("board = %+v", board) + } + + resp = call(t, "PATCH", srv.URL+"/v1/berth/schedule/b1", `{"for":"2h"}`) + moved := decode[map[string][]proto.Booking](t, resp)["bookings"] + if resp.StatusCode != http.StatusOK || len(moved) != 1 || moved[0].End.Sub(moved[0].Start) != 2*time.Hour { + t.Fatalf("move = %d %+v", resp.StatusCode, moved) + } + + resp = call(t, "DELETE", srv.URL+"/v1/berth/schedule/b1", "") + if resp.StatusCode != http.StatusOK { + t.Fatalf("cancel = %d %s", resp.StatusCode, readAll(resp)) + } + resp.Body.Close() + if board := decode[proto.ScheduleBoard](t, call(t, "GET", srv.URL+"/v1/berth/schedule", "")); len(board.Bookings) != 0 { + t.Fatalf("after cancel = %+v", board.Bookings) + } +} + +// Downtime and priority changes are the operator's: the gateway books only +// runs, and will not move or cancel anything else. +func TestScheduleRoutesLeaveTheOperatorsBookings(t *testing.T) { + srv, s := scheduleGateway(t) + now := time.Now() + if _, err := s.Book(proto.Booking{Card: "gpu0", Kind: proto.BookDown, Who: "operator", Start: now.Add(time.Hour), End: now.Add(2 * time.Hour)}, 1, false, now); err != nil { + t.Fatal(err) + } + resp := call(t, "POST", srv.URL+"/v1/berth/schedule", `{"who":"agent","engine":"x","start":"now","for":"30m","kind":"down"}`) + made := decode[map[string][]proto.Booking](t, resp)["bookings"] + if resp.StatusCode != http.StatusCreated || made[0].Kind != proto.BookRun { + t.Fatalf("a kind in the body booked %+v (%d), want a run", made, resp.StatusCode) + } + for _, method := range []string{"PATCH", "DELETE"} { + resp := call(t, method, srv.URL+"/v1/berth/schedule/b1", `{"for":"3h"}`) + if body := readAll(resp); resp.StatusCode != http.StatusForbidden || !strings.Contains(body, "only the operator") { + t.Errorf("%s downtime = %d %s, want 403", method, resp.StatusCode, body) + } + } +} + +func readAll(resp *http.Response) string { + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return string(b) +} diff --git a/internal/harbor/harbor.go b/internal/harbor/harbor.go index f0b7c6a..982c3e1 100644 --- a/internal/harbor/harbor.go +++ b/internal/harbor/harbor.go @@ -133,6 +133,7 @@ func (h *Harbor) Handler() http.Handler { mux.HandleFunc("POST /v1/board/stop", h.boardAction("stop")) mux.HandleFunc("POST /v1/board/load", h.boardAction("load")) mux.HandleFunc("POST /v1/board/queue", h.boardQueue) + mux.HandleFunc("POST /v1/board/schedule", h.boardSchedule) mux.HandleFunc("POST /v1/pair/code", h.pairCode) return h.guard(mux) } @@ -191,7 +192,7 @@ func (h *Harbor) guard(next http.Handler) http.Handler { } // writePaths are the only paths the harbor takes a POST on. -var writePaths = map[string]bool{"/pair": true, "/v1/board/switch": true, "/v1/board/stop": true, "/v1/board/load": true, "/v1/board/queue": true, "/v1/pair/code": true} +var writePaths = map[string]bool{"/pair": true, "/v1/board/switch": true, "/v1/board/stop": true, "/v1/board/load": true, "/v1/board/queue": true, "/v1/board/schedule": true, "/v1/pair/code": true} // mode tells the page which guard this harbor runs under. It is a harbor // fact, stable for the process lifetime, so the page fetches it once: unlike diff --git a/internal/harbor/schedule_test.go b/internal/harbor/schedule_test.go new file mode 100644 index 0000000..67ea1cd --- /dev/null +++ b/internal/harbor/schedule_test.go @@ -0,0 +1,60 @@ +// Copyright 2026 Trevin Tindall (T-Crypt) +// SPDX-License-Identifier: Apache-2.0 + +package harbor + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/T-Crypt/berth/internal/proto" +) + +// A paired device books downtime, moves it and cancels it through the +// harbor, straight to berthd; the board reads it from /v1/status; an +// unpaired device changes nothing; nothing reaches the gateway. +func TestBoardSchedule(t *testing.T) { + base, gw, token, _ := brokerHarbor(t, testKey) + paired := map[string]string{"Cookie": cookieName + "=" + token, "X-Berth": "1", "Sec-Fetch-Site": "same-origin"} + unpaired := map[string]string{"X-Berth": "1", "Sec-Fetch-Site": "same-origin"} + start := time.Now().Add(time.Hour).Truncate(time.Minute) + down := func(id string, from time.Time, d time.Duration) string { + b, _ := json.Marshal(proto.Booking{ID: id, Kind: proto.BookDown, Who: "operator", Start: from, End: from.Add(d), Note: "driver update"}) + return string(b) + } + + if code, body := call(t, "POST", base+"/v1/board/schedule", `{"action":"book","booking":`+down("", start, time.Hour)+`}`, unpaired); code != 401 { + t.Fatalf("unpaired book = %d %s, want 401", code, body) + } + code, body := call(t, "POST", base+"/v1/board/schedule", `{"action":"book","days":2,"booking":`+down("", start, time.Hour)+`}`, paired) + var got struct{ Bookings []proto.Booking } + if code != 200 || json.Unmarshal([]byte(body), &got) != nil || len(got.Bookings) != 2 || got.Bookings[0].Card != "gpu0" { + t.Fatalf("book = %d %s", code, body) + } + + code, body = call(t, "GET", base+"/v1/status", "", nil) + var st proto.Status + if code != 200 || json.Unmarshal([]byte(body), &st) != nil || len(st.Bookings) != 2 || st.Bookings[0].Note != "driver update" { + t.Fatalf("status bookings = %d %s", code, body) + } + + if code, body = call(t, "POST", base+"/v1/board/schedule", `{"action":"move","booking":`+down("b1", start.Add(30*time.Minute), time.Hour)+`}`, paired); code != 200 { + t.Fatalf("move = %d %s", code, body) + } + if code, body = call(t, "POST", base+"/v1/board/schedule", `{"action":"move","booking":`+down("b1", start.AddDate(0, 0, 1), time.Hour)+`}`, paired); code != 409 || !strings.Contains(body, "clashes with b2") { + t.Fatalf("move onto b2 = %d %s, want 409", code, body) + } + if code, body = call(t, "POST", base+"/v1/board/schedule", `{"action":"cancel","booking":{"id":"b2"}}`, paired); code != 200 { + t.Fatalf("cancel = %d %s", code, body) + } + for _, bad := range []string{`{"action":"nap","booking":{}}`, `{"action":"cancel","booking":{}}`, `{"action":"book","booking":{"id":"b1"}}`, `{"action":"book"}`} { + if code, body = call(t, "POST", base+"/v1/board/schedule", bad, paired); code != 400 { + t.Fatalf("%s = %d %s, want 400", bad, code, body) + } + } + if gw.last() != "" { + t.Fatalf("a schedule action reached the gateway: %q", gw.last()) + } +} diff --git a/internal/harbor/switchboard.go b/internal/harbor/switchboard.go index 10426a5..c7c10a4 100644 --- a/internal/harbor/switchboard.go +++ b/internal/harbor/switchboard.go @@ -106,6 +106,39 @@ func (h *Harbor) boardQueue(w http.ResponseWriter, r *http.Request) { } } +// boardSchedule is POST /v1/board/schedule: a paired device books, moves or +// cancels any booking, downtime and priority changes included. Like the +// queue, it goes to berthd's socket: agents holding the gateway's key book +// only their own runs there. +func (h *Harbor) boardSchedule(w http.ResponseWriter, r *http.Request) { + if !h.writeOK(w, r) { + return + } + var req struct { + Action string `json:"action"` + Booking *proto.Booking `json:"booking"` + Days int `json:"days,omitempty"` + Earliest bool `json:"earliest,omitempty"` + } + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<16)) + op := map[string]string{"book": proto.OpBook, "move": proto.OpRebook, "cancel": proto.OpUnbook} + if err != nil || json.Unmarshal(body, &req) != nil || op[req.Action] == "" || req.Booking == nil || + (req.Action != "book") != (req.Booking.ID != "") { + apiError(w, http.StatusBadRequest, "bad_body", `the body must be JSON like {"action":"book","booking":{...}} or {"action":"move|cancel","booking":{"id":"b1",...}}`) + return + } + m, err := h.ask(proto.Msg{Op: op[req.Action], Booking: req.Booking, Days: req.Days, Earliest: req.Earliest}) + switch { + case err != nil: + apiError(w, http.StatusServiceUnavailable, "berthd_down", "berthd is not answering; the schedule is unchanged") + case m.Op == proto.OpRefused: + apiError(w, http.StatusConflict, "refused", m.Reason) + default: + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string][]proto.Booking{"bookings": m.Bookings}) + } +} + // toGateway sends one request to the gateway with the node's key and hands // its status and body back to the page. func (h *Harbor) toGateway(w http.ResponseWriter, r *http.Request, method, path string, body []byte) { diff --git a/internal/harbor/switchboard_test.go b/internal/harbor/switchboard_test.go index f9b5c40..95aa6de 100644 --- a/internal/harbor/switchboard_test.go +++ b/internal/harbor/switchboard_test.go @@ -20,6 +20,7 @@ import ( "github.com/T-Crypt/berth/internal/node" "github.com/T-Crypt/berth/internal/pair" "github.com/T-Crypt/berth/internal/procs" + "github.com/T-Crypt/berth/internal/schedule" "github.com/T-Crypt/berth/internal/server" ) @@ -83,7 +84,11 @@ func brokerHarbor(t *testing.T, key string) (base string, gw *fakeGateway, token ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) s := &pair.Store{Path: filepath.Join(dir, "harbor-devices.json")} - go server.Serve(ctx, ln, node.One(b), server.Extras{Pair: s}, log) + sched, err := schedule.Open(filepath.Join(dir, "schedule.json")) + if err != nil { + t.Fatal(err) + } + go server.Serve(ctx, ln, node.One(b), server.Extras{Pair: s, Schedule: sched}, log) code, err := s.Code() if err != nil { t.Fatal(err) diff --git a/internal/harbor/web/harbor.css b/internal/harbor/web/harbor.css index 3607b80..1f61314 100644 --- a/internal/harbor/web/harbor.css +++ b/internal/harbor/web/harbor.css @@ -1994,3 +1994,79 @@ body.reduced-motion .si-live, body.reduced-motion .si-connecting, body.reduced-m .pair input { padding: 0.6rem; font-size: 1rem; color: var(--ink-strong); background: var(--panel-3); border: 1px solid var(--edge); border-radius: 6px; } .pair button { padding: 0.75rem; font-size: 1rem; color: var(--ink-strong); background: var(--cyan-deep); border: 1px solid var(--cyan-dim); border-radius: 6px; } .pair a { color: var(--cyan); } + +/* ---------------- SCHEDULE: the card's scheduler ---------------- */ +.sb-now { display: flex; flex-direction: column; gap: var(--s2); } +.sb-line { font-family: var(--mono); font-size: var(--fs-small); color: var(--ink); border-left: 3px solid var(--hair-2); padding: var(--s1) var(--s2); } +.sb-line-run { border-left-color: var(--cyan); } +.sb-line-priority { border-left-color: var(--amber); } +.sb-line-down { border-left-color: var(--magenta); color: var(--ink-strong); } +.sb-chip-run { color: var(--cyan); border-color: var(--cyan-dim); } +.sb-head-actions { display: inline-flex; align-items: center; gap: var(--s3); flex-wrap: wrap; justify-content: flex-end; } +.sb-legend { display: inline-flex; align-items: center; gap: var(--s1); font-size: var(--fs-micro); color: var(--dim); } +.sb-key { display: inline-block; width: 12px; height: 8px; border-radius: 2px; margin-left: var(--s2); } +.sb-k-run { background: var(--cyan-deep); border: 1px solid var(--cyan); } +.sb-k-priority { background: transparent; border: 1px dashed var(--amber); } +.sb-k-down { background: repeating-linear-gradient(135deg, var(--magenta-deep) 0 3px, transparent 3px 6px); border: 1px solid var(--magenta); } +.sb-k-window { background: var(--green); height: 3px; opacity: 0.6; } +.sb-k-live { background: var(--green); } +.sb-card-pick { display: flex; gap: var(--s2); margin-bottom: var(--s2); flex-wrap: wrap; } +.sb-card-pick .btn[aria-pressed="true"] { color: var(--cyan); border-color: var(--cyan); background: var(--cyan-wash); } +.sb-board { display: flex; flex-direction: column; gap: 3px; overflow-x: auto; padding-bottom: var(--s1); } +.sb-row { display: grid; grid-template-columns: 64px minmax(560px, 1fr); align-items: stretch; gap: var(--s2); } +.sb-day { font-family: var(--mono); font-size: var(--fs-small); color: var(--dim); align-self: center; white-space: nowrap; } +.sb-today { color: var(--amber); font-weight: 700; } +.sb-track { + position: relative; height: 46px; border-radius: var(--r1); cursor: copy; + background-color: var(--panel-3); + /* an hour line every 1/24, stronger every 6 h */ + background-image: + repeating-linear-gradient(to right, var(--hair) 0 1px, transparent 1px calc(100% / 4)), + repeating-linear-gradient(to right, var(--chart-grid) 0 1px, transparent 1px calc(100% / 24)); +} +.sb-hours .sb-track { height: 16px; background: none; cursor: default; } +.sb-tick { position: absolute; top: 0; transform: translateX(-1px); font-family: var(--mono); font-size: var(--fs-micro); color: var(--dim-2); } +.sb-past { position: absolute; inset: 0 auto 0 0; background: rgba(6, 11, 17, 0.55); pointer-events: none; border-radius: var(--r1) 0 0 var(--r1); } +.sb-nowline { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--amber); box-shadow: 0 0 6px var(--amber); pointer-events: none; z-index: 3; } +.sb-window { position: absolute; bottom: 1px; height: 3px; background: var(--green); opacity: 0.45; pointer-events: none; border-radius: 2px; } +.sb-live { position: absolute; top: 1px; height: 4px; background: var(--green); border-radius: 2px; pointer-events: none; z-index: 2; } +.sb-bar { + position: absolute; top: 7px; height: 22px; min-width: 3px; padding: 0 var(--s1); + overflow: hidden; border-radius: 3px; cursor: pointer; text-align: left; + font-family: var(--mono); font-size: var(--fs-micro); line-height: 20px; color: var(--ink-strong); + border: 1px solid var(--cyan); background: var(--cyan-deep); +} +.sb-bar:hover, .sb-bar:focus-visible { filter: brightness(1.25); outline: 1px solid var(--ink-strong); z-index: 4; } +.sb-bar-text { white-space: nowrap; } +.sb-priority { background: rgba(232, 181, 111, 0.12); border: 1px dashed var(--amber); color: var(--amber); } +.sb-down { background: repeating-linear-gradient(135deg, var(--magenta-deep) 0 6px, var(--magenta-dim) 6px 12px); border-color: var(--magenta); } +.sb-lane2 { top: 31px; height: 13px; line-height: 11px; } +.sb-hint { margin-top: var(--s2); font-size: var(--fs-micro); color: var(--dim-2); } +.sq.sb-item-run { border-left-color: var(--cyan); } +.sq.sb-item-priority { border-left-color: var(--amber); } +.sq.sb-item-down { border-left-color: var(--magenta); } + +dialog#sched-dlg { border: 1px solid var(--hair-2); padding: 0; background: var(--panel); color: var(--ink); border-radius: 8px; box-shadow: var(--shadow-pop); max-width: 460px; width: calc(100vw - 32px); } +dialog#sched-dlg::backdrop { background: var(--scrim); backdrop-filter: blur(3px); } +.sched-form { padding: var(--s3); display: flex; flex-direction: column; gap: var(--s2); font-family: var(--mono); font-size: var(--fs-small); } +.sched-form label { display: flex; flex-direction: column; gap: 2px; color: var(--dim); font-size: var(--fs-micro); letter-spacing: 0.5px; } +.sched-form label[hidden], .sched-form .sf-row[hidden] { display: none; } +.sched-form input, .sched-form select { + min-height: 36px; padding: 0 var(--s2); border: 1px solid var(--edge); border-radius: var(--r1); + background: var(--panel-3); color: var(--ink-strong); font: inherit; font-size: var(--fs-body); +} +.sched-form input:focus-visible, .sched-form select:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; } +.sf-row { display: flex; gap: var(--s3); flex-wrap: wrap; } +.sf-row label { flex: 1 1 140px; } +.sf-row input[type="number"] { width: 100%; } +.sched-form .sf-check { flex-direction: row; align-items: center; gap: var(--s2); align-self: flex-end; min-height: 36px; } +.sched-form .sf-check input { min-height: 0; } +.sf-explain { margin: 0; color: var(--ink); line-height: 1.5; border-left: 3px solid var(--cyan-dim); padding-left: var(--s2); } +.sf-error { margin: 0; color: var(--magenta); } +.sf-error:empty, .sf-explain:empty { display: none; } +@media (max-width: 640px) { + .sb-row { grid-template-columns: 44px minmax(520px, 1fr); } + .sb-legend { display: none; } +} +.sb-edit { cursor: pointer; background: none; color: var(--cyan); border-color: var(--cyan-dim); font-family: var(--mono); min-height: 24px; } +.sb-edit:hover, .sb-edit:focus-visible { color: var(--ink-strong); border-color: var(--cyan); } diff --git a/internal/harbor/web/harbor.js b/internal/harbor/web/harbor.js index 29059f8..e0d87d7 100644 --- a/internal/harbor/web/harbor.js +++ b/internal/harbor/web/harbor.js @@ -13,6 +13,7 @@ import { EngineView } from "./engines.js"; import { LibraryView } from "./library.js"; import { ResidencyView } from "./residency.js"; import { initSwitch } from "./switch.js"; +import { initSchedule } from "./schedule.js"; import { sparkline, lineChart, stackedArea, timelineChart } from "./charts.js"; import { PAL } from "./palette.js"; import { GIB } from "./util.js"; @@ -124,7 +125,7 @@ function initialLbRange() { return "24h"; } -let board, ticket, engineView, residency, priorityView, libraryView, switchView; +let board, ticket, engineView, residency, priorityView, libraryView, switchView, scheduleView; let connPill, statePill, vmPill, nodeVersion, lastUpdate, demoStrip, alertStripEl; let odometerReels, counterSince, counterMeta; let ctiles; @@ -205,6 +206,7 @@ function main() { residency = new ResidencyView($("residency-canvas"), $("residency-legend"), $("residency-sessions"), $("residency-meta")); residency.colorOf = (name) => engineColor(name); switchView = initSwitch({ demo: state.demo }); + scheduleView = initSchedule({ demo: state.demo }); buildKpiStrip(); wireMode(); applyMode(); @@ -471,8 +473,8 @@ function applyMode() { // ---------------- tabs ---------------- function wireTabs() { - const tabs = { harbor: $("tab-harbor"), switch: $("tab-switch"), engines: $("tab-engines"), about: $("tab-about") }; - const panels = { harbor: $("panel-harbor"), switch: $("panel-switch"), engines: $("panel-engines"), about: $("panel-about") }; + const tabs = { harbor: $("tab-harbor"), switch: $("tab-switch"), schedule: $("tab-schedule"), engines: $("tab-engines"), about: $("tab-about") }; + const panels = { harbor: $("panel-harbor"), switch: $("panel-switch"), schedule: $("panel-schedule"), engines: $("panel-engines"), about: $("panel-about") }; const show = (key) => { if (!tabs[key]) key = "harbor"; for (const k of Object.keys(tabs)) { @@ -482,6 +484,7 @@ function wireTabs() { } if (key === "engines" && state.status) engineView.render(state.status); if (key === "switch") switchView.show(); else switchView.hide(); + if (key === "schedule") scheduleView.show(); else scheduleView.hide(); }; for (const key of Object.keys(tabs)) { tabs[key].addEventListener("click", () => { @@ -518,6 +521,7 @@ const ENGINES_SECTIONS = [ ["sec-recent", "Recent"], ["sec-residency", "Residency"], ["sec-storage", "Storage"], ]; const SWITCH_SECTIONS = [["sec-switch-cards", "Cards"], ["sec-switch-queue", "Queue"], ["sec-switch-engines", "Engines"]]; +const SCHEDULE_SECTIONS = [["sec-sched-now", "Now"], ["sec-sched-board", "7 days"], ["sec-sched-list", "Bookings"]]; const ABOUT_SECTIONS = [ ["about-top", "Berth"], ["about-cards", "Cards"], ["about-modes", "Modes"], ["about-nav", "Getting around"], ["about-keys", "Keyboard"], ["about-states", "Status words"], ["about-kpis", "KPIs"], ["about-counters", "Counters"], @@ -531,6 +535,7 @@ function wireChrome() { } catch (e) { state.collapsed = []; } buildSubnav($("subnav-harbor"), HARBOR_SECTIONS); buildSubnav($("subnav-switch"), SWITCH_SECTIONS); + buildSubnav($("subnav-schedule"), SCHEDULE_SECTIONS); buildSubnav($("subnav-engines"), ENGINES_SECTIONS); buildSubnav($("subnav-about"), ABOUT_SECTIONS); wireCollapse(); @@ -629,7 +634,7 @@ function wireShortcuts() { const mode = document.querySelector(".app-header .mode"); if (mode) mode.before(keys); shortcutsDlg.querySelector(".sc-close").addEventListener("click", () => shortcutsDlg.close()); - const tabFor = { 1: "tab-harbor", 2: "tab-switch", 3: "tab-engines", 4: "tab-about" }; + const tabFor = { 1: "tab-harbor", 2: "tab-switch", 3: "tab-schedule", 4: "tab-engines", 5: "tab-about" }; for (const k of Object.keys(tabFor)) onKey(k, () => $(tabFor[k]).click()); onKey("b", () => setMode("basic", true)); onKey("a", () => setMode("advanced", true)); diff --git a/internal/harbor/web/index.html b/internal/harbor/web/index.html index cc12d26..7d68f28 100644 --- a/internal/harbor/web/index.html +++ b/internal/harbor/web/index.html @@ -29,6 +29,7 @@ @@ -227,6 +228,36 @@

ENGINES

+ +