fix(container): idle stop ignores silent sessions and never loses work
- The agent marks requests with X-Triple-C-Background: 1 (and the attach/tunnel sessions they open) as not activity (R11). - triple-c-idle-watch no longer requires zero open execs/tunnels: idle is last_activity older than N minutes, no claude, no scheduler job, no running clone, and no unsaved git work. With the WIP push on, it pushes as claude before signalling and stays up (backing off) when the push fails; with it off, dirty repos keep the workspace up. - An idle stop exits 75 so ECS reports it distinctly from a crash; the TERM trap no longer pushes again after the watcher's push. - start_clone_repos writes done from an EXIT trap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3f986368aa
commit
95b68ed068
7 files changed
+266
-63
No files matched your search
+19
-6
@@ -724,8 +724,10 @@ start_clone_repos() {
|
||||
mkdir -m 755 "$status_dir" || status_dir=""
|
||||
(
|
||||
trap '' HUP
|
||||
# `done` however the clone ends (an error, a signal), or the idle
|
||||
# watcher would count it as still running forever.
|
||||
[ -z "$status_dir" ] || trap ': > "$status_dir/done"' EXIT
|
||||
clone_repos "$json" /workspace "$status_dir"
|
||||
[ -z "$status_dir" ] || : > "$status_dir/done"
|
||||
) &
|
||||
}
|
||||
# <<< aws_repos
|
||||
@@ -1170,7 +1172,9 @@ start_agent
|
||||
# with TRIPLEC_WIP_PUSH=1 it pushes every repo's unsaved work to a
|
||||
# triple-c/wip/<stamp> branch (as `claude`, bounded at 90 s), unless the app's
|
||||
# stop guard recorded `pushed` or `discard` in /run/triple-c/stop-reason
|
||||
# (written as root through the agent just before StopTask). ECS gives a task
|
||||
# (written as root through the agent just before StopTask), or the idle
|
||||
# watcher recorded `idle` (it pushes *before* signalling and only signals once
|
||||
# nothing unsaved is left, so an idle stop never loses work). ECS gives a task
|
||||
# `stopTimeout` seconds between SIGTERM and SIGKILL — 30 by default, 120 at
|
||||
# most on Fargate — so the task definition must raise it for the push to
|
||||
# finish. Once only: a second TERM during the push changes nothing.
|
||||
@@ -1180,9 +1184,13 @@ start_agent
|
||||
# auto-stop off. When the workspace is idle it records the reason "idle" and
|
||||
# sends TERM to *this* script ($$) — not PID 1, which under ECS's
|
||||
# initProcessEnabled is docker-init — so an idle stop and an ECS stop take
|
||||
# this same trap and push at most once. Its environment is built from scratch:
|
||||
# it needs none of the container's.
|
||||
# this same trap and push at most once. An idle stop exits with status 75
|
||||
# (triplec_idle_exit; Rust `aws::tasks::IDLE_EXIT_CODE`), so ECS reports it as
|
||||
# EssentialContainerExited with that exit code and the app can say "stopped
|
||||
# after being idle" rather than "crashed". Its environment is built from
|
||||
# scratch: it needs none of the container's but TRIPLEC_WIP_PUSH.
|
||||
# >>> aws_stop
|
||||
triplec_idle_exit=75
|
||||
aws_before_stop() {
|
||||
[ "${TRIPLEC_HOST:-}" = aws ] || return 0
|
||||
[ -z "${triplec_stopping:-}" ] || return 0
|
||||
@@ -1190,7 +1198,11 @@ aws_before_stop() {
|
||||
local reason=sigterm recorded
|
||||
recorded=$(cat /run/triple-c/stop-reason 2>/dev/null)
|
||||
case "$recorded" in
|
||||
idle) reason=idle ;;
|
||||
idle)
|
||||
# The watcher already pushed (or found nothing to push).
|
||||
triplec_exit_status=$triplec_idle_exit
|
||||
echo "entrypoint: stopping (idle) — work in progress already handled by the idle watcher"
|
||||
return 0 ;;
|
||||
# The app's stop guard already pushed, or the user chose to stop
|
||||
# without pushing: honour that instead of pushing again.
|
||||
pushed|discard)
|
||||
@@ -1220,6 +1232,7 @@ start_idle_watch() {
|
||||
TRIPLEC_IDLE_STOP_MINUTES="$minutes" \
|
||||
TRIPLEC_IDLE_SIGNAL_PID="$signal_pid" \
|
||||
TRIPLEC_AGENT_TOKEN_FILE="${TRIPLEC_AGENT_TOKEN_FILE:-/dev/shm/triple-c/agent-token}" \
|
||||
TRIPLEC_WIP_PUSH="${TRIPLEC_WIP_PUSH:-0}" \
|
||||
/usr/local/bin/triple-c-idle-watch
|
||||
rc=$?
|
||||
# 0: it signalled the stop. 2: misconfigured, and a restart would
|
||||
@@ -1244,7 +1257,7 @@ keepalive_pid=""
|
||||
stop_keepalive() {
|
||||
[ "$triplec_aws" = 1 ] && aws_before_stop
|
||||
[ -n "$keepalive_pid" ] && kill "$keepalive_pid" 2>/dev/null
|
||||
exit 0
|
||||
exit "${triplec_exit_status:-0}"
|
||||
}
|
||||
trap stop_keepalive TERM INT HUP
|
||||
throttle_fifo=/run/triple-c-keepalive.throttle
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::State;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::response::Response;
|
||||
use bytes::Bytes;
|
||||
use serde::Deserialize;
|
||||
@@ -13,7 +13,7 @@ use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::pty;
|
||||
use crate::spawn::{self, ExecSpec, Io, PrepareError};
|
||||
use crate::{AppState, CountGuard, MAX_WS_MESSAGE};
|
||||
use crate::{AppState, Background, CountGuard, MAX_WS_MESSAGE};
|
||||
|
||||
/// How long the client has to send its spec after the upgrade.
|
||||
const SPEC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -47,10 +47,15 @@ enum Input {
|
||||
Data(Bytes),
|
||||
}
|
||||
|
||||
pub async fn upgrade(State(st): State<Arc<AppState>>, ws: WebSocketUpgrade) -> Response {
|
||||
pub async fn upgrade(
|
||||
State(st): State<Arc<AppState>>,
|
||||
bg: Option<Extension<Background>>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
let bg = bg.map(|Extension(b)| b).unwrap_or_default();
|
||||
ws.max_message_size(MAX_WS_MESSAGE)
|
||||
.max_frame_size(MAX_WS_MESSAGE)
|
||||
.on_upgrade(move |socket| session(socket, st))
|
||||
.on_upgrade(move |socket| session(socket, st, bg))
|
||||
}
|
||||
|
||||
fn text(v: serde_json::Value) -> Message {
|
||||
@@ -69,7 +74,7 @@ fn frame(channel: u8, data: &[u8]) -> Message {
|
||||
Message::Binary(v.into())
|
||||
}
|
||||
|
||||
async fn session(mut socket: WebSocket, st: Arc<AppState>) {
|
||||
async fn session(mut socket: WebSocket, st: Arc<AppState>, bg: Background) {
|
||||
// 1. The spec, as one text frame.
|
||||
let first = match tokio::time::timeout(SPEC_TIMEOUT, socket.recv()).await {
|
||||
Ok(Some(Ok(Message::Text(t)))) => t,
|
||||
@@ -166,7 +171,7 @@ async fn session(mut socket: WebSocket, st: Arc<AppState>) {
|
||||
tokio::select! {
|
||||
ev = ev_rx.recv() => match ev {
|
||||
Some(Event::Out(ch, data)) => {
|
||||
st.activity.touch();
|
||||
st.activity.touch_for(bg);
|
||||
if socket.send(frame(ch, &data)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
@@ -180,7 +185,7 @@ async fn session(mut socket: WebSocket, st: Arc<AppState>) {
|
||||
},
|
||||
msg = socket.recv() => match msg {
|
||||
Some(Ok(Message::Binary(data))) => {
|
||||
st.activity.touch();
|
||||
st.activity.touch_for(bg);
|
||||
if req.attach_stdin {
|
||||
if let Some(tx) = &in_tx {
|
||||
let _ = tx.send(Input::Data(data));
|
||||
|
||||
@@ -194,6 +194,30 @@ impl Activity {
|
||||
pub fn touch(&self) {
|
||||
self.last_unix.store(now_unix(), Ordering::Relaxed);
|
||||
}
|
||||
/// Touch unless the session belongs to a background request.
|
||||
pub fn touch_for(&self, bg: Background) {
|
||||
if !bg.0 {
|
||||
self.touch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A request carrying this header with the value `1` is a background poll
|
||||
/// (the app's auth bridge reading `/proc/net/tcp` every 2 s): it is served
|
||||
/// like any other but never counts as activity, nor does the I/O of an
|
||||
/// attach or tunnel it opens. Otherwise such polls would keep an idle
|
||||
/// workspace up forever.
|
||||
pub const BACKGROUND_HEADER: &str = "x-triple-c-background";
|
||||
|
||||
/// Whether the request was marked with [`BACKGROUND_HEADER`]; set by the
|
||||
/// auth layer as a request extension for the handlers that keep a session.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct Background(pub bool);
|
||||
|
||||
impl Background {
|
||||
pub fn of(headers: &axum::http::HeaderMap) -> Background {
|
||||
Background(headers.get(BACKGROUND_HEADER).is_some_and(|v| v.as_bytes() == b"1"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Increments a counter for as long as it lives, so an exec or tunnel that
|
||||
@@ -326,7 +350,7 @@ pub async fn serve(listener: tokio::net::TcpListener, config: Config) -> std::io
|
||||
/// Bearer-token gate on every request. A failure is `401` with an **empty**
|
||||
/// body (spec): nothing about the API is disclosed to a caller without the
|
||||
/// token.
|
||||
async fn auth(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
|
||||
async fn auth(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||
let presented = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
@@ -336,11 +360,14 @@ async fn auth(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Resp
|
||||
return StatusCode::UNAUTHORIZED.into_response();
|
||||
}
|
||||
// `health` and `activity` are the idle monitor's own probes; counting them
|
||||
// would mean an idle container could never look idle.
|
||||
// would mean an idle container could never look idle. Background polls
|
||||
// (see [`BACKGROUND_HEADER`]) are exempt for the same reason.
|
||||
let bg = Background::of(req.headers());
|
||||
let path = req.uri().path();
|
||||
if path != "/v1/health" && path != "/v1/activity" {
|
||||
st.activity.touch();
|
||||
st.activity.touch_for(bg);
|
||||
}
|
||||
req.extensions_mut().insert(bg);
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
|
||||
@@ -7,14 +7,14 @@ use std::time::Duration;
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{Query, State};
|
||||
use axum::extract::{Extension, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use serde::Deserialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::{error, AppState, CountGuard, MAX_WS_MESSAGE};
|
||||
use crate::{error, AppState, Background, CountGuard, MAX_WS_MESSAGE};
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
@@ -25,9 +25,11 @@ pub struct TunnelQuery {
|
||||
|
||||
pub async fn upgrade(
|
||||
State(st): State<Arc<AppState>>,
|
||||
bg: Option<Extension<Background>>,
|
||||
q: Result<Query<TunnelQuery>, QueryRejection>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
let bg = bg.map(|Extension(b)| b).unwrap_or_default();
|
||||
let port = match q {
|
||||
Ok(Query(q)) if q.port != 0 => q.port,
|
||||
Ok(_) => return error(StatusCode::BAD_REQUEST, "port must be 1-65535"),
|
||||
@@ -35,10 +37,10 @@ pub async fn upgrade(
|
||||
};
|
||||
ws.max_message_size(MAX_WS_MESSAGE)
|
||||
.max_frame_size(MAX_WS_MESSAGE)
|
||||
.on_upgrade(move |socket| session(socket, st, port))
|
||||
.on_upgrade(move |socket| session(socket, st, port, bg))
|
||||
}
|
||||
|
||||
async fn session(mut socket: WebSocket, st: Arc<AppState>, port: u16) {
|
||||
async fn session(mut socket: WebSocket, st: Arc<AppState>, port: u16, bg: Background) {
|
||||
// Loopback only, by construction: the tunnel reaches in-container
|
||||
// listeners, never the network the container can see.
|
||||
let tcp = match tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(("127.0.0.1", port))).await {
|
||||
@@ -56,7 +58,7 @@ async fn session(mut socket: WebSocket, st: Arc<AppState>, port: u16) {
|
||||
tokio::select! {
|
||||
r = rd.read(&mut buf) => match r {
|
||||
Ok(n) if n > 0 => {
|
||||
st.activity.touch();
|
||||
st.activity.touch_for(bg);
|
||||
if socket.send(Message::Binary(buf[..n].to_vec().into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
@@ -68,7 +70,7 @@ async fn session(mut socket: WebSocket, st: Arc<AppState>, port: u16) {
|
||||
},
|
||||
m = socket.recv() => match m {
|
||||
Some(Ok(Message::Binary(d))) => {
|
||||
st.activity.touch();
|
||||
st.activity.touch_for(bg);
|
||||
if wr.write_all(&d).await.is_err() {
|
||||
let _ = socket.send(Message::Close(None)).await;
|
||||
return;
|
||||
|
||||
@@ -862,6 +862,76 @@ async fn activity_counts_execs_and_tunnels_and_ignores_its_own_probes() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_requests_and_their_sessions_are_not_activity() {
|
||||
let a = start().await;
|
||||
let (_, v0) = a.get("/v1/activity").await;
|
||||
let t0 = v0["last_activity_unix"].as_i64().unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(1100)).await;
|
||||
|
||||
// A one-shot exec marked as background.
|
||||
let r = a
|
||||
.http
|
||||
.post(a.url("/v1/exec"))
|
||||
.bearer_auth(TOKEN)
|
||||
.header("X-Triple-C-Background", "1")
|
||||
.json(&json!({ "cmd": ["echo", "hi"], "user": a.user }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status(), 200);
|
||||
|
||||
// A background attach whose process talks.
|
||||
let mut req = format!("ws://{}/v1/attach", a.addr).into_client_request().unwrap();
|
||||
req.headers_mut().insert("Authorization", format!("Bearer {TOKEN}").parse().unwrap());
|
||||
req.headers_mut().insert("X-Triple-C-Background", "1".parse().unwrap());
|
||||
let mut ws = tokio_tungstenite::connect_async(req).await.unwrap().0;
|
||||
let spec = json!({ "cmd": ["sh", "-c", "echo out; cat"], "user": a.user, "attach_stdin": true });
|
||||
ws.send(Message::Text(spec.to_string().into())).await.unwrap();
|
||||
assert_eq!(next_text(&mut ws).await["type"], "started");
|
||||
ws.send(Message::Binary(b"typed\n".to_vec().into())).await.unwrap();
|
||||
let mut acc = Vec::new();
|
||||
read_until(&mut ws, &mut acc, "typed").await;
|
||||
|
||||
let (_, v) = a.get("/v1/activity").await;
|
||||
assert_eq!(v["last_activity_unix"].as_i64().unwrap(), t0, "background requests are not activity: {v}");
|
||||
|
||||
// Any other value of the header is an ordinary request.
|
||||
a.http
|
||||
.get(a.url("/v1/exec/nope"))
|
||||
.bearer_auth(TOKEN)
|
||||
.header("X-Triple-C-Background", "yes")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let (_, v) = a.get("/v1/activity").await;
|
||||
assert!(v["last_activity_unix"].as_i64().unwrap() > t0, "{v}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_open_but_silent_attach_stops_being_activity() {
|
||||
let a = start().await;
|
||||
let (mut ws, _) = a.attach(json!({ "cmd": ["cat"], "attach_stdin": true })).await;
|
||||
ws.send(Message::Binary(b"x\n".to_vec().into())).await.unwrap();
|
||||
let mut acc = Vec::new();
|
||||
read_until(&mut ws, &mut acc, "x").await;
|
||||
let (_, v) = a.get("/v1/activity").await;
|
||||
let t1 = v["last_activity_unix"].as_i64().unwrap();
|
||||
assert_eq!(v["active_execs"], 1);
|
||||
|
||||
// Still attached, nothing flowing: the timestamp stays put, so the
|
||||
// idle watcher (which no longer looks at the counters) can see it age.
|
||||
tokio::time::sleep(Duration::from_millis(2100)).await;
|
||||
let (_, v) = a.get("/v1/activity").await;
|
||||
assert_eq!(v["last_activity_unix"].as_i64().unwrap(), t1, "{v}");
|
||||
|
||||
// Input on the attach is activity again.
|
||||
ws.send(Message::Binary(b"y\n".to_vec().into())).await.unwrap();
|
||||
read_until(&mut ws, &mut acc, "y").await;
|
||||
let (_, v) = a.get("/v1/activity").await;
|
||||
assert!(v["last_activity_unix"].as_i64().unwrap() > t1, "{v}");
|
||||
}
|
||||
|
||||
// ── connection limits ──────────────────────────────────────────────────────
|
||||
|
||||
/// Wait for the server to close `s`: `Ok(elapsed)` on EOF or reset,
|
||||
|
||||
+115
-39
@@ -1,45 +1,62 @@
|
||||
#!/bin/bash
|
||||
# triple-c-idle-watch [--check]
|
||||
#
|
||||
# Idle auto-stop for an AWS workspace (plan ruling P7). Started by
|
||||
# Idle auto-stop for an AWS workspace (plan ruling P7, R11). Started by
|
||||
# entrypoint.sh, as root, only when TRIPLEC_HOST=aws and
|
||||
# TRIPLEC_IDLE_STOP_MINUTES is set. Every interval it asks whether the
|
||||
# workspace is idle:
|
||||
#
|
||||
# * the agent's /v1/activity (read with the agent's own token file) shows
|
||||
# no authenticated activity for N minutes, no open exec, no open tunnel;
|
||||
# no authenticated activity for N minutes. The agent counts requests and
|
||||
# the bytes of attaches and tunnels, so an open but silent terminal tab
|
||||
# ages like no tab at all, and the app's background polls (the auth
|
||||
# bridge, marked X-Triple-C-Background) never count. The open exec and
|
||||
# tunnel counters are *not* consulted (R11);
|
||||
# * no `claude` process is running;
|
||||
# * no scheduler job is running (`triple-c-scheduler status`, as claude);
|
||||
# * the start's background repository clone has finished (entrypoint.sh,
|
||||
# start_clone_repos: /run/triple-c-clone exists without `done`).
|
||||
# start_clone_repos: /run/triple-c-clone exists without `done`);
|
||||
# * no work would be lost: `triple-c-wip-push --dry-run` (as claude) finds
|
||||
# no dirty repository and no unpushed commit. With the WIP push on
|
||||
# (TRIPLEC_WIP_PUSH=1) such work is pushed here, before the stop, and the
|
||||
# workspace stops only once that push succeeded; a failed push keeps it
|
||||
# running and is retried later (backing off). With it off, unsaved work
|
||||
# simply keeps the workspace up.
|
||||
#
|
||||
# Anything it cannot read counts as NOT idle: a stop is the one thing here
|
||||
# that cannot be undone, so every doubt keeps the workspace running.
|
||||
#
|
||||
# When idle it records "idle" as the stop reason and sends SIGTERM to the
|
||||
# entrypoint (TRIPLEC_IDLE_SIGNAL_PID). The entrypoint's TERM trap does the
|
||||
# WIP push (reason read from that file) and stops the keepalive, so a stop
|
||||
# from here and a stop from ECS take the same single path — and a SIGTERM from
|
||||
# ECS arriving mid-push cannot start a second, concurrent push.
|
||||
# entrypoint (TRIPLEC_IDLE_SIGNAL_PID). The entrypoint's TERM trap sees
|
||||
# "idle", does not push again (this script already did), stops the keepalive
|
||||
# and exits with the idle status (75) so the app can tell an idle stop from a
|
||||
# crash. A stop from ECS (SIGTERM, no marker) still pushes in the trap, best
|
||||
# effort; a SIGTERM from ECS arriving mid-way cannot start a second push.
|
||||
#
|
||||
# Why not `kill -TERM 1`: with initProcessEnabled ECS runs the container under
|
||||
# docker-init, so PID 1 is the init, not the entrypoint. The init would
|
||||
# forward the signal, but signalling the entrypoint directly does not depend on
|
||||
# that and also works without an init.
|
||||
#
|
||||
# --check evaluates once and exits 0 (idle) or 1 (not idle); for tests and
|
||||
# for looking at a live task.
|
||||
# --check evaluates once and exits 0 (idle and nothing unsaved, or unsaved
|
||||
# work the WIP push would take) or 1 (not idle); for tests and for looking at
|
||||
# a live task. It never pushes.
|
||||
#
|
||||
# Configuration (environment; the entrypoint sets the first three, the rest
|
||||
# Configuration (environment; the entrypoint sets the first four, the rest
|
||||
# exist for tests):
|
||||
# TRIPLEC_IDLE_STOP_MINUTES N (required, > 0)
|
||||
# TRIPLEC_IDLE_SIGNAL_PID the entrypoint's PID
|
||||
# TRIPLEC_AGENT_TOKEN_FILE default /dev/shm/triple-c/agent-token
|
||||
# TRIPLEC_WIP_PUSH 1: push unsaved work before an idle stop
|
||||
# TRIPLEC_AGENT_URL default http://127.0.0.1:47900
|
||||
# TRIPLEC_IDLE_INTERVAL seconds between checks, default 60
|
||||
# TRIPLEC_STOP_REASON_FILE default /run/triple-c/stop-reason
|
||||
# TRIPLEC_SCHEDULER_BIN default /usr/local/bin/triple-c-scheduler
|
||||
# TRIPLEC_SCHEDULER_USER default claude; empty runs it as this user
|
||||
# (also the user the WIP push runs as)
|
||||
# TRIPLEC_WIP_PUSH_BIN default /usr/local/bin/triple-c-wip-push
|
||||
# TRIPLEC_WIP_TIMEOUT seconds for the push, default 90
|
||||
# TRIPLEC_WIP_BACKOFF_MAX longest wait between push retries, default 1800
|
||||
# TRIPLEC_IDLE_PROC_NAME default claude
|
||||
# TRIPLEC_CLONE_STATUS_DIR default /run/triple-c-clone
|
||||
|
||||
@@ -55,26 +72,31 @@ scheduler="${TRIPLEC_SCHEDULER_BIN:-/usr/local/bin/triple-c-scheduler}"
|
||||
scheduler_user="${TRIPLEC_SCHEDULER_USER-claude}"
|
||||
proc_name="${TRIPLEC_IDLE_PROC_NAME:-claude}"
|
||||
clone_dir="${TRIPLEC_CLONE_STATUS_DIR:-/run/triple-c-clone}"
|
||||
wip_push="${TRIPLEC_WIP_PUSH:-0}"
|
||||
wip_bin="${TRIPLEC_WIP_PUSH_BIN:-/usr/local/bin/triple-c-wip-push}"
|
||||
wip_timeout="${TRIPLEC_WIP_TIMEOUT:-90}"
|
||||
backoff_max="${TRIPLEC_WIP_BACKOFF_MAX:-1800}"
|
||||
|
||||
# >>> is_idle
|
||||
# is_idle now last_activity_unix active_execs active_tunnels claude_running jobs_running minutes
|
||||
# is_idle now last_activity_unix claude_running jobs_running minutes
|
||||
# Pure: exit 0 when idle, 1 otherwise. Every argument must be a plain
|
||||
# non-negative integer; anything else (an empty or garbled read) is not idle.
|
||||
# Open execs and tunnels are deliberately not an input (R11): their traffic
|
||||
# already moves last_activity_unix, and an open but silent one is idle.
|
||||
is_idle() {
|
||||
local a
|
||||
[ $# -eq 7 ] || return 1
|
||||
[ $# -eq 5 ] || return 1
|
||||
for a in "$@"; do
|
||||
case "$a" in ''|*[!0-9]*) return 1 ;; esac
|
||||
done
|
||||
local now=$1 last=$2 execs=$3 tunnels=$4 claude=$5 jobs=$6 mins=$7
|
||||
local now=$1 last=$2 claude=$3 jobs=$4 mins=$5
|
||||
[ "$mins" -gt 0 ] || return 1
|
||||
[ "$execs" -eq 0 ] && [ "$tunnels" -eq 0 ] || return 1
|
||||
[ "$claude" -eq 0 ] && [ "$jobs" -eq 0 ] || return 1
|
||||
[ $((now - last)) -ge $((mins * 60)) ]
|
||||
}
|
||||
# <<< is_idle
|
||||
|
||||
# Prints "last execs tunnels", or fails.
|
||||
# Prints last_activity_unix, or fails.
|
||||
read_activity() {
|
||||
local token body
|
||||
token=$(cat "$token_file" 2>/dev/null) || return 1
|
||||
@@ -83,19 +105,23 @@ read_activity() {
|
||||
# is readable by every user in the container.
|
||||
body=$(printf 'header = "Authorization: Bearer %s"\n' "$token" \
|
||||
| curl -sf --max-time 5 --config - "$agent_url/v1/activity" 2>/dev/null) || return 1
|
||||
printf '%s' "$body" | jq -r '[.last_activity_unix, .active_execs, .active_tunnels]
|
||||
| map(if type == "number" and . >= 0 and . == floor then tostring else "x" end)
|
||||
| join(" ")' 2>/dev/null
|
||||
printf '%s' "$body" | jq -r '.last_activity_unix
|
||||
| if type == "number" and . >= 0 and . == floor then tostring else "x" end' 2>/dev/null
|
||||
}
|
||||
|
||||
# Run "$@" as the scheduler user (claude) when we are root, else as is.
|
||||
as_user() {
|
||||
if [ -n "$scheduler_user" ] && [ "$(id -u)" = 0 ]; then
|
||||
su -s /bin/bash -c '"$@"' -- "$scheduler_user" _ "$@"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# 1 when a scheduler job is running *or* the question cannot be answered.
|
||||
jobs_running() {
|
||||
local out
|
||||
if [ -n "$scheduler_user" ] && [ "$(id -u)" = 0 ]; then
|
||||
out=$(su -s /bin/bash -c '"$1" status' -- "$scheduler_user" _ "$scheduler" 2>/dev/null) || { echo 1; return; }
|
||||
else
|
||||
out=$("$scheduler" status 2>/dev/null) || { echo 1; return; }
|
||||
fi
|
||||
out=$(as_user "$scheduler" status 2>/dev/null) || { echo 1; return; }
|
||||
if [ "$out" = "Nothing running." ]; then echo 0; else echo 1; fi
|
||||
}
|
||||
|
||||
@@ -104,14 +130,38 @@ clone_running() {
|
||||
[ -d "$clone_dir" ] && [ ! -e "$clone_dir/done" ]
|
||||
}
|
||||
|
||||
check() {
|
||||
local act last execs tunnels claude jobs
|
||||
act=$(read_activity) || return 1
|
||||
read -r last execs tunnels <<< "$act"
|
||||
# The folders with unsaved work (dirty, or commits no remote has), one per
|
||||
# line; nothing when there is none. Fails when it cannot tell.
|
||||
unsaved_work() {
|
||||
local out
|
||||
out=$(as_user timeout -k 5 60 "$wip_bin" --dry-run 2>/dev/null) || return 1
|
||||
printf '%s\n' "$out" | jq -r 'select(.dirty == true or (.unpushed // 0) > 0) | .folder' 2>/dev/null
|
||||
}
|
||||
|
||||
# The activity, process, job and clone conditions.
|
||||
quiet() {
|
||||
local last claude jobs
|
||||
last=$(read_activity) || return 1
|
||||
if pgrep -x "$proc_name" >/dev/null 2>&1; then claude=1; else claude=0; fi
|
||||
jobs=$(jobs_running)
|
||||
clone_running && jobs=1
|
||||
is_idle "$(date +%s)" "${last:-}" "${execs:-}" "${tunnels:-}" "$claude" "$jobs" "$minutes"
|
||||
is_idle "$(date +%s)" "${last:-}" "$claude" "$jobs" "$minutes"
|
||||
}
|
||||
|
||||
# Say something once per change of state, not every interval.
|
||||
said=""
|
||||
say_once() {
|
||||
[ "$1" = "$said" ] && return 0
|
||||
said="$1"
|
||||
echo "triple-c-idle-watch: $1"
|
||||
}
|
||||
|
||||
# --check: quiet, and no unsaved work unless the WIP push would take it.
|
||||
check() {
|
||||
local dirty
|
||||
quiet || return 1
|
||||
dirty=$(unsaved_work) || return 1
|
||||
[ -z "$dirty" ] || [ "$wip_push" = 1 ]
|
||||
}
|
||||
|
||||
case "$minutes" in
|
||||
@@ -127,18 +177,44 @@ case "$signal_pid" in
|
||||
''|*[!0-9]*|0|1) echo "triple-c-idle-watch: TRIPLEC_IDLE_SIGNAL_PID must be the entrypoint's PID" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
push_failures=0
|
||||
next_push_at=0
|
||||
while :; do
|
||||
sleep "$interval"
|
||||
if check; then
|
||||
echo "triple-c-idle-watch: idle for ${minutes} minutes — stopping the workspace"
|
||||
mkdir -p "$(dirname "$reason_file")" 2>/dev/null
|
||||
# A pushed/discard marker means the app's stop guard has decided and
|
||||
# its stop is under way: keep that decision rather than overwrite it.
|
||||
case "$(cat "$reason_file" 2>/dev/null)" in
|
||||
pushed|discard) ;;
|
||||
*) printf 'idle\n' > "$reason_file" ;;
|
||||
esac
|
||||
kill -TERM "$signal_pid"
|
||||
exit 0
|
||||
if ! quiet; then
|
||||
said=""
|
||||
continue
|
||||
fi
|
||||
if ! dirty=$(unsaved_work); then
|
||||
say_once "idle, but the repositories' state cannot be read — not stopping"
|
||||
continue
|
||||
fi
|
||||
if [ -n "$dirty" ]; then
|
||||
folders=$(printf '%s' "$dirty" | paste -sd, -)
|
||||
if [ "$wip_push" != 1 ]; then
|
||||
say_once "idle, but $folders has unsaved work and the WIP push is off — not stopping"
|
||||
continue
|
||||
fi
|
||||
[ "$(date +%s)" -ge "$next_push_at" ] || continue
|
||||
echo "triple-c-idle-watch: idle — pushing work in progress ($folders) before stopping..."
|
||||
if ! as_user timeout -k 5 "$wip_timeout" "$wip_bin" --reason idle; then
|
||||
push_failures=$((push_failures + 1))
|
||||
wait_s=$((interval << (push_failures < 10 ? push_failures : 10)))
|
||||
[ "$wait_s" -le "$backoff_max" ] || wait_s=$backoff_max
|
||||
next_push_at=$(( $(date +%s) + wait_s ))
|
||||
said=""
|
||||
echo "triple-c-idle-watch: the WIP push failed — staying up; retrying in ${wait_s}s"
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
echo "triple-c-idle-watch: idle for ${minutes} minutes — stopping the workspace"
|
||||
mkdir -p "$(dirname "$reason_file")" 2>/dev/null
|
||||
# A pushed/discard marker means the app's stop guard has decided and
|
||||
# its stop is under way: keep that decision rather than overwrite it.
|
||||
case "$(cat "$reason_file" 2>/dev/null)" in
|
||||
pushed|discard) ;;
|
||||
*) printf 'idle\n' > "$reason_file" ;;
|
||||
esac
|
||||
kill -TERM "$signal_pid"
|
||||
exit 0
|
||||
done
|
||||
@@ -37,6 +37,11 @@ has a quirk the app relies on, the agent reproduces it, and this document names
|
||||
|
||||
- **Every request** needs `Authorization: Bearer <token>`. A missing or wrong token gets `401`
|
||||
with an empty body. The comparison is constant-time.
|
||||
- **Background requests** carry `X-Triple-C-Background: 1` (exactly `1`; any other value is an
|
||||
ordinary request). They are served like any other, but neither the request nor the bytes of an
|
||||
attach or tunnel it opens count as activity (see `GET /v1/activity`). The app sends it on polls
|
||||
no person is behind — today the auth bridge's `/proc/net/tcp` read every 2 s
|
||||
(`ContainerTarget::exec_oneshot_background`).
|
||||
- **Errors** are `4xx`/`5xx` with body `{"error": "<message>"}`, Content-Type `application/json`.
|
||||
- **JSON** is UTF-8. Raw bytes inside JSON are standard base64 with padding.
|
||||
- **Users** are names resolved through `/etc/passwd` and `/etc/group` in the container. An exec
|
||||
@@ -121,14 +126,19 @@ When either side ends, the other is closed.
|
||||
|
||||
### `GET /v1/activity`
|
||||
`200 {"last_activity_unix": <int>, "active_execs": <int>, "active_tunnels": <int>}`.
|
||||
"Activity" means any request other than `health` and `activity`, or any byte through an attach or
|
||||
tunnel. This is used by idle auto-stop later.
|
||||
"Activity" means any request other than `health`, `activity` and background requests, or any byte
|
||||
(either direction) through an attach or tunnel that was not opened by a background request.
|
||||
`last_activity_unix` is the input to AWS idle auto-stop (`container/triple-c-idle-watch`), which
|
||||
does **not** consult the two counters: an attach or tunnel that is open but silent ages like no
|
||||
session at all, so an open terminal tab doesn't keep a workspace up by itself (ruling R11). The
|
||||
counters stay for diagnostics.
|
||||
|
||||
## Client mapping (`host::ContainerTarget::Agent`)
|
||||
|
||||
| ContainerTarget | Agent call |
|
||||
|---|---|
|
||||
| `exec_oneshot*` (all variants) | `POST /v1/exec`, with `limit` = the variant's limit (`MAX_ONESHOT_OUTPUT` or explicit) |
|
||||
| `exec_oneshot_background` | `POST /v1/exec` with `X-Triple-C-Background: 1` (Docker: same as `exec_oneshot_limited`) |
|
||||
| `exec_detached` | `POST /v1/exec/detached` |
|
||||
| `attach` / `attach_exec` | `GET /v1/attach`; `input` is an `AsyncWrite` whose shutdown sends `close_stdin` |
|
||||
| `wait_exec_exit` | poll `GET /v1/exec/{id}` (same budget as the Docker version: 200 × 25 ms, shared constants in `docker/exec.rs`) |
|
||||
|
||||
Reference in new issue
Block a user