Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
51 changes: 37 additions & 14 deletions crates/api/src/web/discord_retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,44 @@ mod tests {
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
store_deadlines(
&db,
r#"{"g:7":1710000000000,"t:7":1710000001000,"token":1710000001000,"nope":5,"m:bad":9}"#.into(),
)
.await
.unwrap();
});
let loaded = load_deadlines_sync(&Db::open(&path, 2).unwrap()).unwrap();
assert_eq!(loaded.get("g:7"), Some(&1_710_000_000_000));
assert_eq!(loaded.get("t:7"), Some(&1_710_000_001_000));
assert!(!loaded.contains_key("token"));
assert!(!loaded.contains_key("nope"));
assert!(!loaded.contains_key("m:bad"));
for length in 0..=21 {
let id = "7".repeat(length);
let keys = [
format!("g:{id}"),
format!("t:{id}"),
format!("m:{id}"),
format!("r:{id}:9"),
format!("r:9:{id}"),
];
for millis in [i64::MIN, 0, 1, 1_710_000_000_000, i64::MAX] {
let mut record = serde_json::json!({"global": millis, "token": 5, "m:bad": 9});
let mut expected = BTreeMap::new();
if millis > 0 {
expected.insert("global".to_owned(), millis);
}
for key in keys.iter() {
record[key] = millis.into();
if (1..=20).contains(&length) && millis > 0 {
expected.insert(key.clone(), millis);
}
}
runtime
.block_on(store_deadlines(&db, record.to_string()))
.unwrap();
assert_eq!(
load_deadlines_sync(&db).unwrap(),
expected,
"id length {length}, deadline {millis}"
);
}
}
drop(db);
let reopened = Db::open(&path, 2).unwrap();
assert_eq!(
load_deadlines_sync(&reopened).unwrap(),
BTreeMap::from([("global".to_owned(), i64::MAX)])
);
drop(reopened);
for suffix in ["", "-wal", "-shm"] {
let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
}
Expand Down
37 changes: 28 additions & 9 deletions crates/api/src/web/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1404,15 +1404,34 @@ mod tests {

#[tokio::test(start_paused = true)]
async fn discord_retry_after_honors_header_and_json_seconds() {
assert_eq!(discord_retry_after(Some("2"), b"{}").as_secs(), 2);
assert_eq!(
discord_retry_after(Some("2"), br#"{"retry_after":4.5}"#).as_millis(),
4500
);
assert_eq!(discord_retry_after(None, b"{}").as_secs(), 1);
assert_eq!(discord_retry_after(Some("0"), b"{}").as_secs(), 1);
assert_eq!(discord_retry_after(Some("120"), b"{}").as_secs(), 120);
assert_eq!(discord_retry_after(Some("90000"), b"{}").as_secs(), 90000);
// Eighth-seconds are exactly representable on the wire. Compute the
// expected wait in integer milliseconds independently of the parser.
let waits = [
None,
Some(0u32),
Some(4),
Some(8),
Some(16),
Some(36),
Some(960),
Some(720_000),
];
for header in waits {
for body in waits {
let header_value = header.map(|n| (f64::from(n) / 8.0).to_string());
let body_value =
serde_json::json!({"retry_after": body.map(|n| f64::from(n) / 8.0)});
let expected_ms = header.into_iter().chain(body).max().unwrap_or(0).max(8) * 125;
assert_eq!(
discord_retry_after(
header_value.as_deref(),
&serde_json::to_vec(&body_value).unwrap()
),
Duration::from_millis(u64::from(expected_ms))
);
}
}
assert_eq!(discord_retry_after(None, b"{}"), Duration::from_secs(1));
for invalid in ["-1", "NaN", "inf", "-inf"] {
assert_eq!(
discord_retry_after(Some(invalid), b"{}"),
Expand Down
9 changes: 8 additions & 1 deletion crates/bot/src/commands/userinfo/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3202,7 +3202,14 @@ impl StatsDispatch {
"data": {"id": "3", "name": name, "type": 1, "options": options, "resolved": resolved}
}))
.unwrap();
crate::commands::handle_interaction(&self.app, &self.ctx, interaction).await;
// Several fixture helpers await this dispatch. Keep its future on the heap
// so their nested debug frames fit on the normal Rust test thread.
Box::pin(crate::commands::handle_interaction(
&self.app,
&self.ctx,
interaction,
))
.await;
}

/// Reply bodies sent to Discord (non-empty content or embeds), in order,
Expand Down
18 changes: 12 additions & 6 deletions crates/bot/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5426,12 +5426,18 @@ BEGIN SELECT RAISE(ABORT, 'fixture pacing failure'); END;",

#[test]
fn deadline_millis_clamps_to_i64() {
assert_eq!(member_sync_deadline_ms(10, Duration::MAX), i64::MAX);
assert_eq!(member_sync_deadline_ms(10, Duration::from_millis(5)), 15);
assert_eq!(
member_sync_deadline_ms(i64::MAX, Duration::from_millis(1)),
i64::MAX
);
let max = i64::MAX;
for now in [0, 10, max / 2, max - 1, max] {
let room = (max - now) as u64;
for millis in [0, 1, 5, room.saturating_sub(1), room, room + 1, u64::MAX] {
for nanos in [0, 999_999] {
let wait = Duration::from_millis(millis) + Duration::from_nanos(nanos);
let expected = (u128::from(now as u64) + u128::from(millis)).min(max as u128);
assert_eq!(member_sync_deadline_ms(now, wait) as u128, expected);
}
}
assert_eq!(member_sync_deadline_ms(now, Duration::MAX), max);
}
}

const TOKEN_A: &str = "synthetic_token_r4303412353";
Expand Down
63 changes: 34 additions & 29 deletions crates/bot/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -850,35 +850,40 @@ mod tests {

#[test]
fn planned_stop_needs_every_ready_shard_connected() {
use serenity::gateway::ConnectionStage::{Connected, Connecting, Resuming};
let runners = |stages: &[(u32, serenity::gateway::ConnectionStage)]| {
stages
.iter()
.copied()
.collect::<std::collections::HashMap<_, _>>()
};
assert!(super::gateway_covered(&runners(&[(0, Connected)]), &[0]));
assert!(
!super::gateway_covered(&runners(&[(0, Connected)]), &[]),
"never reached Ready"
);
assert!(
!super::gateway_covered(&runners(&[]), &[0]),
"restarting shard has no runner"
);
assert!(!super::gateway_covered(&runners(&[(0, Resuming)]), &[0]));
assert!(!super::gateway_covered(
&runners(&[(0, Connected), (1, Connecting)]),
&[0, 1]
));
assert!(
!super::gateway_covered(&runners(&[(1, Connected)]), &[0]),
"another shard's runner cannot stand in for a Ready shard"
);
assert!(super::gateway_covered(
&runners(&[(0, Connected), (1, Connecting)]),
&[0]
));
use serenity::gateway::ConnectionStage::*;
let stages = [
None,
Some(Connected),
Some(Connecting),
Some(Disconnected),
Some(Handshake),
Some(Identifying),
Some(Resuming),
];
for ready_mask in 0..8 {
let ready = (0..3)
.filter(|shard| ready_mask & (1 << shard) != 0)
.collect::<Vec<_>>();
for mut layout in 0..stages.len().pow(3) {
let mut runners = std::collections::HashMap::new();
let mut connected_mask = 0;
for shard in 0..3 {
if let Some(stage) = stages[layout % stages.len()] {
runners.insert(shard, stage);
if stage == Connected {
connected_mask |= 1 << shard;
}
}
layout /= stages.len();
}
let expected = ready_mask != 0 && ready_mask & !connected_mask == 0;
assert_eq!(
super::gateway_covered(&runners, &ready),
expected,
"ready {ready:?}, runners {runners:?}"
);
}
}
}

use super::*;
Expand Down
52 changes: 52 additions & 0 deletions crates/runtime/src/cgroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2734,6 +2734,58 @@ mod tests {
}
}

#[test]
fn memory_reading_agrees_across_limit_and_stat_boundaries() {
for (v1, usage, limit_file) in [
(true, "memory.usage_in_bytes", "memory.limit_in_bytes"),
(false, "memory.current", "memory.max"),
] {
for (stat, expected_usage) in [
(None, Some((10, MemorySource::CgroupUsage))),
(Some("inactive_file 4"), Some((6, MemorySource::CgroupStat))),
(
Some("inactive_file 11"),
Some((0, MemorySource::CgroupStat)),
),
(Some("file 100"), None),
] {
let tree = temp_tree();
write_files(&tree.path, &[(usage, "10")]);
if let Some(stat) = stat {
write_files(&tree.path, &[("memory.stat", stat)]);
}
for limit in [
None,
Some(0),
Some(63),
Some(64),
Some(65),
Some((1u64 << 62) - 1),
Some(1 << 62),
Some(u64::MAX),
] {
if let Some(limit) = limit {
write_files(&tree.path, &[(limit_file, &limit.to_string())]);
}
for host in [None, Some(64)] {
let cap =
limit.filter(|&n| !v1 || (n < 1 << 62 && host.is_none_or(|h| n < h)));
let expected = expected_usage.map(|(program_bytes, source)| MemoryUse {
program_bytes,
source,
limit: cap.map_or(MemoryLimit::Unlimited, MemoryLimit::Bytes),
});
assert_eq!(
read_memory(&tree.path, || host),
expected,
"v1 {v1}, limit {limit:?}, host {host:?}, stat {stat:?}"
);
}
}
}
}
}

// A v1 memory controller mounted at `cgroup_dir`, with an optional
// host `MemTotal` line, as read through the production /proc layout.
fn v1_proc_fixture(cgroup_dir: &Path, meminfo: Option<&str>) -> TempTree {
Expand Down
56 changes: 31 additions & 25 deletions crates/runtime/src/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,32 +409,38 @@ mod tests {
#[tokio::test]
async fn health_request_line_can_span_multiple_reads() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let mut client = TcpStream::connect(listener.local_addr().unwrap())
.await
.unwrap();
let (server, _) = listener.accept().await.unwrap();
client.write_all(b"GET ").await.unwrap();
server.readable().await.unwrap();
server.writable().await.unwrap();

let response = super::answer_connection(server);
tokio::pin!(response);
// Poll the handler with only the first fragment available.
tokio::select! {
biased;
result = &mut response => panic!("answered before the request line was complete: {result:?}"),
() = std::future::ready(()) => {}
}
for (method, body) in [("GET", "ok"), ("HEAD", "")] {
let line = format!("{method} /health HTTP/1.1\r\n");
for split in 1..line.len() {
let mut client = TcpStream::connect(listener.local_addr().unwrap())
.await
.unwrap();
let (server, _) = listener.accept().await.unwrap();
client.write_all(&line.as_bytes()[..split]).await.unwrap();
server.readable().await.unwrap();
server.writable().await.unwrap();

let response = super::answer_connection(server);
tokio::pin!(response);
// Poll the handler with only the first fragment available.
tokio::select! {
biased;
result = &mut response => panic!("answered before the request line was complete: {result:?}"),
() = std::future::ready(()) => {}
}

client
.write_all(b"/health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
.await
.unwrap();
response.await.unwrap();
let mut text = String::new();
client.read_to_string(&mut text).await.unwrap();
assert!(text.starts_with("HTTP/1.1 200 OK"), "unexpected: {text}");
assert!(text.ends_with("\r\n\r\nok"), "unexpected: {text}");
client.write_all(&line.as_bytes()[split..]).await.unwrap();
response.await.unwrap();
let mut text = String::new();
client.read_to_string(&mut text).await.unwrap();
assert!(text.starts_with("HTTP/1.1 200 OK"), "unexpected: {text}");
assert_eq!(
text.split_once("\r\n\r\n").unwrap().1,
body,
"split {split}"
);
}
}
}

// Paused time fires the sleep below only after every ready accept and
Expand Down
2 changes: 1 addition & 1 deletion docs/BUNNY-UPDATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ the new base image's baked bot before the API. On a managed installation, a
same-ABI base-image swap restores the pinned bot and leaves the core schema
unchanged.

For the guild schema 23 → 24 and 24 → 25 upgrades, use a revision-49 or newer
For the guild schema 23 → 24, 24 → 25, and 25 → 26 upgrades, use a revision-49 or newer
bot launcher. Apply one guild schema step at a time.
If the running bot launcher is older, check the matching release in
Administration and use **Advanced launcher controls** to update the bot
Expand Down
7 changes: 4 additions & 3 deletions docs/DATABASE-BASELINE.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ across guilds ([MEMBERS.md](MEMBERS.md)).

## Separate guild-store family

The `GuildDataStore` library initializes/verifies `jmodguard-guild-1`, version 25,
using `migrations/guild/0016_baseline.sql` through `0024_deletion_requests.sql`.
The `GuildDataStore` library initializes/verifies `jmodguard-guild-1`, version 26,
using `migrations/guild/0016_baseline.sql` through `0025_subject_case_dates.sql`.
The v0.2.0 baseline includes the version 16 payload format with optional immutable
ban attempt tags, and the version 17 `guild_member_pending_rejoin_notes` table for
durable member-rejoin log delivery.
Expand All @@ -142,12 +142,13 @@ Version 25 adds [deletion requests](DELETION-REQUESTS.md) and the
transaction-scoped grants that let an erasure redact one person's data from
cases, case history, evidence and unresolved audits. Existing rows are not
changed. For stores on schema 24, use the same paired upgrade.
Version 26 indexes live cases by subject, date and case ID for chronological member case lists.
Earlier binaries must not open stores that use a newer guild schema. This separate
database holds identity, placement bindings, receipts, membership/log-channel
settings, selected cases, history, sources, evidence ownership, Bunny transfer
progress, tenant settings, bounded latest-message snapshots and the bounded
[member directory](MEMBERS.md). Initialize verifies and upgrades a matching earlier
store atomically at bot startup. Ordinary opens require version 25. See
store atomically at bot startup. Ordinary opens require version 26. See
[tenant runtime](TENANT-RUNTIME.md). Core is at schema 35. Each opener refuses
the other family. No records are moved by startup.
Guild migration 0009 adds bounded latest-message snapshots with fixed 24-hour expiry
Expand Down
7 changes: 4 additions & 3 deletions docs/GUILD-STORES.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pairs fail instead of falling back to a local file. Synchronous open/initializat
on a startup or blocking worker, like core database opening.

The separate `jmodguard-guild-1` family starts at the v0.2.0 baseline (schema
version 17) and applies migrations 0017–0024 to reach version 25. The baseline
version 17) and applies migrations 0017–0025 to reach version 26. The baseline
includes the earlier schema changes described below. Version1 introduced an immutable singleton identity (family, store ID,
shared/dedicated owner), immutable initial
guild/revision bindings and mutation receipts. Version2 adds captured membership and
Expand Down Expand Up @@ -103,12 +103,13 @@ Version 25 adds `guild_deletion_requests` and `guild_erasure_grants` for
[deletion requests](DELETION-REQUESTS.md), and lets a granted transaction redact
one person's data from otherwise immutable cases, history, evidence and
unresolved audits. Use the same paired upgrade for stores on schema 24.
Version 26 adds a chronological case index for each subject within a membership.
Guild-store migrations run separately from core bootstrap.

| Operation | Contract |
|---|---|
| `initialize` | At bot startup, initialize an empty database atomically, upgrade a matching store at version 17 or later to schema 25, or verify a current identity. Refuse core, foreign, unmarked, newer or mismatched stores without adopting them. |
| `open` | Verify the current schema 25 identity and ownership. Ordinary runtime opens create no schema or binding. |
| `initialize` | At bot startup, initialize an empty database atomically, upgrade a matching store at version 17 or later to schema 26, or verify a current identity. Refuse core, foreign, unmarked, newer or mismatched stores without adopting them. |
| `open` | Verify the current schema 26 identity and ownership. Ordinary runtime opens create no schema or binding. |
| `bind_initial_placement` | Verify identity and install the catalog's initial guild/revision in one primary transaction. Matching retries write nothing; a different revision or dedicated owner conflicts. |
| `verify_placement` | Check identity, ownership and the exact stored guild/revision in one primary snapshot; missing bindings fail. This is not authorization for a later separate data operation. |

Expand Down
Loading
Loading