console: the instance usage route and its start month
usage/instances/@from.json is written create-only, as the first day of
the next UTC month, once the console holds its hostname history verified
active with CONSOLE_INSTANCE_USAGE on (RunUsageFrom at start, and every
route call). Pending or unread is 503 and touches nothing; not active or
host claims is 409; a held state with another At moves From forward by
CAS, never back.
GET /api/cli/apps/{account}/{app}/usage?month=YYYY-MM: the instance gate,
the month, the history check, a month before From (409 naming the first
month), the 60 s memo keyed by sqid/app/month, then one LIST and a GET
per box and date up to today through the settled-day cache, fetched
ahead with a per-key dry body. Any unreadable object is a 503 with
Retry-After: 60 and the InstanceUsageRead request job's failed run.
Over 10,000 instances is 409. usageDayDate knows the root instance family.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,666
−21
cmd/console/main.go+8 −0internal/console/apilinks_test.go+5 −3internal/console/apiusage.go+334 −6internal/console/apiusage_test.go+616 −0internal/console/claim_workers.go+6 −0internal/console/jobs.go+19 −0internal/console/jobs_test.go+23 −7internal/console/server.go+3 −0internal/console/usagedays.go+9 −2internal/console/usagefrom.go+203 −0internal/console/usagefrom_test.go+433 −0internal/console/usagerole_test.go+7 −3
Intent
diff --git a/cmd/console/main.go b/cmd/console/main.go| index ccfc10413..363d82288 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -892,6 +892,14 @@ func serve() { |
| srv.RunFleetOwnerBackfill(ctx) |
| srv.RunAppPlacementBackfill(ctx) |
| }) |
| + // The instance usage attribution start (instance usage design §4): |
| + // checked now and every minute until usage/instances/@from.json is |
| + // held, then done. After LoadHostsMode above, whose held state it |
| + // reads, and after ConfigureClaimRuntime, so it never races that |
| + // swap of cfg.Releases. Only with the switch on. |
| + if cfg.InstanceUsage { |
| + work.Go("RunUsageFrom", srv.RunUsageFrom) |
| + } |
| // Each claim worker runs on work's context under its own name. |
| startClaimWorker := func(name string) { |
| work.Go(name, func(ctx context.Context) { srv.RunClaimWorker(ctx, name) }) |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| index 731cedbd5..a03d4c98e 100644 |
| --- a/internal/console/apilinks_test.go |
| +++ b/internal/console/apilinks_test.go |
| @@ -666,9 +666,11 @@ var linkedAllowAnswers = map[string]int{ |
| "GET /api/cli/apps/{account}/{app}/analytics": http.StatusOK, |
| // The fixture deployment has no GeoIP database: the door's own answer. |
| "GET /api/cli/apps/{account}/{app}/geo": http.StatusServiceUnavailable, |
| - // The usage read's placeholder answers 501 past its gates until the |
| - // read lands (instance usage Task 6). |
| - "GET /api/cli/apps/{account}/{app}/usage": http.StatusNotImplemented, |
| + // The usage read past its gates: the walk's console never ran the |
| + // start-up read of its hostname history, so the read answers the |
| + // history's pending 503 (instance usage design §8), not the linked |
| + // refusal. TestLinkedAppReachesTheUsageDoor holds its 200. |
| + "GET /api/cli/apps/{account}/{app}/usage": http.StatusServiceUnavailable, |
| // Paul's ruling (2026-11-10): the hub applies these to a link's forward |
| // row, so they stay editable; each redirects back with its flash. |
| "POST /a/{sqid}/apps/{app}/analytics/setting": http.StatusSeeOther, |
diff --git a/internal/console/apiusage.go b/internal/console/apiusage.go| index 64c61f86b..0ce77d9a7 100644 |
| --- a/internal/console/apiusage.go |
| +++ b/internal/console/apiusage.go |
| @@ -1,13 +1,341 @@ |
| package console |
| -import "net/http" |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "os" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "time" |
| -// handleAPIUsage answers `carlos usage` (instance usage design §8). A |
| -// placeholder until the read lands: the instance gate (a member, or a |
| -// credential the door admits, bound to this app), then 501. |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// The usage read, `carlos usage` (instance usage design §8): one app's |
| +// bytes and requests per instance for one whole UTC month at or after the |
| +// attribution start (usagefrom.go), summed from the per-box, per-date |
| +// objects under usage/instances/ in this console's own store. It wakes |
| +// nothing and reads no record. |
| + |
| +// The route's copy (docs/superpowers/notes/instance-usage-copy.md §F). |
| +const ( |
| + msgUsageMonthMalformed = "month: want YYYY-MM, such as 2027-01" // F1 |
| + msgUsageNotActive = "Usage by instance is not available on this console: its hostname history is not active, so bytes cannot be tied to one instance." // F4 |
| + msgUsagePending = "The console is still checking its hostname history. Try again in a minute." // F5 |
| + msgUsageUnreadable = "Could not read this app's usage. Try again in a minute." // F6 |
| + msgUsageOverCap = "This app has more than 10,000 instances with traffic this month, so the results cannot fit in one answer. Ask for paging." // F7 |
| +) |
| + |
| +// msgUsageMonthFuture is F2. |
| +func msgUsageMonthFuture(month string) string { |
| + return "month: " + month + " has not started yet" |
| +} |
| + |
| +// msgUsageBeforeFrom is F3, from the first day counting covers. |
| +func msgUsageBeforeFrom(from time.Time) string { |
| + return "Counting by instance starts on " + from.Format("2 January 2006") + ". Ask for " + from.Format("2006-01") + " or later." |
| +} |
| + |
| +// usageInstanceCap is the most instances one answer lists (about 1.1 MB of |
| +// JSON); past it the route refuses rather than pages. |
| +const usageInstanceCap = 10000 |
| + |
| +// usageMemoTTL is how long an answer is reused for one account, app and |
| +// month. Counts reach the objects within a five-minute flush anyway. |
| +const usageMemoTTL = time.Minute |
| + |
| +// usageRetryAfter is the Retry-After of every 503 the route gives. |
| +const usageRetryAfter = "60" |
| + |
| +// usageMonthLayout is the month parameter's one form. |
| +const usageMonthLayout = "2006-01" |
| + |
| +type usageResponse struct { |
| + App string `json:"app"` |
| + Month string `json:"month"` |
| + From string `json:"from"` // month start, RFC 3339 |
| + To string `json:"to"` // next month start |
| + Instances []usageInstance `json:"instances"` |
| + Unattributed usageTotals `json:"unattributed"` |
| + Total usageTotals `json:"total"` |
| + ReadAt string `json:"read_at"` |
| +} |
| + |
| +// usageInstance is one instance host's counts. The hop fields are the |
| +// subset served through another box: inside the totals, never added. |
| +type usageInstance struct { |
| + Host string `json:"host"` |
| + BytesOut int64 `json:"bytes_out"` |
| + Requests int64 `json:"requests"` |
| + HopBytesOut int64 `json:"hop_bytes_out,omitempty"` |
| + HopRequests int64 `json:"hop_requests,omitempty"` |
| +} |
| + |
| +type usageTotals struct { |
| + BytesOut int64 `json:"bytes_out"` |
| + Requests int64 `json:"requests"` |
| +} |
| + |
| +// usageMemo holds the route's answers for usageMemoTTL, keyed by the |
| +// gate's account sqid, the app and the month. Only answers are kept: a |
| +// read fault never is. Expired entries are dropped on every put, so it |
| +// holds at most a minute of distinct asks. |
| +type usageMemo struct { |
| + mu sync.Mutex |
| + m map[string]usageMemoEntry |
| +} |
| + |
| +// usageMemoEntry is one answer: a 200 with its body, or the over-cap 409. |
| +type usageMemoEntry struct { |
| + at time.Time |
| + status int |
| + resp usageResponse |
| + overCap bool |
| +} |
| + |
| +func (c *usageMemo) get(key string, now time.Time) (usageMemoEntry, bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + e, ok := c.m[key] |
| + if !ok || now.Sub(e.at) >= usageMemoTTL || now.Before(e.at) { |
| + return usageMemoEntry{}, false |
| + } |
| + return e, true |
| +} |
| + |
| +func (c *usageMemo) put(key string, e usageMemoEntry) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.m == nil { |
| + c.m = map[string]usageMemoEntry{} |
| + } |
| + for k, o := range c.m { |
| + if e.at.Sub(o.at) >= usageMemoTTL || e.at.Before(o.at) { |
| + delete(c.m, k) |
| + } |
| + } |
| + c.m[key] = e |
| +} |
| + |
| +// handleAPIUsage answers `carlos usage`. In order: the instance gate (a |
| +// member, or a credential the door admits, bound to this app); the month; |
| +// the hostname history and the attribution start (usageFromCheck), before |
| +// any memo answer; a month before the start; the memo; the read. |
| func (s *Server) handleAPIUsage(w http.ResponseWriter, r *http.Request) { |
| - if _, _, _, ok := s.instanceGate(w, r); !ok { |
| + _, acct, app, ok := s.instanceGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + now := s.usageClock().UTC() |
| + month := r.URL.Query().Get("month") |
| + if month == "" { |
| + month = now.Format(usageMonthLayout) |
| + } |
| + start, err := time.Parse(usageMonthLayout, month) |
| + if err != nil || start.Format(usageMonthLayout) != month { |
| + jsonError(w, http.StatusBadRequest, msgUsageMonthMalformed) |
| + return |
| + } |
| + if start.After(now) { |
| + jsonError(w, http.StatusBadRequest, msgUsageMonthFuture(month)) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| + defer cancel() |
| + v, err := s.usageFromCheck(ctx, now) |
| + if err != nil { |
| + log.Printf("console: api usage %s/%s: the attribution start: %v", acct.Sqid, app, err) |
| + usageUnavailable(w, msgUsageUnreadable) |
| + return |
| + } |
| + if v.Status == http.StatusServiceUnavailable { |
| + usageUnavailable(w, v.Msg) |
| + return |
| + } |
| + if v.Status != 0 { |
| + jsonError(w, v.Status, v.Msg) |
| return |
| } |
| - jsonError(w, http.StatusNotImplemented, "not implemented") |
| + from, err := time.Parse(time.DateOnly, v.From.From) |
| + if err != nil { // decodeUsageFrom and firstOfNextMonth make this impossible |
| + log.Printf("console: api usage %s/%s: the attribution start %q: %v", acct.Sqid, app, v.From.From, err) |
| + usageUnavailable(w, msgUsageUnreadable) |
| + return |
| + } |
| + if start.Before(from) { |
| + writeJSON(w, http.StatusConflict, map[string]string{"error": msgUsageBeforeFrom(from), "first_month": from.Format(usageMonthLayout)}) |
| + return |
| + } |
| + |
| + key := acct.Sqid + "/" + app + "/" + month |
| + if e, ok := s.usageMemo.get(key, now); ok { |
| + writeUsageEntry(w, e) |
| + return |
| + } |
| + var sums map[string]usage.InstanceCount |
| + err = s.jobs.Run(ctx, "InstanceUsageRead", func(ctx context.Context) error { |
| + var err error |
| + sums, _, err = s.readInstanceUsage(ctx, acct.Sqid, app, usageDates(start, from, now), now) |
| + return err |
| + }) |
| + if err != nil { |
| + log.Printf("console: api usage %s/%s %s: %v", acct.Sqid, app, month, err) |
| + usageUnavailable(w, msgUsageUnreadable) |
| + return |
| + } |
| + e := usageMemoEntry{at: now, status: http.StatusOK} |
| + if e.resp, e.overCap = buildUsageResponse(app, month, start, sums, now); e.overCap { |
| + e.status = http.StatusConflict |
| + } |
| + s.usageMemo.put(key, e) |
| + writeUsageEntry(w, e) |
| +} |
| + |
| +func writeUsageEntry(w http.ResponseWriter, e usageMemoEntry) { |
| + if e.overCap { |
| + jsonError(w, http.StatusConflict, msgUsageOverCap) |
| + return |
| + } |
| + writeJSON(w, e.status, e.resp) |
| +} |
| + |
| +// usageUnavailable is a 503 the caller may retry in a minute. |
| +func usageUnavailable(w http.ResponseWriter, msg string) { |
| + w.Header().Set("Retry-After", usageRetryAfter) |
| + jsonError(w, http.StatusServiceUnavailable, msg) |
| +} |
| + |
| +// usageDates is every date of the month starting at start, from the later |
| +// of start and from, to the earlier of the month's last day and today. |
| +func usageDates(start, from, now time.Time) []string { |
| + first := start |
| + if from.After(first) { |
| + first = from |
| + } |
| + last := start.AddDate(0, 1, -1) |
| + if today := now.UTC().Truncate(24 * time.Hour); today.Before(last) { |
| + last = today |
| + } |
| + var out []string |
| + for d := first; !d.After(last); d = d.AddDate(0, 0, 1) { |
| + out = append(out, d.Format(time.DateOnly)) |
| + } |
| + return out |
| +} |
| + |
| +// buildUsageResponse is the answer from the summed counts: instances by |
| +// host, "" as unattributed, total both together. overCap when more than |
| +// usageInstanceCap instances had traffic. |
| +func buildUsageResponse(app, month string, start time.Time, sums map[string]usage.InstanceCount, now time.Time) (usageResponse, bool) { |
| + out := usageResponse{ |
| + App: app, Month: month, |
| + From: start.Format(time.RFC3339), |
| + To: start.AddDate(0, 1, 0).Format(time.RFC3339), |
| + Instances: []usageInstance{}, |
| + ReadAt: now.UTC().Format(time.RFC3339), |
| + } |
| + for host, c := range sums { |
| + out.Total.BytesOut += c.BytesOut |
| + out.Total.Requests += c.Requests |
| + if host == "" { |
| + out.Unattributed = usageTotals{BytesOut: c.BytesOut, Requests: c.Requests} |
| + continue |
| + } |
| + out.Instances = append(out.Instances, usageInstance{Host: host, BytesOut: c.BytesOut, Requests: c.Requests, |
| + HopBytesOut: c.HopBytesOut, HopRequests: c.HopRequests}) |
| + } |
| + if len(out.Instances) > usageInstanceCap { |
| + return usageResponse{}, true |
| + } |
| + sort.Slice(out.Instances, func(i, j int) bool { return out.Instances[i].Host < out.Instances[j].Host }) |
| + return out, false |
| +} |
| + |
| +// instanceUsageDryBody is the smallest valid day object for key: the dry |
| +// pass of readInstanceUsage takes it as it takes a real one, so every key |
| +// is named and fetched ahead. |
| +func instanceUsageDryBody(key string) []byte { |
| + box, date, account, app, ok := usage.ParseInstanceDayKey(key) |
| + if !ok { |
| + return []byte("{}") |
| + } |
| + raw, _ := json.Marshal(usage.InstanceDay{V: 1, Box: box, Date: date, Account: account, App: app, |
| + Applied: map[string]string{}, Instances: map[string]usage.InstanceCount{}}) |
| + return raw |
| +} |
| + |
| +// readInstanceUsage sums one app's counts per host over every box under |
| +// usage/instances/ and every date given: one LIST, then one GET per box |
| +// and date, read concurrently through the settled-day cache. A missing |
| +// object is a box that served none of the app's traffic that day; any |
| +// other failure (a read error, a body over the read cap, one that does |
| +// not parse or does not match its key) is the whole read's error, never a |
| +// smaller figure. |
| +func (s *Server) readInstanceUsage(ctx context.Context, sqid, app string, dates []string, now time.Time) (map[string]usage.InstanceCount, prefetchStats, error) { |
| + type out struct { |
| + sums map[string]usage.InstanceCount |
| + err error |
| + } |
| + o, stats := readConcurrentlyStatsFor(ctx, s.usageDayReader(now), nil, instanceUsageDryBody, usageDayLimit, func(rs release.Store) out { |
| + sums, err := sumInstanceUsage(ctx, rs, sqid, app, dates) |
| + return out{sums, err} |
| + }) |
| + if o.err == nil { |
| + if err := ctx.Err(); err != nil { |
| + o.err = fmt.Errorf("console: instance usage: %w", err) |
| + } |
| + } |
| + return o.sums, stats, o.err |
| +} |
| + |
| +// sumInstanceUsage is readInstanceUsage's reader over rs. Which keys it |
| +// reads follows from the listing alone. |
| +func sumInstanceUsage(ctx context.Context, rs release.Store, sqid, app string, dates []string) (map[string]usage.InstanceCount, error) { |
| + dirs, err := rs.ListDirs(ctx, usage.InstancesPrefix) |
| + if err != nil { |
| + return nil, fmt.Errorf("console: instance usage: list %s: %w", usage.InstancesPrefix, err) |
| + } |
| + var boxes []string |
| + for _, d := range dirs { |
| + box := strings.TrimSuffix(strings.TrimPrefix(d, usage.InstancesPrefix), "/") |
| + if keySegment(box) && d == usage.InstancesPrefix+box+"/" { |
| + boxes = append(boxes, box) |
| + } |
| + } |
| + sort.Strings(boxes) |
| + sums := map[string]usage.InstanceCount{} |
| + for _, box := range boxes { |
| + for _, date := range dates { |
| + key, err := usage.InstanceDayKey(box, date, sqid, app) |
| + if err != nil { |
| + return nil, fmt.Errorf("console: instance usage: %s/%s/%s/%s: %w", box, date, sqid, app, err) |
| + } |
| + raw, _, err := rs.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, fmt.Errorf("console: instance usage: read %s: %w", key, err) |
| + } |
| + if int64(len(raw)) > usageDayReadCap { |
| + return nil, fmt.Errorf("console: instance usage: %s: %w", key, errUsageDayTooLarge) |
| + } |
| + day, err := usage.DecodeInstanceDay(key, raw) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for host, c := range day.Instances { |
| + cur := sums[host] |
| + cur.Add(c) |
| + sums[host] = cur |
| + } |
| + } |
| + } |
| + return sums, nil |
| } |
diff --git a/internal/console/apiusage_test.go b/internal/console/apiusage_test.go| new file mode 100644 |
| index 000000000..e06f47517 |
| --- /dev/null |
| +++ b/internal/console/apiusage_test.go |
| @@ -0,0 +1,616 @@ |
| +package console |
| + |
| +// The usage read (instance usage design §8): one app's per-instance counts |
| +// for a UTC month, behind the instance gate and the hostname history, from |
| +// this console's own store, memoised for a minute per account, app and |
| +// month. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// usageHookStore records every Get and fails the keys in fail. |
| +type usageHookStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + gets []string |
| + fail map[string]error |
| + onGet func(key string) |
| +} |
| + |
| +func (s *usageHookStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.mu.Lock() |
| + s.gets = append(s.gets, key) |
| + err := s.fail[key] |
| + hook := s.onGet |
| + s.mu.Unlock() |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + if hook != nil { |
| + hook(key) |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func (s *usageHookStore) setFail(key string, err error) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.fail == nil { |
| + s.fail = map[string]error{} |
| + } |
| + if err == nil { |
| + delete(s.fail, key) |
| + return |
| + } |
| + s.fail[key] = err |
| +} |
| + |
| +func (s *usageHookStore) got() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return slices.Clone(s.gets) |
| +} |
| + |
| +// usageEnv is a console with the switch on, the history held verified |
| +// active at usageAt1, @from at 1 January 2027, a fake clock at usageT0, |
| +// and a usage credential for the fixture account's app kass. |
| +type usageEnv struct { |
| + fx *consoleFixture |
| + hook *usageHookStore |
| + tok string |
| + mu sync.Mutex |
| + now time.Time |
| +} |
| + |
| +func newUsageEnv(t *testing.T) *usageEnv { |
| + return newUsageEnvWith(t, nil) |
| +} |
| + |
| +// newUsageEnvWith is newUsageEnv with wrap around the store, inside the |
| +// hook. |
| +func newUsageEnvWith(t *testing.T, wrap func(release.Store) release.Store) *usageEnv { |
| + t.Helper() |
| + e := &usageEnv{hook: &usageHookStore{}, now: usageT0} |
| + e.fx = newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, |
| + Tweak: func(c *Config) { c.InstanceUsage = true }, |
| + WrapReleases: func(st release.Store) release.Store { |
| + if wrap != nil { |
| + st = wrap(st) |
| + } |
| + e.hook.Store = st |
| + return e.hook |
| + }}) |
| + e.fx.srv.usageNow = e.clock |
| + holdHosts(e.fx.srv, activeAt(usageAt1), true) |
| + seedUsageFrom(t, e.fx.rel, "2027-01-01", usageAt1) |
| + e.tok = serviceToken(t, e.fx.st, OpsAccountID, "meter", "kass", svcrole.Usage) |
| + return e |
| +} |
| + |
| +func (e *usageEnv) clock() time.Time { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + return e.now |
| +} |
| + |
| +func (e *usageEnv) advance(d time.Duration) { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + e.now = e.now.Add(d) |
| +} |
| + |
| +// get asks for kass's usage for month ("" for none) with the usage |
| +// credential. |
| +func (e *usageEnv) get(t *testing.T, month string) (int, string, http.Header) { |
| + t.Helper() |
| + return e.getAs(t, e.fx.sqid, "kass", month, e.tok) |
| +} |
| + |
| +func (e *usageEnv) getAs(t *testing.T, sqid, app, month, tok string) (int, string, http.Header) { |
| + t.Helper() |
| + u := e.fx.ts.URL + "/api/cli/apps/" + sqid + "/" + app + "/usage" |
| + if month != "" { |
| + u += "?month=" + month |
| + } |
| + req, err := http.NewRequest(http.MethodGet, u, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+tok) |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + body, err := io.ReadAll(res.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return res.StatusCode, string(body), res.Header |
| +} |
| + |
| +func (e *usageEnv) okResponse(t *testing.T, month string) usageResponse { |
| + t.Helper() |
| + status, body, _ := e.get(t, month) |
| + if status != http.StatusOK { |
| + t.Fatalf("usage %q = %d %s, want 200", month, status, body) |
| + } |
| + var out usageResponse |
| + if err := json.Unmarshal([]byte(body), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + return out |
| +} |
| + |
| +// putDay writes one app's day object on one box. |
| +func putDay(t *testing.T, st release.Store, box, date, acct, app string, counts map[string]usage.InstanceCount) { |
| + t.Helper() |
| + key, err := usage.InstanceDayKey(box, date, acct, app) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + d := usage.InstanceDay{V: 1, Box: box, Date: date, Account: acct, App: app, Applied: map[string]string{}, Instances: counts} |
| + raw, err := json.Marshal(d) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putRawKey(t, st, key, raw) |
| +} |
| + |
| +func putRawKey(t *testing.T, st release.Store, key string, raw []byte) { |
| + t.Helper() |
| + _, etag, err := st.Get(context.Background(), key) |
| + if err != nil { |
| + etag = "" |
| + } |
| + if _, err := st.Put(context.Background(), key, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func dayKey(t *testing.T, box, date, acct, app string) string { |
| + t.Helper() |
| + key, err := usage.InstanceDayKey(box, date, acct, app) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return key |
| +} |
| + |
| +func bytesOut(n int64) map[string]usage.InstanceCount { |
| + return map[string]usage.InstanceCount{"a.example.com": {BytesOut: n, Requests: 1}} |
| +} |
| + |
| +func usageJob(t *testing.T, srv *Server) JobStatus { |
| + t.Helper() |
| + for _, j := range srv.jobs.Snapshot() { |
| + if j.Name == "InstanceUsageRead" { |
| + return j |
| + } |
| + } |
| + t.Fatal("InstanceUsageRead is not on the jobs registry") |
| + return JobStatus{} |
| +} |
| + |
| +// TestUsageSumsBoxesAndDates: two boxes, three dates; a deleted |
| +// instance's host is still listed, "" is unattributed, total is both, the |
| +// instances sorted by host. |
| +func TestUsageSumsBoxesAndDates(t *testing.T) { |
| + e := newUsageEnv(t) |
| + s := e.fx.sqid |
| + putDay(t, e.fx.rel, "b1", "2027-01-18", s, "kass", map[string]usage.InstanceCount{ |
| + "zeta.example.com": {BytesOut: 100, Requests: 2, HopBytesOut: 40, HopRequests: 1}, |
| + "alpha.example.com": {BytesOut: 10, Requests: 1}, |
| + "": {BytesOut: 7, Requests: 1}, |
| + }) |
| + putDay(t, e.fx.rel, "b2", "2027-01-19", s, "kass", map[string]usage.InstanceCount{ |
| + "zeta.example.com": {BytesOut: 5, Requests: 1}, |
| + "gone.example.com": {BytesOut: 3, Requests: 3}, // its instance was deleted |
| + }) |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", map[string]usage.InstanceCount{ |
| + "": {BytesOut: 1, Requests: 1}, |
| + "alpha.example.com": {BytesOut: 2, Requests: 1}, |
| + }) |
| + // Another app's object on the same box and date is not this app's. |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", s, "other", bytesOut(1000)) |
| + |
| + out := e.okResponse(t, "2027-01") |
| + want := usageResponse{ |
| + App: "kass", Month: "2027-01", From: "2027-01-01T00:00:00Z", To: "2027-02-01T00:00:00Z", |
| + Instances: []usageInstance{ |
| + {Host: "alpha.example.com", BytesOut: 12, Requests: 2}, |
| + {Host: "gone.example.com", BytesOut: 3, Requests: 3}, |
| + {Host: "zeta.example.com", BytesOut: 105, Requests: 3, HopBytesOut: 40, HopRequests: 1}, |
| + }, |
| + Unattributed: usageTotals{BytesOut: 8, Requests: 2}, |
| + Total: usageTotals{BytesOut: 128, Requests: 10}, |
| + ReadAt: "2027-01-20T12:00:00Z", |
| + } |
| + if fmt.Sprintf("%+v", out) != fmt.Sprintf("%+v", want) { |
| + t.Fatalf("usage =\n %+v\nwant\n %+v", out, want) |
| + } |
| + // No month is the current one. |
| + if out := e.okResponse(t, ""); out.Month != "2027-01" || out.Total != want.Total { |
| + t.Fatalf("no month = %+v, want the current month's answer", out) |
| + } |
| + // An app with nothing counted is an empty list, not null. |
| + _, body, _ := e.getAs(t, e.fx.sqid, "kass", "2027-01", e.tok) |
| + if !strings.Contains(body, `"instances":[`) { |
| + t.Fatalf("body = %s", body) |
| + } |
| +} |
| + |
| +// TestUsageEmptyIsAnEmptyList: no objects at all is 200 with an empty |
| +// instances list and zero totals. |
| +func TestUsageEmptyIsAnEmptyList(t *testing.T) { |
| + e := newUsageEnv(t) |
| + status, body, _ := e.get(t, "2027-01") |
| + if status != http.StatusOK || !strings.Contains(body, `"instances":[]`) || !strings.Contains(body, `"total":{"bytes_out":0,"requests":0}`) { |
| + t.Fatalf("usage = %d %s, want 200 with no instances", status, body) |
| + } |
| +} |
| + |
| +// TestUsageMonthBounds (Review Focus 3): malformed and future months are |
| +// 400, a month before From is 409 naming From's month, From's month is |
| +// 200, and the current month reads no date after today. |
| +func TestUsageMonthBounds(t *testing.T) { |
| + e := newUsageEnv(t) |
| + putDay(t, e.fx.rel, "b1", "2027-01-03", e.fx.sqid, "kass", bytesOut(9)) |
| + for _, m := range []string{"2027-1", "2027-13", "27-01", "2027-01-05", "January", "2027-00", "+2027-01", "2027-01%20"} { |
| + status, body, _ := e.get(t, m) |
| + if status != http.StatusBadRequest || jsonField(t, body, "error") != msgUsageMonthMalformed { |
| + t.Errorf("month %q = %d %s, want 400 %q", m, status, body, msgUsageMonthMalformed) |
| + } |
| + } |
| + status, body, _ := e.get(t, "2027-02") |
| + if want := "month: 2027-02 has not started yet"; status != http.StatusBadRequest || jsonField(t, body, "error") != want { |
| + t.Errorf("future month = %d %s, want 400 %q", status, body, want) |
| + } |
| + status, body, _ = e.get(t, "2026-12") |
| + if want := "Counting by instance starts on 1 January 2027. Ask for 2027-01 or later."; status != http.StatusConflict || |
| + jsonField(t, body, "error") != want || jsonField(t, body, "first_month") != "2027-01" { |
| + t.Errorf("before From = %d %s, want 409 %q naming 2027-01", status, body, want) |
| + } |
| + before := len(e.hook.got()) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 9 { |
| + t.Fatalf("From's month = %+v, want 9 bytes", out) |
| + } |
| + sawToday := false |
| + for _, k := range e.hook.got()[before:] { |
| + _, date, _, _, ok := usage.ParseInstanceDayKey(k) |
| + if !ok { |
| + continue |
| + } |
| + if date > "2027-01-20" { |
| + t.Errorf("read %s, a date after today", k) |
| + } |
| + sawToday = sawToday || date == "2027-01-20" |
| + } |
| + if !sawToday { |
| + t.Error("today's object was not read") |
| + } |
| +} |
| + |
| +// TestUsagePreFromObjectsIgnored: objects dated before From on the same |
| +// boxes are never counted. |
| +func TestUsagePreFromObjectsIgnored(t *testing.T) { |
| + e := newUsageEnv(t) |
| + putDay(t, e.fx.rel, "b1", "2026-12-31", e.fx.sqid, "kass", bytesOut(500)) |
| + putDay(t, e.fx.rel, "b1", "2027-01-01", e.fx.sqid, "kass", bytesOut(5)) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 5 { |
| + t.Fatalf("total = %+v, want only January's 5 bytes", out.Total) |
| + } |
| + for _, k := range e.hook.got() { |
| + if strings.Contains(k, "/2026-12-") { |
| + t.Errorf("read %s, before From", k) |
| + } |
| + } |
| +} |
| + |
| +// TestUsageMemoKeyedByAccount: the same app name in two accounts gives two |
| +// answers within the memo's minute. |
| +func TestUsageMemoKeyedByAccount(t *testing.T) { |
| + e := newUsageEnv(t) |
| + acct := planAccount(t, e.fx, 501) |
| + if _, err := e.fx.st.CreateAppIn(acct.ID, "kass", "paul@example.test", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + tok2 := serviceToken(t, e.fx.st, acct.ID, "meter2", "kass", svcrole.Usage) |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", e.fx.sqid, "kass", bytesOut(11)) |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", acct.Sqid, "kass", bytesOut(22)) |
| + for _, c := range []struct { |
| + sqid, tok string |
| + want int64 |
| + }{{e.fx.sqid, e.tok, 11}, {acct.Sqid, tok2, 22}, {e.fx.sqid, e.tok, 11}} { |
| + status, body, _ := e.getAs(t, c.sqid, "kass", "2027-01", c.tok) |
| + var out usageResponse |
| + if status != http.StatusOK || json.Unmarshal([]byte(body), &out) != nil || out.Total.BytesOut != c.want { |
| + t.Fatalf("account %s = %d %s, want %d bytes", c.sqid, status, body, c.want) |
| + } |
| + } |
| + // The other account's credential cannot read the first's. |
| + if status, body, _ := e.getAs(t, e.fx.sqid, "kass", "2027-01", tok2); status != http.StatusNotFound { |
| + t.Fatalf("account 2's credential at account 1 = %d %s, want 404", status, body) |
| + } |
| +} |
| + |
| +// TestUsagePendingAndBreakOnMemoHit: after a 200, pending is 503 and a |
| +// break is 409; no memo answer leaks past either. |
| +func TestUsagePendingAndBreakOnMemoHit(t *testing.T) { |
| + e := newUsageEnv(t) |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", e.fx.sqid, "kass", bytesOut(11)) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 11 { |
| + t.Fatalf("first answer = %+v", out) |
| + } |
| + for _, c := range []struct { |
| + name string |
| + mode string |
| + verified bool |
| + status int |
| + msg string |
| + }{ |
| + {"unverified", "active", false, http.StatusServiceUnavailable, msgUsagePending}, |
| + {"unread", "", false, http.StatusServiceUnavailable, msgUsagePending}, |
| + {"invalidated", "invalidated", true, http.StatusConflict, msgUsageNotActive}, |
| + {"incomplete", "incomplete", true, http.StatusConflict, msgUsageNotActive}, |
| + } { |
| + st := activeAt(usageAt1) |
| + st.Mode = c.mode |
| + holdHosts(e.fx.srv, st, c.verified) |
| + status, body, hdr := e.get(t, "2027-01") |
| + if status != c.status || jsonField(t, body, "error") != c.msg { |
| + t.Errorf("%s: = %d %s, want %d %q", c.name, status, body, c.status, c.msg) |
| + } |
| + if c.status == http.StatusServiceUnavailable && hdr.Get("Retry-After") != "60" { |
| + t.Errorf("%s: Retry-After = %q, want 60", c.name, hdr.Get("Retry-After")) |
| + } |
| + } |
| + // A restart reading active with another At: the memo's January answer |
| + // is not given, since January is now before From. |
| + holdHosts(e.fx.srv, activeAt(usageAt2), true) |
| + if status, body, _ := e.get(t, "2027-01"); status != http.StatusConflict || jsonField(t, body, "first_month") != "2027-02" { |
| + t.Errorf("after a break = %d %s, want 409 naming 2027-02", status, body) |
| + } |
| +} |
| + |
| +// TestRequestJobsAreDeclared: InstanceUsageRead is on the jobs registry, |
| +// Not run yet, before any call, with its label; with the switch off it is |
| +// not on the page. |
| +func TestRequestJobsAreDeclared(t *testing.T) { |
| + e := newUsageEnv(t) |
| + if j := usageJob(t, e.fx.srv); j.State != JobNotRun || j.Runs != 0 { |
| + t.Fatalf("before any call: %+v, want Not run yet", j) |
| + } |
| + if got := jobLabels["InstanceUsageRead"]; got != "Instance usage reads" { |
| + t.Fatalf("label = %q", got) |
| + } |
| + rows := opJobRows(e.fx.srv.jobs.Snapshot()) |
| + if !slices.ContainsFunc(rows, func(r opJobRow) bool { return r.Label == "Instance usage reads" && r.Status.Label == jobWordNotRun }) { |
| + t.Fatalf("jobs page rows = %+v, want Instance usage reads, Not run yet", rows) |
| + } |
| + off := usageFixture(t, false) |
| + for _, j := range off.srv.jobs.Snapshot() { |
| + if j.Name == "InstanceUsageRead" { |
| + t.Fatalf("switch off: %+v is on the jobs page", j) |
| + } |
| + } |
| +} |
| + |
| +// TestUsageReadFaults: an object that exists but cannot be read, parsed, |
| +// fails its key check or is over the read cap makes the answer a 503 with |
| +// Retry-After: 60, and the job's run Failed with that error; a clean read |
| +// after sets it back to OK. |
| +func TestUsageReadFaults(t *testing.T) { |
| + e := newUsageEnv(t) |
| + s := e.fx.sqid |
| + key := dayKey(t, "b1", "2027-01-20", s, "kass") |
| + putDay(t, e.fx.rel, "b1", "2027-01-19", s, "kass", bytesOut(3)) |
| + old := usageDayReadCap |
| + t.Cleanup(func() { usageDayReadCap = old }) |
| + for _, c := range []struct { |
| + name string |
| + setup func() |
| + want string |
| + }{ |
| + {"read error", func() { |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", bytesOut(1)) |
| + e.hook.setFail(key, errors.New("store went away")) |
| + }, "store went away"}, |
| + {"bad JSON", func() { putRawKey(t, e.fx.rel, key, []byte("{not json")) }, "parse"}, |
| + {"key mismatch", func() { |
| + raw, _ := json.Marshal(usage.InstanceDay{V: 1, Box: "b2", Date: "2027-01-20", Account: s, App: "kass"}) |
| + putRawKey(t, e.fx.rel, key, raw) |
| + }, usage.ErrInstanceDayMismatch.Error()}, |
| + {"over the cap", func() { |
| + usageDayReadCap = 64 |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", map[string]usage.InstanceCount{strings.Repeat("h", 80) + ".example.com": {BytesOut: 1}}) |
| + }, errUsageDayTooLarge.Error()}, |
| + } { |
| + c.setup() |
| + e.advance(2 * time.Minute) // past the memo |
| + status, body, hdr := e.get(t, "2027-01") |
| + if status != http.StatusServiceUnavailable || jsonField(t, body, "error") != msgUsageUnreadable || hdr.Get("Retry-After") != "60" { |
| + t.Errorf("%s: = %d %s (Retry-After %q), want 503 %q", c.name, status, body, hdr.Get("Retry-After"), msgUsageUnreadable) |
| + } |
| + if j := usageJob(t, e.fx.srv); j.State != JobFailed || !strings.Contains(j.Err, c.want) { |
| + t.Errorf("%s: job = %+v, want Failed with %q", c.name, j, c.want) |
| + } |
| + // Repaired: a clean read is OK again. |
| + e.hook.setFail(key, nil) |
| + usageDayReadCap = old |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", bytesOut(1)) |
| + e.advance(2 * time.Minute) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 4 { |
| + t.Errorf("%s repaired: total = %+v, want 4 bytes", c.name, out.Total) |
| + } |
| + if j := usageJob(t, e.fx.srv); j.State != JobOK { |
| + t.Errorf("%s repaired: job = %+v, want OK", c.name, j) |
| + } |
| + } |
| +} |
| + |
| +// TestUsageCap: 10,000 instances with traffic is an answer; 10,001 is 409. |
| +func TestUsageCap(t *testing.T) { |
| + e := newUsageEnv(t) |
| + hosts := map[string]usage.InstanceCount{} |
| + for i := range usageInstanceCap { |
| + hosts[fmt.Sprintf("i%05d.example.com", i)] = usage.InstanceCount{BytesOut: 1, Requests: 1} |
| + } |
| + hosts[""] = usage.InstanceCount{BytesOut: 1, Requests: 1} // unattributed is not an instance |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", e.fx.sqid, "kass", hosts) |
| + if out := e.okResponse(t, "2027-01"); len(out.Instances) != usageInstanceCap { |
| + t.Fatalf("10,000 instances: got %d", len(out.Instances)) |
| + } |
| + putDay(t, e.fx.rel, "b2", "2027-01-20", e.fx.sqid, "kass", map[string]usage.InstanceCount{"one-more.example.com": {BytesOut: 1}}) |
| + e.advance(2 * time.Minute) |
| + status, body, _ := e.get(t, "2027-01") |
| + if status != http.StatusConflict || jsonField(t, body, "error") != msgUsageOverCap { |
| + t.Fatalf("10,001 instances = %d %.200s, want 409 %q", status, body, msgUsageOverCap) |
| + } |
| +} |
| + |
| +// TestUsageOtherAppCredential: a usage credential for kass asking for |
| +// another app of the same account meets the gate's 404. |
| +func TestUsageOtherAppCredential(t *testing.T) { |
| + e := newUsageEnv(t) |
| + if _, err := e.fx.st.CreateAppIn(OpsAccountID, "other", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + putDay(t, e.fx.rel, "b1", "2027-01-20", e.fx.sqid, "other", bytesOut(7)) |
| + if status, body, _ := e.getAs(t, e.fx.sqid, "other", "2027-01", e.tok); status != http.StatusNotFound { |
| + t.Fatalf("kass's credential at other's usage = %d %s, want 404", status, body) |
| + } |
| +} |
| + |
| +// TestUsageLateWriteAfterSettle (Review Focus 4): a settled date is read, |
| +// then rewritten with more bytes. The answer stays until the cache entry |
| +// is usageDayMaxAge old, then is the new total, never the sum of both. |
| +func TestUsageLateWriteAfterSettle(t *testing.T) { |
| + e := newUsageEnv(t) |
| + putDay(t, e.fx.rel, "b1", "2027-01-05", e.fx.sqid, "kass", bytesOut(100)) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 100 { |
| + t.Fatalf("first read = %+v", out.Total) |
| + } |
| + putDay(t, e.fx.rel, "b1", "2027-01-05", e.fx.sqid, "kass", bytesOut(250)) |
| + e.advance(2 * time.Minute) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 100 { |
| + t.Fatalf("past the memo, inside the cache = %+v, want 100", out.Total) |
| + } |
| + e.advance(usageDayMaxAge - 2*time.Minute - time.Second) |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 100 { |
| + t.Fatalf("a second before the cache entry ages out = %+v, want 100", out.Total) |
| + } |
| + e.advance(time.Minute) // the cache entry is past usageDayMaxAge, and the memo's minute |
| + if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 250 { |
| + t.Fatalf("after the cache entry aged out = %+v, want 250", out.Total) |
| + } |
| +} |
| + |
| +// TestUsagePrefetchesEveryKey: the dry pass accepts every per-key body, so |
| +// the real reads run concurrently; a real body naming another box is still |
| +// refused. |
| +func TestUsagePrefetchesEveryKey(t *testing.T) { |
| + e := newUsageEnv(t) |
| + s := e.fx.sqid |
| + dates := []string{"2027-01-18", "2027-01-19", "2027-01-20"} |
| + for _, box := range []string{"b1", "b2"} { |
| + for _, d := range dates { |
| + putDay(t, e.fx.rel, box, d, s, "kass", bytesOut(1)) |
| + } |
| + } |
| + var ( |
| + mu sync.Mutex |
| + inFlight int |
| + most int |
| + allIn = make(chan struct{}) |
| + allClosed bool |
| + ) |
| + e.hook.mu.Lock() |
| + e.hook.onGet = func(key string) { |
| + if _, _, _, _, ok := usage.ParseInstanceDayKey(key); !ok { |
| + return |
| + } |
| + mu.Lock() |
| + inFlight++ |
| + most = max(most, inFlight) |
| + if inFlight == 6 && !allClosed { |
| + allClosed = true |
| + close(allIn) |
| + } |
| + mu.Unlock() |
| + select { |
| + case <-allIn: |
| + case <-time.After(2 * time.Second): // sequential reads: give up waiting |
| + } |
| + mu.Lock() |
| + inFlight-- |
| + mu.Unlock() |
| + } |
| + e.hook.mu.Unlock() |
| + sums, stats, err := e.fx.srv.readInstanceUsage(context.Background(), s, "kass", dates, usageT0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if most != 6 { |
| + t.Errorf("most reads in flight = %d, want all 6 at once", most) |
| + } |
| + if stats.Peak == 0 { |
| + t.Errorf("prefetch stats = %+v, want the bodies fetched ahead", stats) |
| + } |
| + if got := sums["a.example.com"].BytesOut; got != 6 { |
| + t.Errorf("sum = %d, want 6", got) |
| + } |
| + |
| + e.hook.mu.Lock() |
| + e.hook.onGet = nil |
| + e.hook.mu.Unlock() |
| + raw, _ := json.Marshal(usage.InstanceDay{V: 1, Box: "b1", Date: "2027-01-19", Account: s, App: "kass"}) |
| + putRawKey(t, e.fx.rel, dayKey(t, "b2", "2027-01-19", s, "kass"), raw) |
| + if _, _, err := e.fx.srv.readInstanceUsage(context.Background(), s, "kass", dates, usageT0); !errors.Is(err, usage.ErrInstanceDayMismatch) { |
| + t.Fatalf("a body naming another box: err = %v, want ErrInstanceDayMismatch", err) |
| + } |
| +} |
| + |
| +// TestUsageDayDateKnowsInstances: an instance day key in the root family |
| +// is a usage day object (cached when settled, read under the cap); a fleet |
| +// prefix, @from and a malformed key are not. |
| +func TestUsageDayDateKnowsInstances(t *testing.T) { |
| + key := dayKey(t, "b1", "2027-01-05", "acct", "shop") |
| + if date, ok := usageDayDate(key); !ok || date != "2027-01-05" { |
| + t.Errorf("usageDayDate(%s) = %q %v", key, date, ok) |
| + } |
| + if usageDayLimit(key) != usageDayReadCap { |
| + t.Errorf("usageDayLimit(%s) = %d, want the read cap", key, usageDayLimit(key)) |
| + } |
| + // An app named like a date is still that app's object. |
| + if k := dayKey(t, "b1", "2027-01-05", "acct", "2027-01-06"); func() bool { d, ok := usageDayDate(k); return !ok || d != "2027-01-05" }() { |
| + t.Errorf("usageDayDate(%s) is wrong", k) |
| + } |
| + for _, k := range []string{ |
| + "fleets/f1/" + key, |
| + usage.InstanceFromKey, |
| + usage.InstancesPrefix + "b1/2027-01-05/acct.json", |
| + usage.InstancesPrefix + "b1/2027-13-05/acct/shop.json", |
| + usage.InstancesPrefix + "b1/2027-01-05/acct/shop/x.json", |
| + usage.InstancesPrefix + "../2027-01-05/acct/shop.json", |
| + } { |
| + if d, ok := usageDayDate(k); ok { |
| + t.Errorf("usageDayDate(%s) = %q, want not a day object", k, d) |
| + } |
| + } |
| +} |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index 8c1385ebf..360816713 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -45,6 +45,12 @@ func (s *Server) registerClaimWorkers() { |
| } |
| s.claimWorkers[name] = func(ctx context.Context) { h(context.WithValue(ctx, claimEntryKey{}, e)) } |
| } |
| + // The request jobs are Not run yet until a request runs them. |
| + for _, name := range requestJobs { |
| + if requestJobOn(s.cfg, name) { |
| + s.jobs.declare(name) |
| + } |
| + } |
| } |
| // publishMovesConsoleWorker is PublishMovesConsole as a recorded worker. The |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index 46889c6b6..6f942e0b7 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -327,6 +327,25 @@ var jobLabels = map[string]string{ |
| "FleetRelabel": "Fleet box placement", |
| "ManagedFleets": "Managed fleet provisioning", // COPY |
| "LinkSync": copyLinkJobLabel, |
| + // A request job (requestJobs). |
| + "InstanceUsageRead": "Instance usage reads", |
| +} |
| + |
| +// requestJobs are the jobs a door runs per request rather than a worker |
| +// per tick: a read whose fault is filed as the job's failed run, so the |
| +// operator pages show it (instance usage design §8). |
| +// TestEveryWorkerReportsItsRuns holds .jobs.Run names to the claim |
| +// workers and these. |
| +var requestJobs = []string{"InstanceUsageRead"} |
| + |
| +// requestJobOn reports whether name's door is served on this console: |
| +// a request job is declared only where it can run. |
| +func requestJobOn(c Config, name string) bool { |
| + switch name { |
| + case "InstanceUsageRead": |
| + return c.InstanceUsage |
| + } |
| + return false |
| } |
| // The job status words (OPS-80 to OPS-82). |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index 4261639c5..22a9f538d 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -423,8 +423,9 @@ func consoleSourceFiles(t *testing.T) (*token.FileSet, []*ast.File) { |
| } |
| // TestEveryWorkerReportsItsRuns: every claim worker wraps its pass in |
| -// s.jobs.Run under its own name, and every name has a label. A worker that |
| -// does not report, or reports under a typo, fails here. |
| +// s.jobs.Run under its own name, every other .jobs.Run name is a request |
| +// job (requestJobs), and every name has a label. A worker that does not |
| +// report, or reports under a typo, fails here. |
| func TestEveryWorkerReportsItsRuns(t *testing.T) { |
| _, files := consoleSourceFiles(t) |
| reported := map[string]bool{} |
| @@ -462,16 +463,31 @@ func TestEveryWorkerReportsItsRuns(t *testing.T) { |
| t.Errorf("worker %s has no jobLabels entry", name) |
| } |
| } |
| + // Every worker reports its runs. |
| + for _, name := range workers { |
| + if !reported[name] { |
| + t.Errorf("worker %s never reports through .jobs.Run", name) |
| + } |
| + } |
| + // The request-driven jobs (a door's read filed as a job) report too, |
| + // and are labelled. |
| + jobs := slices.Clone(workers) |
| + for _, name := range requestJobs { |
| + jobs = append(jobs, name) |
| + if _, ok := jobLabels[name]; !ok { |
| + t.Errorf("request job %s has no jobLabels entry", name) |
| + } |
| + } |
| for name := range reported { |
| got = append(got, name) |
| } |
| - sort.Strings(workers) |
| + sort.Strings(jobs) |
| sort.Strings(got) |
| - if !slices.Equal(got, workers) { |
| - t.Errorf("jobs reported through .jobs.Run:\n %q\nclaim workers:\n %q", got, workers) |
| + if !slices.Equal(got, jobs) { |
| + t.Errorf("jobs reported through .jobs.Run:\n %q\nclaim workers and request jobs:\n %q", got, jobs) |
| } |
| - if len(jobLabels) != len(workers) { |
| - t.Errorf("jobLabels has %d entries for %d workers", len(jobLabels), len(workers)) |
| + if len(jobLabels) != len(jobs) { |
| + t.Errorf("jobLabels has %d entries for %d workers and request jobs", len(jobLabels), len(jobs)) |
| } |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 081dc6b1d..10104fa7b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1113,6 +1113,9 @@ type Server struct { |
| // hosts is the hostname history's mode, read once (hostsused.go). |
| hosts hostsHistory |
| + // The instance usage read's clock, attribution start and memo |
| + // (usagefrom.go, apiusage.go). |
| + instanceUsageState |
| // lapseBeforeConverge, when set (tests only), runs inside the account's |
| // grace pass just before the lapse converges (plans 4d, Astra finding 1). |
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go| index 0f8693741..faf30de48 100644 |
| --- a/internal/console/usagedays.go |
| +++ b/internal/console/usagedays.go |
| @@ -100,9 +100,16 @@ type usageDayCache struct { |
| // usageDayDate is the date a usage day object's key names, for the five |
| // families the economics sweep reads: metrics.DayKey and usage.EdgeDayKey |
| // under the platform root or a fleet's prefix, usage.StorageDayKey and |
| -// usage.CensusDayKey. Any other key is not a day object (ok false), and is |
| -// read through untouched. |
| +// usage.CensusDayKey; for an app's analytics day file; and for the |
| +// instance usage family under the root only (usage.InstanceDayKey, which |
| +// the usage read reads). Any other key is not a day object (ok false), and |
| +// is read through untouched. |
| func usageDayDate(key string) (date string, ok bool) { |
| + if strings.HasPrefix(key, usage.InstancesPrefix) { |
| + // Its last segment is the app, not the date. |
| + _, date, _, _, ok := usage.ParseInstanceDayKey(key) |
| + return date, ok |
| + } |
| rest, ok := strings.CutSuffix(key, ".json") |
| if !ok { |
| return "", false |
diff --git a/internal/console/usagefrom.go b/internal/console/usagefrom.go| new file mode 100644 |
| index 000000000..66d45847a |
| --- /dev/null |
| +++ b/internal/console/usagefrom.go |
| @@ -0,0 +1,203 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "os" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// The attribution start, usage/instances/@from.json (instance usage design |
| +// §4). A host is never reused only from the hostname history's activation |
| +// on, so the console records the first whole UTC month it can answer, and |
| +// the activation that month rests on. It is written the first time this |
| +// console holds the history verified active with the switch on, as the |
| +// first day of the next month, and moved only on a real break (the history |
| +// held active with another At), only forward. A check that is pending, or |
| +// a start-up read that failed and is retrying, is not a break: it answers |
| +// 503 and touches nothing. |
| + |
| +// usageFromEvery is how often RunUsageFrom checks until @from is held. |
| +const usageFromEvery = time.Minute |
| + |
| +// usageFromAttempts bounds the re-reads after lost CAS races in one check. |
| +const usageFromAttempts = 4 |
| + |
| +// usageFromVerdict is one check's answer: ok (Status 0) with the From held, |
| +// or the route's refusal with its copy. |
| +type usageFromVerdict struct { |
| + From usage.InstanceFrom |
| + Status int // 0 ok; 503 pending; 409 not active, or not started |
| + Msg string // Task 0 copy |
| +} |
| + |
| +// instanceUsageState is the server's instance usage memory: its clock |
| +// seam, the @from it holds, and the route's memo. |
| +type instanceUsageState struct { |
| + // usageNow is the usage paths' clock seam: nil means time.Now. Tests |
| + // set it; nothing in production does. |
| + usageNow func() time.Time |
| + // usageFromMu serialises the checks, so one process writes @from once. |
| + usageFromMu sync.Mutex |
| + // usageFromHeld is the @from this process last read or wrote; nil |
| + // until then. |
| + usageFromHeld *usage.InstanceFrom |
| + usageMemo usageMemo |
| +} |
| + |
| +func (s *Server) usageClock() time.Time { |
| + if s.usageNow != nil { |
| + return s.usageNow() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// errUsageOff is the check's error on a console with the switch off: it |
| +// never writes @from there. |
| +var errUsageOff = errors.New("console: instance usage is switched off") |
| + |
| +// errUsageFromRaced is the check's error when @from kept changing under it. |
| +var errUsageFromRaced = errors.New("console: instance usage: the attribution start kept changing under the check") |
| + |
| +// firstOfNextMonth is the first day of the UTC month after now's. |
| +func firstOfNextMonth(now time.Time) string { |
| + now = now.UTC() |
| + return time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC).Format(time.DateOnly) |
| +} |
| + |
| +// usageFromCheck answers whether the route may answer, and from when, |
| +// from the held hostname history state alone (it never reads the history). |
| +// Not active (or a console with host claims, which never activates it) is |
| +// 409; unread or not yet verified is 503. Verified active, it holds the |
| +// @from whose activation is the held At, writing or moving it first when |
| +// needed. A store error is returned. |
| +func (s *Server) usageFromCheck(ctx context.Context, now time.Time) (usageFromVerdict, error) { |
| + if !s.cfg.InstanceUsage { |
| + return usageFromVerdict{}, errUsageOff |
| + } |
| + st, verified := s.hostsCached() |
| + switch { |
| + case s.cfg.HostClaim: |
| + return usageFromVerdict{Status: http.StatusConflict, Msg: msgUsageNotActive}, nil |
| + case st.Mode == "": |
| + // The start-up read failed and LoadHostsMode is retrying. |
| + return usageFromVerdict{Status: http.StatusServiceUnavailable, Msg: msgUsagePending}, nil |
| + case st.Mode != provision.HostsModeActive: |
| + return usageFromVerdict{Status: http.StatusConflict, Msg: msgUsageNotActive}, nil |
| + case !verified: |
| + return usageFromVerdict{Status: http.StatusServiceUnavailable, Msg: msgUsagePending}, nil |
| + } |
| + s.usageFromMu.Lock() |
| + defer s.usageFromMu.Unlock() |
| + if h := s.usageFromHeld; h != nil && h.Activation.Equal(st.At) { |
| + return usageFromVerdict{From: *h}, nil |
| + } |
| + if s.cfg.Releases == nil { |
| + return usageFromVerdict{}, errors.New("console: instance usage: no deployment store") |
| + } |
| + for range usageFromAttempts { |
| + f, err := s.settleUsageFrom(ctx, st.At, now) |
| + if errors.Is(err, release.ErrCASConflict) { |
| + continue // another console wrote it first: read what it wrote |
| + } |
| + if err != nil { |
| + return usageFromVerdict{}, err |
| + } |
| + s.usageFromHeld = &f |
| + return usageFromVerdict{From: f}, nil |
| + } |
| + return usageFromVerdict{}, errUsageFromRaced |
| +} |
| + |
| +// settleUsageFrom reads @from and makes it rest on the activation at: |
| +// absent, it is created as the next month; present with that activation, |
| +// it is kept; present with another (a break), From moves to the later of |
| +// its own and the next month. A lost race is release.ErrCASConflict. |
| +func (s *Server) settleUsageFrom(ctx context.Context, at, now time.Time) (usage.InstanceFrom, error) { |
| + raw, etag, err := s.cfg.Releases.Get(ctx, usage.InstanceFromKey) |
| + if errors.Is(err, os.ErrNotExist) { |
| + f := usage.InstanceFrom{From: firstOfNextMonth(now), Activation: at} |
| + return f, s.putUsageFrom(ctx, f, "") |
| + } |
| + if err != nil { |
| + return usage.InstanceFrom{}, fmt.Errorf("console: instance usage: read %s: %w", usage.InstanceFromKey, err) |
| + } |
| + old, err := decodeUsageFrom(raw) |
| + if err != nil { |
| + return usage.InstanceFrom{}, err |
| + } |
| + if old.Activation.Equal(at) { |
| + return old, nil |
| + } |
| + f := usage.InstanceFrom{From: max(old.From, firstOfNextMonth(now)), Activation: at} |
| + if err := s.putUsageFrom(ctx, f, etag); err != nil { |
| + return usage.InstanceFrom{}, err |
| + } |
| + log.Printf("console: instance usage: the hostname history was activated again (%s, was %s): counting by instance now starts on %s", |
| + at.UTC().Format(time.RFC3339), old.Activation.UTC().Format(time.RFC3339), f.From) |
| + return f, nil |
| +} |
| + |
| +// putUsageFrom writes f on ifMatch ("" is create-only). |
| +func (s *Server) putUsageFrom(ctx context.Context, f usage.InstanceFrom, ifMatch string) error { |
| + raw, err := json.Marshal(f) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := s.cfg.Releases.Put(ctx, usage.InstanceFromKey, raw, ifMatch); err != nil { |
| + return fmt.Errorf("console: instance usage: write %s: %w", usage.InstanceFromKey, err) |
| + } |
| + return nil |
| +} |
| + |
| +// decodeUsageFrom parses @from, whose From must be a month's first day. |
| +func decodeUsageFrom(raw []byte) (usage.InstanceFrom, error) { |
| + var f usage.InstanceFrom |
| + if err := json.Unmarshal(raw, &f); err != nil { |
| + return usage.InstanceFrom{}, fmt.Errorf("console: instance usage: parse %s: %w", usage.InstanceFromKey, err) |
| + } |
| + d, err := time.Parse(time.DateOnly, f.From) |
| + if err != nil || d.Day() != 1 { |
| + return usage.InstanceFrom{}, fmt.Errorf("console: instance usage: %s holds no month start (%q)", usage.InstanceFromKey, f.From) |
| + } |
| + return f, nil |
| +} |
| + |
| +// RunUsageFrom checks the attribution start at console start and every |
| +// minute after, until @from is held, then returns: so @from is written |
| +// once the history is verified active, whether or not anyone asks for |
| +// usage. Started from cmd/console only when the switch is on. |
| +func (s *Server) RunUsageFrom(ctx context.Context) { |
| + t := time.NewTicker(usageFromEvery) |
| + defer t.Stop() |
| + s.runUsageFrom(ctx, t.C) |
| +} |
| + |
| +// runUsageFrom is RunUsageFrom on tick (the test seam). |
| +func (s *Server) runUsageFrom(ctx context.Context, tick <-chan time.Time) { |
| + if !s.cfg.InstanceUsage || s.cfg.HostClaim { |
| + return // nothing to write: off, or a history that never activates |
| + } |
| + for { |
| + v, err := s.usageFromCheck(ctx, s.usageClock()) |
| + if err != nil { |
| + log.Printf("console: instance usage: check the attribution start: %v (checking again in a minute)", err) |
| + } else if v.Status == 0 { |
| + return |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-tick: |
| + } |
| + } |
| +} |
diff --git a/internal/console/usagefrom_test.go b/internal/console/usagefrom_test.go| new file mode 100644 |
| index 000000000..7cf5f7275 |
| --- /dev/null |
| +++ b/internal/console/usagefrom_test.go |
| @@ -0,0 +1,433 @@ |
| +package console |
| + |
| +// The attribution start, usage/instances/@from.json (instance usage design |
| +// §4): written once the hostname history is held verified active with the |
| +// switch on, never while the check is pending, and moved only forward, and |
| +// only on a real break. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// usageT0 is the tests' fake now: mid January 2027, UTC. |
| +var usageT0 = time.Date(2027, 1, 20, 12, 0, 0, 0, time.UTC) |
| + |
| +// The activations the tests hold. |
| +var ( |
| + usageAt1 = time.Date(2026, 12, 3, 9, 0, 0, 0, time.UTC) |
| + usageAt2 = time.Date(2027, 1, 18, 9, 0, 0, 0, time.UTC) |
| +) |
| + |
| +// holdHosts sets the process's held hostname history, as the hostsused |
| +// tests do (historyActive): the state and the start-up check's result. |
| +func holdHosts(srv *Server, st provision.HostsState, verified bool) { |
| + srv.hosts.mu.Lock() |
| + defer srv.hosts.mu.Unlock() |
| + srv.hosts.state = st |
| + srv.hosts.verified = verified |
| +} |
| + |
| +func activeAt(at time.Time) provision.HostsState { |
| + return provision.HostsState{Mode: provision.HostsModeActive, At: at} |
| +} |
| + |
| +// storeUsageFrom is @from as the store holds it, ok false when absent. |
| +func storeUsageFrom(t *testing.T, st release.Store) (usage.InstanceFrom, bool) { |
| + t.Helper() |
| + raw, _, err := st.Get(context.Background(), usage.InstanceFromKey) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return usage.InstanceFrom{}, false |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var f usage.InstanceFrom |
| + if err := json.Unmarshal(raw, &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f, true |
| +} |
| + |
| +// seedUsageFrom writes @from as an earlier console would have. |
| +func seedUsageFrom(t *testing.T, st release.Store, from string, at time.Time) { |
| + t.Helper() |
| + raw, err := json.Marshal(usage.InstanceFrom{From: from, Activation: at}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, etag, err := st.Get(context.Background(), usage.InstanceFromKey) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.Put(context.Background(), usage.InstanceFromKey, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// writeHostsMode writes the history's state to the store, as activation |
| +// (offline) would. |
| +func writeHostsMode(t *testing.T, st release.Store, hs provision.HostsState) { |
| + t.Helper() |
| + ctx := context.Background() |
| + _, etag, err := provision.ReadHostsState(ctx, st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := provision.WriteHostsState(ctx, st, hs, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func sameFrom(a, b usage.InstanceFrom) bool { |
| + return a.From == b.From && a.Activation.Equal(b.Activation) |
| +} |
| + |
| +func TestFirstOfNextMonth(t *testing.T) { |
| + for _, c := range []struct { |
| + now time.Time |
| + want string |
| + }{ |
| + {usageT0, "2027-02-01"}, |
| + {time.Date(2027, 12, 31, 23, 59, 59, 0, time.UTC), "2028-01-01"}, |
| + {time.Date(2027, 1, 31, 23, 30, 0, 0, time.FixedZone("x", -2*3600)), "2027-03-01"}, // 01:30 UTC on 1 February |
| + } { |
| + if got := firstOfNextMonth(c.now); got != c.want { |
| + t.Errorf("firstOfNextMonth(%s) = %s, want %s", c.now, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// TestUsageFromWrittenOnlyWhenActiveVerifiedOn: @from is written only when |
| +// the history is held active and verified with the switch on, as the next |
| +// month's first day; pending is 503 and not active is 409, touching |
| +// nothing. |
| +func TestUsageFromWrittenOnlyWhenActiveVerifiedOn(t *testing.T) { |
| + ctx := context.Background() |
| + fx := usageFixture(t, true) |
| + for _, c := range []struct { |
| + name string |
| + st provision.HostsState |
| + verified bool |
| + claim bool |
| + status int |
| + msg string |
| + }{ |
| + {"unread", provision.HostsState{}, false, false, http.StatusServiceUnavailable, msgUsagePending}, |
| + {"incomplete", provision.HostsState{Mode: provision.HostsModeIncomplete}, true, false, http.StatusConflict, msgUsageNotActive}, |
| + {"invalidated", provision.HostsState{Mode: provision.HostsModeInvalidated, At: usageAt1}, true, false, http.StatusConflict, msgUsageNotActive}, |
| + {"active, unverified", activeAt(usageAt1), false, false, http.StatusServiceUnavailable, msgUsagePending}, |
| + {"host claims", activeAt(usageAt1), true, true, http.StatusConflict, msgUsageNotActive}, |
| + } { |
| + holdHosts(fx.srv, c.st, c.verified) |
| + fx.srv.cfg.HostClaim = c.claim |
| + v, err := fx.srv.usageFromCheck(ctx, usageT0) |
| + fx.srv.cfg.HostClaim = false |
| + if err != nil || v.Status != c.status || v.Msg != c.msg { |
| + t.Errorf("%s: check = %+v %v, want %d %q", c.name, v, err, c.status, c.msg) |
| + } |
| + if f, ok := storeUsageFrom(t, fx.rel); ok { |
| + t.Fatalf("%s: @from written: %+v", c.name, f) |
| + } |
| + } |
| + |
| + holdHosts(fx.srv, activeAt(usageAt1), true) |
| + v, err := fx.srv.usageFromCheck(ctx, usageT0) |
| + want := usage.InstanceFrom{From: "2027-02-01", Activation: usageAt1} |
| + if err != nil || v.Status != 0 || !sameFrom(v.From, want) { |
| + t.Fatalf("active and verified: check = %+v %v, want ok %+v", v, err, want) |
| + } |
| + if f, ok := storeUsageFrom(t, fx.rel); !ok || !sameFrom(f, want) { |
| + t.Fatalf("@from = %+v %v, want %+v", f, ok, want) |
| + } |
| + |
| + // Switched off: nothing is written, whatever the history. |
| + off := usageFixture(t, false) |
| + holdHosts(off.srv, activeAt(usageAt1), true) |
| + if v, err := off.srv.usageFromCheck(ctx, usageT0); err == nil { |
| + t.Errorf("switch off: check = %+v, want an error", v) |
| + } |
| + if f, ok := storeUsageFrom(t, off.rel); ok { |
| + t.Fatalf("switch off: @from written: %+v", f) |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + off.srv.runUsageFrom(ctx, nil) |
| + close(done) |
| + }() |
| + <-done // a nil tick never fires: it returned at once |
| +} |
| + |
| +// TestUsageFromPendingKeepsExisting: a check pending, then verified, holds |
| +// the @from already there unchanged: a restart never costs a month. |
| +func TestUsageFromPendingKeepsExisting(t *testing.T) { |
| + ctx := context.Background() |
| + fx := usageFixture(t, true) |
| + seedUsageFrom(t, fx.rel, "2027-01-01", usageAt1) |
| + want := usage.InstanceFrom{From: "2027-01-01", Activation: usageAt1} |
| + |
| + holdHosts(fx.srv, activeAt(usageAt1), false) |
| + if v, err := fx.srv.usageFromCheck(ctx, usageT0); err != nil || v.Status != http.StatusServiceUnavailable { |
| + t.Fatalf("pending: check = %+v %v, want 503", v, err) |
| + } |
| + holdHosts(fx.srv, activeAt(usageAt1), true) |
| + v, err := fx.srv.usageFromCheck(ctx, usageT0) |
| + if err != nil || v.Status != 0 || !sameFrom(v.From, want) { |
| + t.Fatalf("verified: check = %+v %v, want ok %+v", v, err, want) |
| + } |
| + if f, _ := storeUsageFrom(t, fx.rel); !sameFrom(f, want) { |
| + t.Fatalf("@from = %+v, want it unchanged %+v", f, want) |
| + } |
| +} |
| + |
| +// TestUsageFromBreakMovesForward: a held state with another At moves From |
| +// to the month after now, never back. |
| +func TestUsageFromBreakMovesForward(t *testing.T) { |
| + ctx := context.Background() |
| + for _, c := range []struct { |
| + old, want string |
| + }{ |
| + {"2027-01-01", "2027-02-01"}, |
| + {"2027-06-01", "2027-06-01"}, |
| + } { |
| + fx := usageFixture(t, true) |
| + seedUsageFrom(t, fx.rel, c.old, usageAt1) |
| + holdHosts(fx.srv, activeAt(usageAt2), true) |
| + want := usage.InstanceFrom{From: c.want, Activation: usageAt2} |
| + v, err := fx.srv.usageFromCheck(ctx, usageT0) |
| + if err != nil || v.Status != 0 || !sameFrom(v.From, want) { |
| + t.Fatalf("old %s: check = %+v %v, want ok %+v", c.old, v, err, want) |
| + } |
| + if f, _ := storeUsageFrom(t, fx.rel); !sameFrom(f, want) { |
| + t.Fatalf("old %s: @from = %+v, want %+v", c.old, f, want) |
| + } |
| + } |
| +} |
| + |
| +// usageFromRaceStore holds every read of @from until two have read it, so |
| +// two consoles both find it absent and both try the create. |
| +type usageFromRaceStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + reads int |
| + both chan struct{} |
| + puts int |
| + putWins int |
| +} |
| + |
| +func (s *usageFromRaceStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + body, etag, err := s.Store.Get(ctx, key) |
| + if key == usage.InstanceFromKey { |
| + // Answer only once both have read, so neither writes before the |
| + // other has seen the store. |
| + s.mu.Lock() |
| + s.reads++ |
| + if s.reads == 2 { |
| + close(s.both) |
| + } |
| + s.mu.Unlock() |
| + select { |
| + case <-s.both: |
| + case <-ctx.Done(): |
| + return nil, "", ctx.Err() |
| + } |
| + } |
| + return body, etag, err |
| +} |
| + |
| +func (s *usageFromRaceStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + etag, err := s.Store.Put(ctx, key, body, ifMatch) |
| + if key == usage.InstanceFromKey { |
| + s.mu.Lock() |
| + s.puts++ |
| + if err == nil { |
| + s.putWins++ |
| + } |
| + s.mu.Unlock() |
| + } |
| + return etag, err |
| +} |
| + |
| +// TestUsageFromRacingCreate (Review Focus 5): two consoles racing the |
| +// create; one Put wins and both hold its body, even when the loser would |
| +// have written another From. |
| +func TestUsageFromRacingCreate(t *testing.T) { |
| + race := &usageFromRaceStore{both: make(chan struct{})} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, |
| + Tweak: func(c *Config) { c.InstanceUsage = true }, |
| + WrapReleases: func(st release.Store) release.Store { race.Store = st; return race }}) |
| + other, err := NewServer(fx.srv.cfg, fx.st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + holdHosts(fx.srv, activeAt(usageAt1), true) |
| + holdHosts(other, activeAt(usageAt1), true) |
| + |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + var wg sync.WaitGroup |
| + got := make([]usageFromVerdict, 2) |
| + errs := make([]error, 2) |
| + for i, c := range []struct { |
| + srv *Server |
| + now time.Time |
| + }{{fx.srv, usageT0}, {other, usageT0.AddDate(0, 1, 0)}} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + got[i], errs[i] = c.srv.usageFromCheck(ctx, c.now) |
| + }() |
| + } |
| + wg.Wait() |
| + for i := range got { |
| + if errs[i] != nil || got[i].Status != 0 { |
| + t.Fatalf("console %d: check = %+v %v", i, got[i], errs[i]) |
| + } |
| + } |
| + stored, ok := storeUsageFrom(t, fx.rel) |
| + if !ok || !sameFrom(got[0].From, stored) || !sameFrom(got[1].From, stored) { |
| + t.Fatalf("held %+v and %+v, stored %+v %v: want both to hold the stored body", got[0].From, got[1].From, stored, ok) |
| + } |
| + if race.puts != 2 || race.putWins != 1 { |
| + t.Fatalf("puts = %d, won = %d; want two creates, one winning", race.puts, race.putWins) |
| + } |
| +} |
| + |
| +// hostsReadFailStore fails the history's mode read while fail is set. |
| +type hostsReadFailStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + fail bool |
| +} |
| + |
| +func (s *hostsReadFailStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.mu.Lock() |
| + fail := s.fail && key == provision.HostsModeKey |
| + s.mu.Unlock() |
| + if fail { |
| + return nil, "", errors.New("hosts mode: store unreachable") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +// TestUsageFromUnreadIsPending: the start-up read fails (mode ""): the |
| +// route is 503 and @from untouched. The read then succeeds and the check |
| +// verifies: the existing @from is held unchanged. |
| +func TestUsageFromUnreadIsPending(t *testing.T) { |
| + ctx := context.Background() |
| + fs := &hostsReadFailStore{fail: true} |
| + e := newUsageEnvWith(t, func(st release.Store) release.Store { fs.Store = st; return fs }) |
| + writeHostsMode(t, e.fx.rel, activeAt(usageAt1)) |
| + e.fx.srv.hosts.reset() |
| + if _, err := e.fx.srv.hostsMode(ctx); err == nil { |
| + t.Fatal("the start-up read did not fail") |
| + } |
| + if st, _ := e.fx.srv.hostsCached(); st.Mode != "" { |
| + t.Fatalf("mode = %q, want unread", st.Mode) |
| + } |
| + status, body, hdr := e.get(t, "") |
| + if status != http.StatusServiceUnavailable || jsonField(t, body, "error") != msgUsagePending || hdr.Get("Retry-After") != "60" { |
| + t.Fatalf("route while unread = %d %s (Retry-After %q), want 503 %q", status, body, hdr.Get("Retry-After"), msgUsagePending) |
| + } |
| + want := usage.InstanceFrom{From: "2027-01-01", Activation: usageAt1} |
| + if f, _ := storeUsageFrom(t, e.fx.rel); !sameFrom(f, want) { |
| + t.Fatalf("@from = %+v, want untouched %+v", f, want) |
| + } |
| + |
| + fs.mu.Lock() |
| + fs.fail = false |
| + fs.mu.Unlock() |
| + if mode, err := e.fx.srv.hostsMode(ctx); err != nil || mode != provision.HostsModeActive { |
| + t.Fatalf("mode = %q %v, want active", mode, err) |
| + } |
| + e.fx.srv.hosts.mu.Lock() |
| + e.fx.srv.hosts.verified = true // the start-up check passed |
| + e.fx.srv.hosts.mu.Unlock() |
| + if status, body, _ := e.get(t, ""); status != http.StatusOK { |
| + t.Fatalf("route once verified = %d %s, want 200", status, body) |
| + } |
| + if f, _ := storeUsageFrom(t, e.fx.rel); !sameFrom(f, want) { |
| + t.Fatalf("@from = %+v, want unchanged %+v", f, want) |
| + } |
| +} |
| + |
| +// TestUsageFromSelfInvalidation: with @from held, the console invalidating |
| +// its own history makes the route 409; a restart reading active with a new |
| +// At, once verified, moves From to the month after now. |
| +func TestUsageFromSelfInvalidation(t *testing.T) { |
| + ctx := context.Background() |
| + e := newUsageEnv(t) |
| + writeHostsMode(t, e.fx.rel, activeAt(usageAt1)) |
| + e.fx.srv.hosts.reset() |
| + if _, err := e.fx.srv.hostsMode(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + holdHosts(e.fx.srv, activeAt(usageAt1), true) |
| + if status, body, _ := e.get(t, ""); status != http.StatusOK { |
| + t.Fatalf("route = %d %s, want 200", status, body) |
| + } |
| + |
| + if err := e.fx.srv.invalidateHosts(ctx, "a record the history does not cover"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, body, _ := e.get(t, ""); status != http.StatusConflict || jsonField(t, body, "error") != msgUsageNotActive { |
| + t.Fatalf("route after invalidation = %d %s, want 409 %q", status, body, msgUsageNotActive) |
| + } |
| + |
| + // Reactivated offline with a new At, then a restart. |
| + writeHostsMode(t, e.fx.rel, activeAt(usageAt2)) |
| + e.fx.srv.hosts.reset() |
| + if mode, err := e.fx.srv.hostsMode(ctx); err != nil || mode != provision.HostsModeActive { |
| + t.Fatalf("mode = %q %v, want active", mode, err) |
| + } |
| + e.fx.srv.hosts.mu.Lock() |
| + e.fx.srv.hosts.verified = true |
| + e.fx.srv.hosts.mu.Unlock() |
| + status, body, _ := e.get(t, "2027-01") |
| + if status != http.StatusConflict || jsonField(t, body, "first_month") != "2027-02" { |
| + t.Fatalf("route for January after the break = %d %s, want 409 naming 2027-02", status, body) |
| + } |
| + want := usage.InstanceFrom{From: "2027-02-01", Activation: usageAt2} |
| + if f, _ := storeUsageFrom(t, e.fx.rel); !sameFrom(f, want) { |
| + t.Fatalf("@from = %+v, want %+v", f, want) |
| + } |
| +} |
| + |
| +// TestRunUsageFromStopsOnceHeld: the start-up loop checks on each tick |
| +// until @from is held, then returns. |
| +func TestRunUsageFromStopsOnceHeld(t *testing.T) { |
| + fx := usageFixture(t, true) |
| + fx.srv.usageNow = func() time.Time { return usageT0 } |
| + holdHosts(fx.srv, activeAt(usageAt1), false) |
| + tick := make(chan time.Time) |
| + done := make(chan struct{}) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go func() { |
| + fx.srv.runUsageFrom(ctx, tick) |
| + close(done) |
| + }() |
| + tick <- usageT0 // the first check was pending; this is the second |
| + if _, ok := storeUsageFrom(t, fx.rel); ok { |
| + t.Fatal("@from written while pending") |
| + } |
| + holdHosts(fx.srv, activeAt(usageAt1), true) |
| + select { |
| + case tick <- usageT0: |
| + case <-done: |
| + } |
| + <-done |
| + if f, ok := storeUsageFrom(t, fx.rel); !ok || f.From != "2027-02-01" { |
| + t.Fatalf("@from = %+v %v, want 2027-02-01", f, ok) |
| + } |
| +} |
diff --git a/internal/console/usagerole_test.go b/internal/console/usagerole_test.go| index 75c449d77..b3becf556 100644 |
| --- a/internal/console/usagerole_test.go |
| +++ b/internal/console/usagerole_test.go |
| @@ -270,12 +270,16 @@ func TestLinkedAppReachesTheUsageDoor(t *testing.T) { |
| if _, err := fx.st.CreateLinkedApp(acct.ID, "shop", "link:"+fx.sqid+"/"+p.LinkID, p.LinkID, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| + // The history held verified active and counting started: the read |
| + // answers. |
| + fx.srv.usageNow = func() time.Time { return usageT0 } |
| + holdHosts(fx.srv, activeAt(usageAt1), true) |
| + seedUsageFrom(t, fx.rel, "2027-01-01", usageAt1) |
| refusal := linkCopy(copyLD11, "app", "shop", "home", "walk-home") |
| member := mintWalkPerson(t, fx.st) |
| status, body := getRaw(t, usageURL(fx, "shop"), member) |
| - if status == http.StatusConflict || linkJSONErr(body) == refusal || |
| - status == http.StatusNotFound || status == http.StatusUnauthorized || status == http.StatusForbidden { |
| - t.Errorf("member at a linked app's usage door = %d %s, want past the gates and the linked guard", status, body) |
| + if status != http.StatusOK || linkJSONErr(body) == refusal { |
| + t.Errorf("member at a linked app's usage door = %d %s, want past the gates and the linked guard: 200", status, body) |
| } |
| status, body = getRaw(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/logs", member) |
| if status != http.StatusConflict || linkJSONErr(body) != refusal { |