Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
34df1fd
feat(node): add per-IP write-surface rate brake and apply to write_ro…
beardthelion Jul 13, 2026
74e05be
feat(node): extend the per-IP write brake to the remaining write sinks
beardthelion Jul 13, 2026
6fded6e
test(node): adversarial TrustedProxy verification through the write b…
beardthelion Jul 13, 2026
e6324d2
feat(node): purge-spam admin subcommand for the empty-burst cleanup
beardthelion Jul 13, 2026
285d7c7
fix(review): make purge-spam empty-check reject git-discovery reads
beardthelion Jul 13, 2026
090019d
fix(review): normalization-consistent purge, brake helper, CLI + cove…
beardthelion Jul 13, 2026
dfd4f6c
test(review): close the reasoned-not-run gaps by execution
beardthelion Jul 13, 2026
0135419
fix(node): reject path-traversal repo names in purge-spam before remo…
beardthelion Jul 15, 2026
a0fcbb0
fix(node): delete child rows transactionally in delete_repo_by_id
beardthelion Jul 15, 2026
fde9cfe
fix(node): reap write_rate_limiter in the periodic cleanup loop
beardthelion Jul 15, 2026
15522d5
fix(node): hold the per-repo advisory lock across purge recheck+delete
beardthelion Jul 15, 2026
1fcca0d
fix(node): count purge-spam disk-removal failures separately from del…
beardthelion Jul 15, 2026
d9eebd2
fix(node): warn on unparseable rate-limit env vars instead of silentl…
beardthelion Jul 15, 2026
6325402
docs(node): document GITLAWB_IPFS_API/TIGRIS_BUCKET/METRICS_ADDR/SHUT…
beardthelion Jul 15, 2026
bfbe502
test(node): exercise the dry-run guard with a real on-disk candidate …
beardthelion Jul 15, 2026
cdb102e
style(node): cargo fmt for the #196 fix set
beardthelion Jul 15, 2026
4df79f2
fix(node): pin the writer's advisory-lock connection in RepoWriteGuard
beardthelion Jul 15, 2026
68c1f5c
refactor(node): introduce ObjectStore trait seam over TigrisClient
beardthelion Jul 15, 2026
3c1ceb8
fix(node): make purge-spam Tigris-authoritative and archive-deleting
beardthelion Jul 15, 2026
cf669bb
fix(review): don't hold/leak the pool connection in acquire_write
beardthelion Jul 15, 2026
dde5ea9
fix(node): make advisory-lock guards drop-safe and reorder acquire_write
beardthelion Jul 16, 2026
b94d440
fix(node): complete a fully-received push after client disconnect
beardthelion Jul 16, 2026
e4c4161
fix(node): serialize archive uploads under the per-repo advisory lock
beardthelion Jul 16, 2026
6ba698c
fix(node): let purge-spam reach repos that exist only as archives
beardthelion Jul 16, 2026
9f7757c
refactor(node): dedup limiter setup + write-brake test driver; fix .e…
beardthelion Jul 16, 2026
2a78524
docs(node): drop the .env.example shutdown-grace entry #196 added (#196)
beardthelion Jul 19, 2026
c4b337b
fix(node): give advisory-lock guards a dedicated pool and bound the r…
beardthelion Jul 19, 2026
4934646
fix(node): advertise a window-derived Retry-After on rate-limit 429s …
beardthelion Jul 19, 2026
0c279c9
fix(node): skip slug-scoped purge cascade when a mirror row shares th…
beardthelion Jul 19, 2026
86a8228
fix(node): fail closed classifying the purge target directory (#196)
beardthelion Jul 20, 2026
bf2a54e
fix(node): run the push completion tail in the disconnect-surviving t…
beardthelion Jul 20, 2026
c24b541
fix(node): tombstone bounties when their repo is purged (#196)
beardthelion Jul 20, 2026
3baa9ed
fix(node): serialize create_repo against the purge advisory lock (#196)
beardthelion Jul 20, 2026
9916bca
test(node): prove purge deletes at MAX_CONNECTIONS=1 with the split p…
beardthelion Jul 20, 2026
8f3d643
fix(node): fail the push when the durable upload times out, don't 200…
beardthelion Jul 20, 2026
d1e596e
fix(node): tombstone bounties under both owner forms on purge (#196)
beardthelion Jul 20, 2026
ce5dcc3
fix(node): fail closed on a symlink at the purge target (#196)
beardthelion Jul 20, 2026
7dc7be2
fix(node): retry-after on the push-advert 429, and create_repo locks …
beardthelion Jul 20, 2026
d2ba14e
fix(node): correct the create-pool and bounty-tombstone remediations …
beardthelion Jul 20, 2026
5a46ef6
fix(node): close the durable-upload data-loss class on every write pa…
beardthelion Jul 20, 2026
2fa9fa3
chore: merge main (iCaptcha PoW + gl retry tests) into feat/write-sin…
beardthelion Jul 21, 2026
16517f8
refactor(node): route the per-DID 429 through the shared too_many_req…
beardthelion Jul 21, 2026
ba572b3
fix(node): init's background upload waits out the creator's advisory …
beardthelion Jul 21, 2026
859240b
fix(node): roll back the local issue ref before unlock when the durab…
beardthelion Jul 21, 2026
c07435d
fix(node): fork publishes only after a durable upload, serialized on …
beardthelion Jul 21, 2026
2ad1c79
fix(node): read-path downloads publish under the purge lock, without …
beardthelion Jul 21, 2026
b2ca5a7
fix(node): bound every under-lock object-store call and dedup the upl…
beardthelion Jul 21, 2026
fa4322c
fix(node): harden the read-path download against cancellation, stale …
beardthelion Jul 21, 2026
c3d6e73
fix(node): keep the fork's unbounded work out of the target-lock span…
beardthelion Jul 21, 2026
03ef9b5
refactor(node): move read-path download coordination into a repo_stor…
beardthelion Jul 21, 2026
4408d27
fix(node): bound acquire_write's download and free the download-map e…
beardthelion Jul 21, 2026
a12f21a
fix(node): roll back the fork mirror and archive on late clone/insert…
beardthelion Jul 21, 2026
556aa31
fix(node): serialize repo purge cascade with mirror ingest via adviso…
beardthelion Jul 22, 2026
1d8c281
fix(node): roll back local ref on failed durable upload (close/merge/…
beardthelion Jul 22, 2026
1d0d3d2
fix(node): tie cancelled cold-download cleanup to blocking extraction
beardthelion Jul 22, 2026
03cd81e
chore(node): fmt + clippy cleanup for the #196 fixes
beardthelion Jul 22, 2026
9152178
fix(node): never let a failed ref snapshot become a delete-all rollba…
beardthelion Jul 22, 2026
296704f
fix(node): slug-lock every peer-ingest writer and drive the real inge…
beardthelion Jul 22, 2026
1e79ae5
fix(node): own cold-download cleanup in a spawned task so handler can…
beardthelion Jul 22, 2026
ce25bba
refactor(node): delegate issue ref helpers to the store ref primitives
beardthelion Jul 22, 2026
4329b2a
Merge origin/main into feat/write-sink-brake-coverage (reintegrate cu…
beardthelion Jul 22, 2026
d755180
fix(node): slug-lock arweave anchor writes; fail closed when the pre-…
beardthelion Jul 22, 2026
e6f4b2f
fix(node): close review residuals: coalesce cold downloads to one in-…
beardthelion Jul 22, 2026
1459cf2
Merge remote-tracking branch 'origin/main' into feat/write-sink-brake…
beardthelion Nov 11, 2026
da876e8
fix(node): re-apply create/fork purge serialization and restore brake…
beardthelion Nov 11, 2026
edfa6bb
fix(node): close review gaps in purge, locks, and fork cleanup
beardthelion Nov 11, 2026
96ed2b2
fix(node): subscriptions-only ws schema and unsettled-work purge guard
beardthelion Nov 11, 2026
082a37f
Merge remote-tracking branch 'origin/main' into feat/write-sink-brake…
beardthelion Nov 11, 2026
e9e86a1
fix(node): wire close_issue rollback, close purge symlink gap, correc…
beardthelion Nov 11, 2026
1187dca
fix(node): close purge/upload lifecycle gaps from review
beardthelion Nov 11, 2026
261f7ab
fix(node): merge rollback, honest create rollback, purge row recheck
beardthelion Nov 12, 2026
662b9a3
fix(node): probe purge slug liveness, gate issue write brake behind t…
beardthelion Nov 12, 2026
43d4f59
fix(node): close-issue rollback uses resolved ref, drop router brake …
beardthelion Nov 12, 2026
4b483a3
fix(node): close_issue spends neither bucket when either cap refuses,…
beardthelion Nov 12, 2026
11cadb9
fix(node): refund the write slot when the close cap refuses, send Ret…
beardthelion Nov 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
fix(node): refund the write slot when the close cap refuses, send Ret…
…ry-After on write-bucket 429s (#196)

close_issue debited the write bucket and then the close bucket, so a
concurrent close taking the last close slot between the probe and the
check left the write slot spent with no close done. Drop the probes:
debit write, then close, and refund the write slot when close refuses.

The in-handler write-bucket refusals in close_issue and
create_issue_comment now return AppError::RateLimited, which maps to 429
with a window-derived Retry-After like the router middleware's 429s. The
close-cap-only refusal keeps its plain 429.
  • Loading branch information
beardthelion committed Nov 12, 2026
commit 11cadb938260dc8d6ddd2310e3930014a4e5ddb0
138 changes: 121 additions & 17 deletions crates/gitlawb-node/src/api/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,9 @@ pub async fn create_issue_comment(
// placement close_issue uses for its brake). The route group carries no
// outer brake for exactly this reason.
if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) {
if !state.write_rate_limiter.check(&key).await {
if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await {
tracing::warn!(repo = %repo, key = %key, "create_issue_comment rate limited");
return Err(AppError::TooManyRequests(
"rate limit exceeded — try again later".into(),
));
return Err(AppError::RateLimited(retry_after));
}
}

Expand Down Expand Up @@ -291,15 +289,18 @@ pub async fn close_issue(
// per-IP write brake — the route group deliberately carries no outer
// brake — and this route's own close budget.
//
// Decide on the non-consuming probe first, so a close refused by one
// cap spends nothing from the other bucket. The consuming checks run
// only once both buckets have room; a concurrent request landing in
// between can still fail one of them, which is a 429 like any other.
if state.write_rate_limiter.is_throttled(&key).await
|| state.close_issue_rate_limiter.is_throttled(&key).await
|| !state.write_rate_limiter.check(&key).await
|| !state.close_issue_rate_limiter.check(&key).await
{
// A close refused by either cap spends nothing from the other bucket.
// The write bucket is debited first, and refunded when the close cap
// then refuses, so the guarantee holds even when a concurrent close
// takes the last close slot between the two checks. A write-bucket
// refusal advertises its window's Retry-After; the close-cap refusal
// keeps the plain 429 it has always returned.
if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await {
tracing::warn!(repo = %repo, key = %key, "close_issue rate limited");
return Err(AppError::RateLimited(retry_after));
}
if !state.close_issue_rate_limiter.check(&key).await {
state.write_rate_limiter.refund(&key).await;
tracing::warn!(repo = %repo, key = %key, "close_issue rate limited");
return Err(AppError::TooManyRequests(
"rate limit exceeded — try again later".into(),
Expand Down Expand Up @@ -1374,17 +1375,120 @@ mod lock_pool_shed_tests {
crate::rate_limit::PeerAddr(Some(peer)),
)
.await;
assert!(
matches!(res, Err(AppError::TooManyRequests(_))),
"write cap exhausted must 429: {:?}",
res
let resp = res
.expect_err("write cap exhausted must refuse")
.into_response();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"write cap exhausted must 429"
);
assert!(
state.close_issue_rate_limiter.check(&key).await,
"a close refused by the write cap must leave the close bucket untouched"
);
}

/// 429 from the shared write bucket must advertise a window-derived
/// Retry-After, as the outer-middleware 429s on the other write routes do.
fn assert_429_with_window_retry_after(err: AppError, what: &str) {
let resp = err.into_response();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"{what}: an exhausted write bucket must 429"
);
let secs: u64 = resp
.headers()
.get("retry-after")
.unwrap_or_else(|| panic!("{what}: the write-bucket 429 must carry retry-after"))
.to_str()
.unwrap()
.parse()
.expect("retry-after must be integer seconds");
assert!(
(1..=3600).contains(&secs),
"{what}: retry-after {secs}s must fall inside the 3600s window, not a constant"
);
}

#[sqlx::test]
async fn close_issue_write_cap_429_carries_retry_after(pool: PgPool) {
use std::net::SocketAddr;
use std::time::Duration;

let owner = "did:key:zCLOSERETRYOWNERAAAAAAAAAAAAAAAAAAAAAA";
let mut state = crate::test_support::test_state(pool).await;
state.write_rate_limiter =
crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600));
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
state
.db
.create_repo(&seed_repo(owner, "retry-close"))
.await
.expect("seed repo");

let peer: SocketAddr = "203.0.113.61:7000".parse().unwrap();
assert!(state.write_rate_limiter.check(&peer.ip().to_string()).await);

let res = close_issue(
State(state),
Extension(AuthenticatedDid(owner.to_string())),
Path((
owner.to_string(),
"retry-close".to_string(),
"1".to_string(),
)),
axum::http::HeaderMap::new(),
crate::rate_limit::PeerAddr(Some(peer)),
)
.await;
assert_429_with_window_retry_after(
res.expect_err("write cap exhausted must refuse"),
"close_issue",
);
}

#[sqlx::test]
async fn create_issue_comment_write_cap_429_carries_retry_after(pool: PgPool) {
use std::net::SocketAddr;
use std::time::Duration;

let owner = "did:key:zCOMMENTRETRYOWNERAAAAAAAAAAAAAAAAAAAA";
let mut state = crate::test_support::test_state(pool).await;
state.write_rate_limiter =
crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600));
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
state
.db
.create_repo(&seed_repo(owner, "retry-comment"))
.await
.expect("seed repo");

let peer: SocketAddr = "203.0.113.62:7000".parse().unwrap();
assert!(state.write_rate_limiter.check(&peer.ip().to_string()).await);

let res = create_issue_comment(
State(state),
Extension(AuthenticatedDid(owner.to_string())),
Path((
owner.to_string(),
"retry-comment".to_string(),
"1".to_string(),
)),
axum::http::HeaderMap::new(),
crate::rate_limit::PeerAddr(Some(peer)),
Json(CreateIssueCommentRequest {
body: "x".to_string(),
}),
)
.await;
assert_429_with_window_retry_after(
res.expect_err("write cap exhausted must refuse"),
"create_issue_comment",
);
}

/// close_issue and receive-pack must not share one per-IP bucket.
#[sqlx::test]
async fn close_issue_rate_limit_does_not_drain_push_bucket(pool: PgPool) {
Expand Down
18 changes: 18 additions & 0 deletions crates/gitlawb-node/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ pub enum AppError {
#[error("too many requests: {0}")]
TooManyRequests(String),

/// A 429 from a per-IP limiter that knows when its window frees a slot, so
/// the response advertises that delay as `Retry-After` the way the router
/// middleware's 429s do. `TooManyRequests` stays for limiters that have no
/// such delay to give.
#[error("too many requests: retry in {}s", .0.as_secs())]
RateLimited(std::time::Duration),

#[error("incomplete: {0}")]
Incomplete(String),

Expand Down Expand Up @@ -205,6 +212,11 @@ impl IntoResponse for AppError {
AppError::TooManyRequests(msg) => {
(StatusCode::TOO_MANY_REQUESTS, "rate_limited", msg.clone())
}
AppError::RateLimited(_) => (
StatusCode::TOO_MANY_REQUESTS,
"rate_limited",
crate::rate_limit::RATE_LIMIT_MESSAGE.to_string(),
),
AppError::Incomplete(msg) => {
(StatusCode::UNPROCESSABLE_ENTITY, "incomplete", msg.clone())
}
Expand Down Expand Up @@ -318,6 +330,12 @@ impl IntoResponse for AppError {
axum::http::HeaderValue::from_static("1"),
);
}
if let AppError::RateLimited(retry_after) = &self {
resp.headers_mut().insert(
axum::http::header::RETRY_AFTER,
axum::http::HeaderValue::from(retry_after.as_secs().max(1)),
);
}
resp
}
}
Expand Down
41 changes: 41 additions & 0 deletions crates/gitlawb-node/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,22 @@ impl RateLimiter {
None
}

/// Give back one slot a prior [`check`](Self::check) took for `key`, for a
/// caller that debits two buckets and must undo the first when the second
/// refuses. Drops the newest timestamp: the count is what the cap reads, so
/// that is equivalent to dropping the caller's own even if another request
/// landed in between. An unknown key is a no-op, and a key left with no
/// timestamps is removed so a refund never holds a map entry.
pub(crate) async fn refund(&self, key: &str) {
let mut state = self.state.lock().await;
if let Some(window) = state.get_mut(key) {
window.timestamps.pop();
if window.timestamps.is_empty() {
state.remove(key);
}
}
}

/// Non-consuming check: is this key ALREADY at its limit for the current window?
/// Unlike [`check`], it records nothing and never inserts a new key — used to shed
/// expensive preparatory work (e.g. the `/ipfs/{cid}` legacy scan's O(repos) DB
Expand Down Expand Up @@ -1117,4 +1133,29 @@ mod tests {
"with 99s of a 100s window elapsed, the remaining delay is ~1s, got {retry}"
);
}

/// `refund` gives back exactly one slot a prior `check` took, so a caller
/// that debits two buckets can undo the first when the second refuses.
#[tokio::test]
async fn refund_returns_one_slot_and_is_a_no_op_for_an_unknown_key() {
let limiter = RateLimiter::new(2, Duration::from_secs(60));
assert!(limiter.check("k").await);
assert!(limiter.check("k").await);
assert!(!limiter.check("k").await, "bucket is full");

limiter.refund("k").await;
assert!(limiter.check("k").await, "one slot came back");
assert!(!limiter.check("k").await, "and only one");

// An unknown key must neither panic nor create an entry.
limiter.refund("never-seen").await;
assert!(limiter.state.lock().await.get("never-seen").is_none());

// Refunding the only slot drops the key, so a refunded key does not
// hold a map entry (the limiter's key cap bounds its own state).
let single = RateLimiter::new(1, Duration::from_secs(60));
assert!(single.check("solo").await);
single.refund("solo").await;
assert!(single.state.lock().await.get("solo").is_none());
}
}
Loading