Skip to content

Scale to zero: stop idle projects, start them on the next visit - #3

Merged
michaelaguiar merged 8 commits into
share-cloudflare-tunnelfrom
scale-to-zero
Oct 13, 2026
Merged

michaelaguiar merged 8 commits into
share-cloudflare-tunnelfrom
scale-to-zero

Conversation

@michaelaguiar

@michaelaguiar michaelaguiar commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Stacked on #2 (it changes the share vhost too). Merge #2 first; this PR then retargets to main.

What

Projects nobody is using are stopped, and the next request to one starts it again.

  • alios_idle, a new global service (cmd/alios-idle, internal/idle), does both jobs:
    • Stopping: every 30s it reads each running project's counters from the Docker API. A project counts as active on more than ~8 KiB/min of traffic, more than 1% of a core, or any process exec'd into the container (seen in two samples in a row), such as an open alios shell. One that stays quiet on all three for ALIOS_IDLE_TIMEOUT (default 30m) is stopped.
    • Waking: each vhost ends with import alios_wake <project>. That snippet sends Caddy's 502/503/504 upstream failures to the waker, which starts the container, waits for port 80, and replies with a 307 to the same URL. The waker is asked with a bodiless GET, and the browser resends a POST's body itself. Concurrent requests share one start. A container that's up and listening but still failing gets an error page instead of a redirect loop, except just after a wake, when a burst of asset requests is expected.
  • Sleeping vs stopped: a project the watcher stops is asleep and wakes on the next visit. alios stop keeps a project down until alios start: its vhost imports alios_stopped instead of alios_wake, and visits get a "stopped" page.
  • alios idle [on|off|<duration>] sets a per-project setting, stored in the alios.project.idle label.
  • CLI changes: exec, shell and share start a sleeping project. list and status show it as "sleeping". doctor checks the service, and flags vhosts that predate the snippet and projects busy for hours with no traffic.
  • Optional: alios_idle runs outside the compose group. If its image can't be pulled, global start warns and everything else still works.
  • Image: ghcr.io/aliasproject/alios-idle:<version> is a ~9 MB image built from scratch. scripts/release.sh builds and pushes it for amd64 and arm64.
  • The design is in docs/IDLE.md.

Testing

  • go test -race ./... covers the idle decision logic, the waker (redirects, the loop guard, concurrent wakes, refusing containers that aren't the project's, timeouts) and the watcher (timeouts, per-project settings, busy warnings).
  • Sandbox on the real Docker daemon, live stack untouched: the watcher stopped a container with a 1m timeout on schedule. A request through Caddy 2.10, using the generated snippet, woke a stopped project in ~280 ms and landed on the same URL.
  • caddy adapt accepts the generated base Caddyfile and vhosts. Only 502/503/504 route to the waker.

Not tested yet

  • The real stack: this hasn't run as alios global start on a real machine, because the image isn't published, and switching the live stack over stops idle sites.
  • The release step: release.sh's buildx --push has never been run.
  • Other platforms: Docker Desktop (macOS/Windows) and rootless Docker are untested. Rootless isn't supported.

- Global services gain alios_idle (image tagged with the CLI version,
  ALIOS_IDLE_TIMEOUT passed through, Docker socket mounted, internal
  network only).
- The base Caddyfile defines an alios_wake snippet that sends 502/503/504
  upstream failures to the waker; project, HTTP-only and share vhosts
  import it in place of the old "Project unavailable" response.
- `alios idle [on|off|<duration>]` stores a per-project setting in the
  alios.project.idle label (recreating the container like `alios env`).
- `exec`, `shell`, the implicit command fallthrough and `share` start a
  sleeping project instead of failing; `list` and `status` show a stopped
  project as sleeping while alios_idle runs; `stop` says a visit restarts
  it.
- `doctor` checks alios_idle, ALIOS_IDLE_TIMEOUT, vhosts that predate the
  snippet, and busy-warning lines from the last 24h; `global start` and
  `restart` point out vhosts that still need `alios cert repair`.
- scripts/release.sh builds and pushes the multi-arch alios-idle image.
- docs/IDLE.md, README and CLAUDE.md describe it.

Verified in sandboxes on the real Docker daemon, without touching the
live stack: the watcher stopped a 1m-timeout container on schedule, and
a request through Caddy with the generated snippet woke a stopped
project in ~280ms and was redirected back to the same URL. Caddy 2.10
adapts the generated Caddyfile with the snippet routing only 502/503/504.
- POST/PUT bodies: the first proxy hop consumes the body, so forwarding
  the request to the waker failed and Caddy returned an empty 502. The
  snippet now asks the waker with a bodiless GET; the browser resends the
  original method and body after the 307. Verified through Caddy 2.10
  with 100 KB and chunked POSTs.
- `alios cert repair` wrote vhosts importing alios_wake without the base
  Caddyfile that defines it, so Caddy crash-looped until `global start`.
  Repair now writes the base config first (services.WriteBaseConfig).
- alios_idle was a compose service in GlobalServices, so an unpullable
  image aborted `global start` and took every project down. It now runs
  on its own, best-effort, with a warning when it can't start.
- `alios pause` stopped projects while the waker still ran, so a request
  mid-pause could start one again. Pause stops alios_idle first and still
  resumes it.
- An `alios shell` opened as the container started was folded into the
  process baseline and never counted, so the shell was killed after the
  timeout. Exec'd processes are now identified directly (not descended
  from the container's main PID) instead of against a baseline.
- Open redirect: a path starting "//" made the waker's Location
  protocol-relative (https://<share>//evil.com). Leading slashes are
  collapsed.
- ALIOS_IDLE_TIMEOUT from whichever shell started services silently reset
  the service's timeout. It's now only changed when the variable is set,
  stored on the container, and status/idle/doctor report the running
  value.
- A container started moments ago by anything (not just the waker) gets a
  retry instead of "not responding"; a request that arrives while the
  container is being stopped starts it again once the stop finishes
  rather than waiting out the timeout; Docker API calls time out after
  30s; a failed sample no longer restarts a project's idle timer; the
  stale-vhost hint counts only project vhost files.
@michaelaguiar

Copy link
Copy Markdown
Member Author

Review round 1 (fresh-context reviewer, code-review at high effort)

Fixed in eff373f:

  1. P2, POSTs to a sleeping project returned Caddy's empty 502. The first hop had consumed the body. The waker is now asked with a bodiless GET, and the browser resends the method and body after the 307. Verified through Caddy 2.10: a 100 KB POST and a chunked POST both get a 307 to the same URL.
  2. P2, cert repair crash-looped Caddy. It wrote vhosts that import alios_wake without the base Caddyfile. It now writes the base config first.
  3. P2, alios_idle was a hard dependency. It now runs outside compose on a best-effort basis. A missing image gives a warning, and DNS, Caddy and the projects keep working.
  4. P2, a request mid-pause could wake a project behind the pause. Pause now stops alios_idle first and still resumes it.
  5. P2, an alios shell opened at wake time was never counted, so the shell got killed after the timeout. I replaced the process baseline instead of patching it: exec'd processes are now the ones not descended from the container's main PID, from docker top PID/PPID with default ps arguments. Regression tests cover a shell held open for an hour, and countExecProcs itself.
  6. P2, open redirect via //host. Leading slashes are collapsed. The regression test fails without the fix, and it's verified through Caddy.
  7. P2, the timeout was reset by whichever shell started services. It now changes only when ALIOS_IDLE_TIMEOUT is set, it's stored on the container, and status, idle and doctor report the running value.
  8. P3: "Started recently" now comes from the container's own StartedAt, so a container started by alios start or exec also gets a retry. There's a regression test.
  9. P3: A request arriving during a stop now starts the container once the stop finishes, with a regression test.
  10. P3: Docker API calls now time out after 30s.
  11. P3: A failed sample no longer resets a project's idle timer.
  12. P3: The vhost hint counts only project vhost file names: no pull messages, no share vhosts.

Declined:
10. P3, bare 502 when alios_idle is down. handle_errors gives a failing reverse_proxy no fallback route, so a page there would need a second error layer. With #3 fixed, global start warns and doctor fails when the service is down. docs/IDLE.md now says what you see in that case.

The reviewer confirmed these hold: the compose verbs, the header override, the label check before any start, idle settings surviving a recreate, waker concurrency, and the watcher failing safe on errors.

- startIdle removed the running alios_idle before pulling the image for
  the new CLI version, so a failed pull (offline, not yet published) left
  no waker and every sleeping project served an empty 502. It now pulls
  first and keeps the previous service on failure.
- alios_idle is listed in `alios status` / `global status` again (it left
  GlobalServices), so a stopped or crashed one is visible. Doctor's
  services section skips it; its own section covers it.
- An open but idle `alios shell` counted as "busy without traffic" and
  produced busy warnings after 2h. Only CPU use without traffic counts
  now (regression test fails without the fix).
- Docs/comments no longer describe the removed process baseline.
@michaelaguiar

Copy link
Copy Markdown
Member Author

Review round 2

The reviewer confirmed all 12 round-1 fixes hold. It checked exec detection against a live container's docker top (the main PID's parent is the shim, outside the listing), --init/s6/supervisor trees, the 304 handling, and the redirect edge cases. -race -count=3 is stable.

Fixed in 7ed8c86:

  • P2: on a CLI update, the old alios_idle was removed before the new image was pulled. It now pulls first and keeps the previous version running if the pull fails.
  • P3: alios_idle is listed in status and global status again.
  • P3: an idle open shell no longer triggers busy warnings. Only CPU without traffic counts as busy now, with a regression test.
  • P3: the docs and comments no longer mention the removed process baseline.

Not verified: whether Docker Desktop's docker top output includes a PPID column. If it doesn't, sampling fails safe (it logs an error and stops nothing). It needs a check on a Mac.

@michaelaguiar

Copy link
Copy Markdown
Member Author

Review round 3

The reviewer confirmed all four round-2 fixes hold. It checked every Status() consumer: none treats the listed alios_idle as a failure or as "not set up", and GlobalServices isn't mutated. Busy warnings now need CPU, and no baseline wording is left.

There was one P3, fixed in 9d678f3: when the pull fails and the old alios_idle also fails to start, the warning now says so instead of claiming it's running.

Leaving this as a draft while the alios stop semantics are decided (whether stop means sleep or stay down).

A project the watcher stops for being idle is asleep and wakes on the
next visit. One stopped by hand now stays stopped: otherwise a polling
browser tab, an HMR reconnect or a webhook undoes the stop a second
later with no explanation.

- The vhost records which: `alios stop` swaps `import alios_wake <name>`
  for `import alios_stopped <name>`, a new snippet answering 503 "<name>
  is stopped. Run 'alios start'..." (checked through Caddy 2.10).
  `alios start` rewrites the vhost back; restart, pause/resume leave it.
- `cert repair` keeps stopped projects stopped.
- `exec`, `shell` and `share` start an asleep project but refuse a
  stopped one; `list`/`status` show sleeping vs stopped; doctor reports
  a stopped project as info, and neither it nor the global-start hint
  mistakes a stopped vhost for one that predates scale to zero.
- The swap matches whole lines (unit-tested), so stopping "sho" can't
  touch "shop"'s vhost.
- P1: the vhost was marked stopped only after the container was down, so
  a polling tab hit the waker mid-stop and it started the project again.
  The marker is now written (and Caddy reloaded) before the stop.
- rebuild, php and image start the container but left the marker, so a
  running project showed as stopped and wouldn't wake after its next
  idle stop. They clear it now.
- A vhost importing a snippet the running base Caddyfile lacks (stack
  started by an older alios) made the reload fail and left a file that
  crash-loops Caddy on its next start. stop/start/rebuild/php/image now
  write the current base Caddyfile first, and SetProjectStopped puts the
  vhost back if Caddy rejects it.
- `cert remove` (updateVhostToHTTP) keeps a stop.
- exec/shell/share refuse only a project stopped by hand; if alios_idle
  is down or the vhosts can't be read they wake it as before.
- `alios list` reads the stop markers only when a project is down and
  alios_idle runs, and on a read error calls nothing asleep.
- The stop message no longer promises "stays stopped" after a failed
  mark; docs list which commands clear and keep the marker.
@michaelaguiar

Copy link
Copy Markdown
Member Author

alios stop = stay down (decided with Mike), and its review rounds

96432e3: a project the watcher stops is asleep and wakes on the next visit. One stopped with alios stop stays down until alios start, and visits get a 503 "stopped" page. The vhost records which state applies: import alios_wake <name> or import alios_stopped <name>. The swap matches whole lines and is unit-tested. It was checked through Caddy 2.10.

Review A found 1 P1, 2 P2 and 5 P3, all fixed in bc7f306:

  • P1: the marker was written only after the container stopped, so the waker restarted a project caught mid-stop. It's now written first.
  • P2: rebuild, php and image left the marker in place. They now clear it.
  • P2: a vhost importing a snippet missing from an older base Caddyfile broke Caddy's next start. The base config is now rewritten first, and the vhost is rolled back if the reload fails.
  • P3: cert remove now keeps a stop.
  • P3: exec, shell and share refuse only a project stopped by hand.
  • P3: list fails safe and only reads the vhosts when needed.
  • P3: the stop message and the docs were corrected.

Review B confirmed all of A's fixes hold. Its two P3s are fixed in 5668786: a stop that fails after marking now unmarks the project, and a duplicate base-config write on a non-SSL start is skipped.

internal/commands has no tests, so the handler paths are covered only by the reviews and the sandbox checks.

@michaelaguiar
michaelaguiar marked this pull request as ready for review October 13, 2026 18:19
@michaelaguiar
michaelaguiar merged commit a007294 into share-cloudflare-tunnel Oct 13, 2026
michaelaguiar added a commit that referenced this pull request Oct 13, 2026
@michaelaguiar
michaelaguiar deleted the scale-to-zero branch October 13, 2026 20:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant