diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 330ad3c..5ccd2cf 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -8,6 +8,12 @@ # Use the mutants profile (no debug symbols) for faster builds. profile = "mutants" +# Do not copy gitignored files into the build directories. The default is +# off since cargo-mutants 25.0.2. Without this, each job copies +# .claude/worktrees, with a target directory for each worktree, and the disk +# fills. https://mutants.rs/build-dirs.html#gitignore +gitignore = true + # Skip doctests (none in this project, avoids discovery overhead). additional_cargo_test_args = ["--all-targets"] diff --git a/CLAUDE.md b/CLAUDE.md index fbe9b17..91f0b5c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,7 +88,7 @@ Do not simplify them. | `serenity` | Discord Gateway + REST client | | `serde` + `toml` | Config deserialization | | `tracing` + `tracing-subscriber` | Structured logging (with `env-filter` feature for `RUST_LOG`) | -| `chrono` | Timestamp handling (server-time in formatting) | +| `jiff` | Timestamp handling (the `IRCv3` `server-time` tag) | | `thiserror` | Derive macros for typed error enums in each module | | `anyhow` | Error propagation with context chains in the application/connection layer | | `rand` | Random jitter for reconnect backoff | diff --git a/Cargo.lock b/Cargo.lock index 4c67d2c..b0fec9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -299,12 +299,6 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" -[[package]] -name = "bytecount" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" - [[package]] name = "byteorder" version = "1.5.0" @@ -317,37 +311,6 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -[[package]] -name = "camino" -version = "1.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" -dependencies = [ - "serde_core", -] - -[[package]] -name = "cargo-platform" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo_metadata" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" -dependencies = [ - "camino", - "cargo-platform", - "semver", - "serde", - "serde_json", -] - [[package]] name = "cc" version = "1.5.1" @@ -484,21 +447,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - [[package]] name = "crypto-common" version = "0.1.7" @@ -657,8 +605,8 @@ name = "disirc" version = "0.1.0" dependencies = [ "anyhow", - "chrono", "hegeltest", + "jiff 1.0.2", "mutants", "rand 0.10.3", "reqwest 0.13.5", @@ -745,16 +693,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "error-chain" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" -dependencies = [ - "version_check", + "windows-sys 0.61.2", ] [[package]] @@ -809,9 +748,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -947,12 +886,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - [[package]] name = "h2" version = "0.4.19" @@ -1387,8 +1320,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" dependencies = [ "defmt", - "jiff-core", - "jiff-static", + "jiff-core 0.1.1", + "jiff-static 0.2.37", "jiff-tzdb-platform", "log", "portable-atomic", @@ -1397,6 +1330,20 @@ dependencies = [ "windows-link", ] +[[package]] +name = "jiff" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" +dependencies = [ + "jiff-core 1.0.1", + "jiff-static 1.0.2", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + [[package]] name = "jiff-core" version = "0.1.1" @@ -1407,18 +1354,39 @@ dependencies = [ "log", ] +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" dependencies = [ - "jiff-core", + "jiff-core 0.1.1", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "jiff-static" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" +dependencies = [ + "jiff-core 1.0.1", + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "jiff-tzdb" version = "0.1.8" @@ -1598,21 +1566,6 @@ dependencies = [ "unicase", ] -[[package]] -name = "mini-moka" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c325dfab65f261f386debee8b0969da215b3fa0037e74c8a1234db7ba986d803" -dependencies = [ - "crossbeam-channel", - "crossbeam-utils", - "dashmap", - "skeptic", - "smallvec", - "tagptr", - "triomphe", -] - [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1936,17 +1889,6 @@ dependencies = [ "prost", ] -[[package]] -name = "pulldown-cmark" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b" -dependencies = [ - "bitflags 2.13.2", - "memchr", - "unicase", -] - [[package]] name = "quinn" version = "0.11.12" @@ -2001,7 +1943,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2254,7 +2196,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2327,7 +2269,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2457,10 +2399,6 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] [[package]] name = "serde" @@ -2558,7 +2496,7 @@ dependencies = [ "hex", "indexmap 1.9.3", "indexmap 2.14.2", - "jiff", + "jiff 0.2.37", "schemars 0.9.0", "schemars 1.2.2", "serde_core", @@ -2590,7 +2528,6 @@ dependencies = [ "base64 0.22.1", "bitflags 2.13.2", "bytes", - "chrono", "command_attr", "dashmap", "flate2", @@ -2611,7 +2548,6 @@ dependencies = [ "tokio-tungstenite", "tracing", "typemap_rev", - "typesize", "url", "uwl", ] @@ -2674,21 +2610,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" -[[package]] -name = "skeptic" -version = "0.13.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8" -dependencies = [ - "bytecount", - "cargo_metadata", - "error-chain", - "glob", - "pulldown-cmark", - "tempfile", - "walkdir", -] - [[package]] name = "slab" version = "0.4.12" @@ -2832,12 +2753,6 @@ dependencies = [ "libc", ] -[[package]] -name = "tagptr" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" - [[package]] name = "tempfile" version = "3.27.0" @@ -2848,7 +2763,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3278,12 +3193,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "triomphe" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b40688ea6389c8171614b25491f71d4a27946e0c7ce2da1c6de27e25abf1a0ae" - [[package]] name = "try-lock" version = "0.2.5" @@ -3323,35 +3232,6 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "typesize" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a313188364f7e10138257cb288c64e9b0e282510abefc91c796799559fa14762" -dependencies = [ - "chrono", - "dashmap", - "hashbrown 0.14.5", - "mini-moka", - "parking_lot", - "secrecy", - "serde_json", - "time", - "typesize-derive", - "url", -] - -[[package]] -name = "typesize-derive" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "536b6812192bda8551cfa0e52524e328c6a951b48e66529ee4522d6c721243d6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "unicase" version = "2.9.0" @@ -3378,9 +3258,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -3582,7 +3462,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a9a3c16..ef16257 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,18 +19,31 @@ wiremock = "0.6" [dependencies] tokio = { version = "1", features = ["full"] } tokio-rustls = "0.26" -serenity = { version = "0.12", features = ["cache", "chrono", "client", "gateway", "model"] } +# The default features without "chrono" (unmaintained, RUSTSEC-2026-0543). +# Without it, serenity's Timestamp wraps time::OffsetDateTime. +serenity = { version = "0.12", default-features = false, features = [ + "builder", + "cache", + "client", + "framework", + "gateway", + "http", + "model", + "rustls_backend", + "standard_framework", + "utils", +] } toml = "1.0" serde = { version = "1", features = ["derive"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } -chrono = { version = "0.4", default-features = false, features = ["clock"] } thiserror = "2" anyhow = "1" rand = "0.10.0" serde_json = "1" unicode-segmentation = "1" mutants = "0.0.4" +jiff = { version = "1", default-features = false, features = ["std"] } [profile.mutants] inherits = "test" diff --git a/TODO.md b/TODO.md index 99f0384..1f6cbb1 100644 --- a/TODO.md +++ b/TODO.md @@ -163,7 +163,9 @@ mutants spec 02 had documented as equivalent. ignores eight of them; remove those ignores in the same change. serenity will not bump tungstenite on 0.12, because its errors are public API (serenity PR #3599). The `next` branch already uses - tokio-tungstenite 0.28. Expect API changes. + tokio-tungstenite 0.28. Expect API changes. The `next` branch also + uses `jiff` for `Timestamp`; remove `message_time` in + `src/discord/handler.rs` in the same change. ## Future features diff --git a/specs/02-irc-connection/spec.md b/specs/02-irc-connection/spec.md index 9baf2f4..cb72420 100644 --- a/specs/02-irc-connection/spec.md +++ b/specs/02-irc-connection/spec.md @@ -80,7 +80,7 @@ S2SEvent::MessageReceived { from_uid: String, target: String, // channel or UID text: String, - timestamp: Option>, // from @time= tag; None if absent + timestamp: Option, // from @time= tag; None if absent } S2SEvent::NoticeReceived { @@ -131,7 +131,7 @@ S2SCommand::SendMessage { from_uid: String, target: String, text: String, - timestamp: Option>, // emitted as @time= tag if MTAGS active + timestamp: Option, // emitted as @time= tag if MTAGS active } S2SCommand::SendNotice { @@ -304,7 +304,7 @@ When `MTAGS` is active, incoming messages may carry message tags. | Tag | Action | |-----|--------| -| `@time=` | Parsed as `DateTime`; placed in `S2SEvent::MessageReceived::timestamp` | +| `@time=` | Parsed as `jiff::Timestamp`; placed in `S2SEvent::MessageReceived::timestamp`. The parser accepts RFC 3339 and the wider grammar of `jiff::fmt::temporal` (for example basic format, a comma before the fraction, an offset of hours only, or a time zone annotation). An offset is required. A leap second (`:60`) becomes `:59`. A value that does not parse gives `None` | | `@msgid=` | Recorded for future edit/delete correlation; not forwarded to Discord in v1 | | `@account=` | Ignored; IRC account names are not mapped to Discord identities in v1 | | `@bot=` | Ignored | @@ -398,3 +398,4 @@ that distinguishes the two forms. - [UnrealIRCd Server Protocol — Introduction](https://www.unrealircd.org/docs/Server_protocol:Introduction) — accessed 2026-03-22 - [UnrealIRCd Server Protocol — UID command](https://www.unrealircd.org/docs/Server_protocol:UID_command) — accessed 2026-03-22 - [UnrealIRCd Server Protocol — SJOIN command](https://www.unrealircd.org/docs/Server_protocol:SJOIN_command) — accessed 2026-03-22 +- [jiff::fmt::temporal](https://docs.rs/jiff/1.0.2/jiff/fmt/temporal/index.html) — the grammar of `jiff::Timestamp`'s `FromStr` — accessed 2026-11-24 diff --git a/specs/05-formatting/TODO.md b/specs/05-formatting/TODO.md index 8acf421..4164211 100644 --- a/specs/05-formatting/TODO.md +++ b/specs/05-formatting/TODO.md @@ -7,4 +7,4 @@ Status: **Implemented** - [x] Discord→IRC: newline splitting, code block handling, length splitting at 400 bytes - [x] IRC→Discord: control character stripping/conversion (Unicode Cc category) - [x] IRC→Discord: `@nick` mention conversion, ping-fix zero-width space, length truncation at 2000 chars -- [x] `server-time` ISO 8601 timestamp formatting (chrono) + proptest suite across all transforms +- [x] `server-time` ISO 8601 timestamp formatting (jiff; chrono until 2026-11) + proptest suite across all transforms diff --git a/specs/05-formatting/spec.md b/specs/05-formatting/spec.md index a205ce5..d9fc165 100644 --- a/specs/05-formatting/spec.md +++ b/specs/05-formatting/spec.md @@ -104,7 +104,9 @@ When the uplink has negotiated `server-time`, outgoing `PRIVMSG` messages on the @time=2024-01-15T12:34:56.789Z : PRIVMSG #channel : ``` -Timestamps are formatted as ISO 8601 UTC (`YYYY-MM-DDTHH:MM:SS.mmmZ`). +Timestamps are formatted as ISO 8601 UTC (`YYYY-MM-DDTHH:MM:SS.mmmZ`). The bridge truncates the time to milliseconds. + +If `jiff::Timestamp` cannot represent the Discord timestamp, the bridge omits the tag. serenity 0.12 holds timestamps from -9999-01-01 to 9999-12-31. The range of `jiff::Timestamp` is about one day shorter at each end: -9999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z. ## References @@ -113,4 +115,5 @@ Timestamps are formatted as ISO 8601 UTC (`YYYY-MM-DDTHH:MM:SS.mmmZ`). - [discord/simple-markdown](https://github.com/discord/simple-markdown) — Discord's markdown parser (fork of Khan Academy simple-markdown) — accessed 2026-03-24 - [IRCv3 Message Tags specification](https://ircv3.net/specs/extensions/message-tags) — accessed 2026-03-22 - [IRCv3 server-time specification](https://ircv3.net/specs/extensions/server-time) — accessed 2026-03-22 +- [jiff::Timestamp (MIN, MAX)](https://docs.rs/jiff/1.0.2/jiff/struct.Timestamp.html) — accessed 2026-11-24 - [IRC formatting reference (modern.ircdocs.horse)](https://modern.ircdocs.horse/formatting) — accessed 2026-03-22 diff --git a/src/bridge/orchestrator.rs b/src/bridge/orchestrator.rs index b1acb3f..2743d76 100644 --- a/src/bridge/orchestrator.rs +++ b/src/bridge/orchestrator.rs @@ -409,7 +409,7 @@ impl BridgeState { author_display_name, content, attachments, - Some(*timestamp), + *timestamp, now_ts, &resolver, ); @@ -451,7 +451,7 @@ impl BridgeState { from_uid, target: target_uid, text, - timestamp: Some(*timestamp), + timestamp: *timestamp, }); } DmRouteResult::Error(msg) => { @@ -856,8 +856,7 @@ mod tests { author_display_name: "Alice".into(), content: "hello world".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts, ); @@ -1824,8 +1823,7 @@ mod tests { author_display_name: "Alice".into(), content: "hello".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts, ); @@ -1944,8 +1942,7 @@ mod tests { author_display_name: "Alice".into(), content: "still here".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts + 150, ); @@ -2032,8 +2029,7 @@ mod tests { author_display_name: "Alice".into(), content: "hi".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts, ); @@ -2492,8 +2488,7 @@ mod tests { author_display_name: "Alice".into(), content: "hello".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts + 10, ); @@ -2634,8 +2629,7 @@ mod tests { author_display_name: "Alice".into(), content: "hello".into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts + 10, ); @@ -2781,8 +2775,7 @@ mod tests { author_name: "alice".into(), content: "hello bridge".into(), referenced_content: None, - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }, ts, ); @@ -2805,7 +2798,7 @@ mod tests { fn discord_message_timestamp_propagates_to_irc_send() { let mut state = BridgeState::new(&test_config(), HashMap::new()); let ts = 1_000_000; - let msg_ts = chrono::DateTime::::from_timestamp(1_700_000_123, 0).unwrap(); + let msg_ts = jiff::Timestamp::from_second(1_700_000_123).unwrap(); state.handle_irc_event(&S2SEvent::LinkUp, ts); state.handle_discord_event( @@ -2822,7 +2815,7 @@ mod tests { author_display_name: "Alice".into(), content: "hello".into(), attachments: vec![], - timestamp: msg_ts, + timestamp: Some(msg_ts), }, ts + 10, ); @@ -2848,7 +2841,7 @@ mod tests { config.pseudoclients.dm_bridging = true; let mut state = BridgeState::new(&config, HashMap::new()); let ts = 1_000_000; - let msg_ts = chrono::DateTime::::from_timestamp(1_700_000_456, 0).unwrap(); + let msg_ts = jiff::Timestamp::from_second(1_700_000_456).unwrap(); // Introduce alice + bob so the DM has a valid target (alice DMs bob). state.handle_discord_event( @@ -2869,7 +2862,7 @@ mod tests { author_name: "alice".into(), content: "hi there".into(), referenced_content: Some("**[bob]** earlier message".into()), - timestamp: msg_ts, + timestamp: Some(msg_ts), }, ts + 5, ); diff --git a/src/bridge/relay.rs b/src/bridge/relay.rs index 54ffa8e..081376d 100644 --- a/src/bridge/relay.rs +++ b/src/bridge/relay.rs @@ -1,4 +1,4 @@ -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use crate::discord::DiscordCommand; use crate::formatting::{DiscordResolver, IrcMentionResolver}; @@ -20,7 +20,7 @@ pub(crate) fn discord_to_irc_commands( irc_channel: &str, content: &str, attachments: &[String], - timestamp: Option>, + timestamp: Option, resolver: &dyn DiscordResolver, ) -> Vec { let trimmed = content.trim(); @@ -219,8 +219,7 @@ mod tests { #[test] fn timestamp_is_propagated_to_all_commands() { - use chrono::TimeZone; - let ts = chrono::Utc.timestamp_opt(1_700_000_000, 0).unwrap(); + let ts = jiff::Timestamp::from_second(1_700_000_000).unwrap(); let urls = vec!["https://cdn.discord.com/x.png".to_string()]; let cmds = discord_to_irc_commands("uid1", "#chan", "hi", &urls, Some(ts), &NullResolver); for cmd in &cmds { diff --git a/src/bridge/routing.rs b/src/bridge/routing.rs index 931cef0..886772f 100644 --- a/src/bridge/routing.rs +++ b/src/bridge/routing.rs @@ -250,7 +250,7 @@ pub(crate) fn route_discord_to_irc( author_display_name: &str, content: &str, attachments: &[String], - timestamp: Option>, + timestamp: Option, now_ts: u64, resolver: &dyn DiscordResolver, ) -> Vec { diff --git a/src/discord/handler.rs b/src/discord/handler.rs index aa151e0..fe1f60f 100644 --- a/src/discord/handler.rs +++ b/src/discord/handler.rs @@ -304,7 +304,7 @@ pub(crate) enum IncomingMessage { author_name: String, content: String, referenced_message_id: Option, - timestamp: chrono::DateTime, + timestamp: Option, }, /// A message in a guild channel. Guild { @@ -314,10 +314,20 @@ pub(crate) enum IncomingMessage { display_name: String, content: String, attachments: Vec, - timestamp: chrono::DateTime, + timestamp: Option, }, } +/// Convert a serenity message timestamp to a `jiff::Timestamp`. +/// +/// serenity 0.12 stores it as a `time::OffsetDateTime`, from -9999-01-01 to +/// 9999-12-31. The range of `jiff` is about one day shorter at each end: +/// -9999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z. Outside it, this +/// returns `None`, and the relayed message has no `@time=` tag. +fn message_time(ts: &serenity::model::Timestamp) -> Option { + jiff::Timestamp::from_nanosecond(ts.unix_timestamp_nanos()).ok() +} + /// Decide how to handle an incoming `MESSAGE_CREATE` and marshal its fields. /// /// A message with no `guild_id` is a DM. Note that this classifies only; the @@ -333,7 +343,7 @@ pub(crate) fn classify_message(msg: &Message) -> IncomingMessage { .message_reference .as_ref() .and_then(|msg_ref| msg_ref.message_id), - timestamp: *msg.timestamp, + timestamp: message_time(&msg.timestamp), } } else { let member_nick = msg.member.as_ref().and_then(|m| m.nick.as_deref()); @@ -349,7 +359,7 @@ pub(crate) fn classify_message(msg: &Message) -> IncomingMessage { .to_owned(), content: msg.content.clone(), attachments: msg.attachments.iter().map(|a| a.url.clone()).collect(), - timestamp: *msg.timestamp, + timestamp: message_time(&msg.timestamp), } } } @@ -396,7 +406,7 @@ impl DiscordHandler { author_name: String, content: String, referenced_content: Option, - timestamp: chrono::DateTime, + timestamp: Option, ) { let filter = self.self_filter.read().await; if filter.contains(&author_id) { @@ -426,7 +436,7 @@ impl DiscordHandler { author_display_name: String, content: String, attachments: Vec, - timestamp: chrono::DateTime, + timestamp: Option, ) { let channels = self.bridged_channel_ids.read().await; let filter = self.self_filter.read().await; @@ -1052,9 +1062,7 @@ mod tests { /// Fixed test timestamp; value is arbitrary — tests that care about /// propagation assert on exact equality with this constant. - fn stock_ts() -> chrono::DateTime { - chrono::DateTime::::from_timestamp(1_700_000_000, 0).unwrap() - } + const STOCK_TS: Option = Some(jiff::Timestamp::constant(1_700_000_000, 0)); // --------------------------------------------------------------------------- // handle_ready @@ -1093,7 +1101,7 @@ mod tests { "Alice".into(), "hello".into(), vec![], - stock_ts(), + STOCK_TS, ) .await; let event = rx.try_recv().expect("expected MessageReceived event"); @@ -1118,7 +1126,7 @@ mod tests { "Bot".into(), "echo".into(), vec![], - stock_ts(), + STOCK_TS, ) .await; assert!( @@ -1138,7 +1146,7 @@ mod tests { "User".into(), "hi".into(), vec![], - stock_ts(), + STOCK_TS, ) .await; assert!( @@ -1154,7 +1162,7 @@ mod tests { async fn dm_event_emits_dm_received() { let (tx, mut rx) = mpsc::channel(1); let h = make_handler(tx, &[], &[]); - h.handle_dm_event(42, "alice".into(), "hello".into(), None, stock_ts()) + h.handle_dm_event(42, "alice".into(), "hello".into(), None, STOCK_TS) .await; let event = rx.try_recv().expect("expected DmReceived event"); assert!(matches!( @@ -1167,7 +1175,7 @@ mod tests { async fn dm_from_self_is_dropped() { let (tx, mut rx) = mpsc::channel(1); let h = make_handler(tx, &[], &[42]); // 42 is in self-filter - h.handle_dm_event(42, "bot".into(), "echo".into(), None, stock_ts()) + h.handle_dm_event(42, "bot".into(), "echo".into(), None, STOCK_TS) .await; assert!(rx.try_recv().is_err(), "DM from self should be dropped"); } @@ -1181,7 +1189,7 @@ mod tests { "alice".into(), "reply text".into(), Some("**[bob]** original".into()), - stock_ts(), + STOCK_TS, ) .await; let event = rx.try_recv().expect("expected DmReceived event"); @@ -1460,4 +1468,50 @@ mod tests { assert_eq!(map_online_status(status), expected, "status={status:?}"); } } + + // --------------------------------------------------------------------------- + // message_time + // --------------------------------------------------------------------------- + + use serenity::model::Timestamp as SerenityTimestamp; + + #[test] + fn message_time_keeps_microseconds() { + // Discord sends microsecond precision with a `+00:00` offset. + let ts = SerenityTimestamp::parse("2024-01-15T12:34:56.789123+00:00").unwrap(); + assert_eq!( + message_time(&ts), + Some(jiff::Timestamp::new(1_705_322_096, 789_123_000).unwrap()) + ); + } + + /// `message_time` of the serenity timestamp at `millis`, in nanoseconds. + fn message_time_at(millis: i64) -> Option { + message_time(&SerenityTimestamp::from_millis(millis).unwrap()) + .map(jiff::Timestamp::as_nanosecond) + } + + #[test] + fn message_time_is_some_at_both_jiff_limits() { + for limit in [jiff::Timestamp::MIN, jiff::Timestamp::MAX] { + let millis = limit.as_millisecond(); + assert_eq!( + message_time_at(millis), + Some(i128::from(millis) * 1_000_000), + "{limit}" + ); + } + } + + #[test] + fn message_time_is_none_outside_the_jiff_limits() { + assert_eq!( + message_time_at(jiff::Timestamp::MIN.as_millisecond() - 1), + None + ); + assert_eq!( + message_time_at(jiff::Timestamp::MAX.as_millisecond() + 1), + None + ); + } } diff --git a/src/discord/types.rs b/src/discord/types.rs index 8833827..cdd52d1 100644 --- a/src/discord/types.rs +++ b/src/discord/types.rs @@ -50,7 +50,8 @@ pub enum DiscordEvent { attachments: Vec, /// Discord-side creation timestamp (from `msg.timestamp`). Used to /// emit the `IRCv3` `@time=` server-time tag on the relayed `PRIVMSG`. - timestamp: chrono::DateTime, + /// `None` if `jiff` cannot represent it; the tag is then omitted. + timestamp: Option, }, /// A user's presence changed. PresenceUpdated { @@ -84,8 +85,9 @@ pub enum DiscordEvent { /// determine the target IRC user. referenced_content: Option, /// Discord-side creation timestamp. Emitted as the `IRCv3` `@time=` - /// tag when the DM is relayed as an IRC `PRIVMSG`. - timestamp: chrono::DateTime, + /// tag when the DM is relayed as an IRC `PRIVMSG`. `None` if `jiff` + /// cannot represent it; the tag is then omitted. + timestamp: Option, }, /// Initial member snapshot delivered once per guild after `guild_create`. /// Used to populate the IRC burst and mention resolution lookup tables. diff --git a/src/irc/types.rs b/src/irc/types.rs index a21ab12..bcaac26 100644 --- a/src/irc/types.rs +++ b/src/irc/types.rs @@ -1,4 +1,4 @@ -use chrono::{DateTime, Utc}; +use jiff::Timestamp; /// Protocol-agnostic events emitted by the connection module to the processing task. /// @@ -75,7 +75,7 @@ pub enum S2SEvent { target: String, text: String, /// Parsed from the `@time=` message tag; `None` if the tag was absent. - timestamp: Option>, + timestamp: Option, }, /// A NOTICE was received from an IRC user. @@ -146,7 +146,7 @@ pub enum S2SCommand { target: String, text: String, /// If `Some`, emitted as an `@time=` tag (only when uplink advertised MTAGS). - timestamp: Option>, + timestamp: Option, }, /// Change a pseudoclient's nick. diff --git a/src/irc/unreal/translation.rs b/src/irc/unreal/translation.rs index 4fb4133..95a2dbc 100644 --- a/src/irc/unreal/translation.rs +++ b/src/irc/unreal/translation.rs @@ -1,17 +1,16 @@ -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use super::irc_message::{IrcCommand, IrcMessage, SjoinParams, UidParams}; use crate::irc::types::{S2SCommand, S2SEvent}; -/// Parse the `@time=` message tag value into a `DateTime`. +/// Parse the `@time=` message tag value into a `Timestamp`. /// /// Returns `None` if the tag is absent, malformed, or out of range. -fn parse_time_tag(tags: &[(String, Option)]) -> Option> { +fn parse_time_tag(tags: &[(String, Option)]) -> Option { tags.iter() .find(|(k, _)| k == "time") .and_then(|(_, v)| v.as_deref()) - .and_then(|s| DateTime::parse_from_rfc3339(s).ok()) - .map(|dt| dt.with_timezone(&Utc)) + .and_then(|s| s.parse::().ok()) } /// Translate an inbound `IrcMessage` into an `S2SEvent`. @@ -239,7 +238,9 @@ pub(crate) fn translate_outbound( .map(|t| { vec![( "time".to_owned(), - Some(t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()), + // Spec 05: `YYYY-MM-DDTHH:MM:SS.mmmZ`. The `.3` + // precision truncates to milliseconds. + Some(format!("{t:.3}")), )] }) .unwrap_or_default() @@ -297,7 +298,6 @@ pub(crate) fn translate_outbound( #[cfg(test)] mod tests { - use chrono::TimeZone; use super::*; use crate::irc::unreal::irc_message::{IrcCommand, IrcMessage, SjoinParams, UidParams}; @@ -676,7 +676,7 @@ mod tests { }; assert_eq!( timestamp, - Some(Utc.timestamp_opt(1_700_000_000, 0).unwrap()) + Some(Timestamp::from_second(1_700_000_000).unwrap()) ); } @@ -930,9 +930,13 @@ mod tests { assert_eq!(msgs[0].tags, []); } - #[test] - fn outbound_message_with_timestamp_and_mtags_emits_time_tag() { - let t = Utc.timestamp_opt(1_700_000_000, 0).unwrap(); + /// Builds a UTC instant from Unix seconds and nanoseconds. + fn instant(secs: i64, nanos: i32) -> Timestamp { + Timestamp::new(secs, nanos).unwrap() + } + + /// Returns the value of the `@time=` tag on an outbound `SendMessage`. + fn outbound_time_tag(t: Timestamp) -> Option { let cmd = S2SCommand::SendMessage { from_uid: UID.into(), target: "#general".into(), @@ -940,13 +944,98 @@ mod tests { timestamp: Some(t), }; let msgs = translate_outbound(&cmd, SID, true, 0); - let time_tag = msgs[0].tags.iter().find(|(k, _)| k == "time"); - assert!(time_tag.is_some(), "expected @time= tag when mtags_active"); + msgs[0] + .tags + .iter() + .find(|(k, _)| k == "time") + .and_then(|(_, v)| v.clone()) + } + + #[test] + fn outbound_time_tag_has_milliseconds_and_zulu() { + assert_eq!( + outbound_time_tag(instant(1_700_000_000, 0)).as_deref(), + Some("2023-11-14T22:13:20.000Z") + ); + } + + #[test] + fn outbound_time_tag_truncates_below_milliseconds() { + assert_eq!( + outbound_time_tag(instant(1_700_000_000, 123_999_999)).as_deref(), + Some("2023-11-14T22:13:20.123Z") + ); + } + + #[test] + fn outbound_time_tag_pads_years_below_1000() { + // 0099-01-01T00:00:00Z + assert_eq!( + outbound_time_tag(instant(-59_042_995_200, 0)).as_deref(), + Some("0099-01-01T00:00:00.000Z") + ); + } + + /// Unix seconds of 0000-01-01T00:00:00Z. Before it, years are negative + /// and the text has a sign and six year digits. + const YEAR_0_SECS: i64 = -62_167_219_200; + + /// Draws an instant in `min_secs..=Timestamp::MAX`, with any nanoseconds. + fn draw_instant(tc: &TestCase, min_secs: i64) -> Timestamp { + let secs = tc.draw( + gs::integers::() + .min_value(min_secs) + .max_value(Timestamp::MAX.as_second()), + ); + let nanos = tc.draw(gs::integers::().min_value(0).max_value(999_999_999)); + instant(secs, nanos) + } + + /// For years 0 to 9999, the `@time=` tag is `YYYY-MM-DDTHH:MM:SS.mmmZ` + /// (spec 05). + #[hegel::test] + fn outbound_time_tag_has_the_spec_05_shape(tc: TestCase) { + let tag = outbound_time_tag(draw_instant(&tc, YEAR_0_SECS)).expect("tag is present"); + + let b = tag.as_bytes(); + let digits = |r: std::ops::Range| b[r].iter().all(u8::is_ascii_digit); + assert_eq!(b.len(), 24, "{tag}"); + assert!( + digits(0..4) + && b[4] == b'-' + && digits(5..7) + && b[7] == b'-' + && digits(8..10) + && b[10] == b'T' + && digits(11..13) + && b[13] == b':' + && digits(14..16) + && b[16] == b':' + && digits(17..19) + && b[19] == b'.' + && digits(20..23) + && b[23] == b'Z', + "{tag}" + ); + } + + /// Parsing the `@time=` tag gives the instant truncated to milliseconds. + #[hegel::test] + fn outbound_time_tag_round_trips_at_millisecond_precision(tc: TestCase) { + let t = draw_instant(&tc, Timestamp::MIN.as_second()); + let tag = outbound_time_tag(t).expect("tag is present"); + let tags = vec![("time".to_owned(), Some(tag))]; + // The tag truncates the clock time, so round down, also before 1970. + let millis = t.as_nanosecond().div_euclid(1_000_000) * 1_000_000; + assert_eq!( + parse_time_tag(&tags), + Some(Timestamp::from_nanosecond(millis).unwrap()) + ); } #[test] fn outbound_message_timestamp_suppressed_without_mtags() { - let t = Utc.timestamp_opt(1_700_000_000, 0).unwrap(); + let t = Timestamp::from_second(1_700_000_000).unwrap(); let cmd = S2SCommand::SendMessage { from_uid: UID.into(), target: "#general".into(), @@ -1049,10 +1138,41 @@ mod tests { let tags = vec![("time".into(), Some("2023-11-14T22:13:20.000Z".into()))]; assert_eq!( parse_time_tag(&tags), - Some(Utc.timestamp_opt(1_700_000_000, 0).unwrap()) + Some(Timestamp::from_second(1_700_000_000).unwrap()) ); } + /// jiff accepts the wider grammar of `jiff::fmt::temporal`, not only + /// RFC 3339 (spec 02). + #[test] + fn parse_time_tag_accepts_the_jiff_temporal_grammar() { + for value in [ + "20231114T221320Z", + "2023-11-14T22:13:20,000Z", + "2023-11-14T22:13:20Z[Europe/London]", + "2023-11-14T23:13:20+01", + ] { + let tags = vec![("time".into(), Some(value.into()))]; + assert_eq!( + parse_time_tag(&tags), + Some(instant(1_700_000_000, 0)), + "{value}" + ); + } + } + + #[test] + fn parse_time_tag_turns_a_leap_second_into_59() { + let tags = vec![("time".into(), Some("2016-12-31T23:59:60Z".into()))]; + assert_eq!(parse_time_tag(&tags), Some(instant(1_483_228_799, 0))); + } + + #[test] + fn parse_time_tag_applies_a_non_zero_offset() { + let tags = vec![("time".into(), Some("2023-11-14T23:13:20.000+01:00".into()))]; + assert_eq!(parse_time_tag(&tags), Some(instant(1_700_000_000, 0))); + } + // ----------------------------------------------------------------------- // Robustness: translate_inbound must never panic on remote input // ----------------------------------------------------------------------- diff --git a/tests/e2e_irc.rs b/tests/e2e_irc.rs index 592df95..6f009ac 100644 --- a/tests/e2e_irc.rs +++ b/tests/e2e_irc.rs @@ -251,8 +251,7 @@ async fn relay_probe_until_seen( author_display_name: probe.author_display_name.into(), content: probe.content.into(), attachments: vec![], - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0) - .unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }) .await .unwrap(); @@ -919,7 +918,7 @@ async fn e2e_discord_dm_with_nick_colon_relays_to_irc() { author_name: "alice".into(), content: "testbot: hey from discord dm".into(), referenced_content: None, - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0).unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }) .await .unwrap(); @@ -978,7 +977,7 @@ async fn e2e_discord_dm_unresolvable_sends_help() { author_name: "alice".into(), content: "just a random message".into(), referenced_content: None, - timestamp: chrono::DateTime::::from_timestamp(1_700_000_000, 0).unwrap(), + timestamp: jiff::Timestamp::from_second(1_700_000_000).ok(), }) .await .unwrap();