Skip to content

Commit bab9842

Browse files
leynosterragon-labs[bot]
andauthored
Refactor unwrap and expect propagation; pluggable server plumbing (#400)
* Refactor connection frame handling - Flatten frame processing loop to reduce nesting and keep timeout purge logic explicit. - Bundle framing state into a context struct so handle_frame stays within clippy argument limits without changing behaviour. Tests: - make check-fmt - make test * Simplify frame handling helpers - Track deserialization failures with a helper to cut closure argument count and keep error reporting consistent. - Wrap response forwarding inputs in ResponseContext and flatten send/serialize loop to satisfy clippy nesting limits. - Adjust connection call site to use the new context wrapper. Tests: - make check-fmt - make test * Refactor connection construction - Introduce ConnectionChannels wrapper so with_hooks stays within clippy argument limits and update call sites accordingly. - Split fragmented frame processing into a helper to eliminate excessive nesting and avoid borrow conflicts. Tests: - make check-fmt - make test * Refine push handle flow - Extract rate-limiter wait and DLQ logging into helpers to reduce nesting while preserving non-blocking behaviour. Tests: - make check-fmt - make test * Reduce reassembler arguments - Derive message id from the occupied entry so append_and_maybe_complete drops an argument and stays within clippy limits. Tests: - make check-fmt - make test * Streamline server preamble handling - Pass preamble hooks into process_stream as a single struct to satisfy clippy argument limits and keep spawn logic simple. Tests: - make check-fmt - make test * Bundle accept loop options - Wrap preamble hooks, shutdown signal, tracker, and backoff config into AcceptLoopOptions so accept_loop meets clippy argument limits. - Update server worker spawn and tests to construct the new options struct and refresh docs example. Tests: - make check-fmt - make test * Enhanced code metric requirements * Fix remaining clippy warnings - Flatten timeout handling and fragmentation purge, collapse DLQ send handling, and simplify echo example handler. - Reduce nesting in fragmentation tests and multi-packet world producer helper. - Bundle push policy test cases to satisfy clippy argument limits. Tests: - make lint - make test * Lint documentation * Fix envelope rustdoc links - Point intra-doc links to crate::app::builder::WireframeApp and its handle_connection method so docsrs resolves them. Tests: - make check-fmt - make test * Fix push builder rustdoc link - Remove private DEFAULT_PUSH_RATE intra-doc link and describe default rate in prose to satisfy docsrs. Tests: - make check-fmt - make test * Tidy reassembler rustdoc links - Remove redundant explicit intra-doc link targets for MessageId and FragmentSeries to satisfy docsrs lint. Tests: - make check-fmt - make test * Introduce hygeine lints * Expect private_bounds with reason - Replace #[allow(private_bounds)] with #[expect(private_bounds)] and document why the helper trait aliases stay private. Tests: - make check-fmt - make test * Refactor forward_response complexity - Split response fragmentation, serialization, and send steps into helpers and flatten error paths to satisfy clippy cognitive complexity. Tests: - make check-fmt - make test * Update markdownlint rules and ignore settings * Apply documentation and writing style corrections to AGENTS.md * Revise and expand Rust code and testing conventions in AGENTS.md * Standardize and clarify command-line tooling sections in AGENTS.md * Reformat wireframe_testing crate README for improved Markdown flow * Update logging to use inline variable interpolation and improve error messages * Refactor fragmenter test to use helper function for checking fragments * Require Sync on Preamble trait to improve concurrency guarantees * Refactor preamble handling in connection processing and isolate handler logic * Refactor accept loop for clarity and extract iteration logic * Cleanup test utility preamble helpers with consistent lint expectations * Add and standardize lint expectations for single-line rstest fixtures * Add crate-level lint expectations for test modules requiring them * Remove redundant or now-unnecessary allow/expect attributes on simple fixtures * Standardize lint attributes for test utilities and unused helper code * Apply consistent lint suppression to push_policies.rs test fixtures * Deny debug/print macros; use tracing in examples Add lints to deny dbg_macro, print_stdout and print_stderr to catch leftover debugging prints early. Replace direct stdout/stderr usage in examples and tests with structured logging (tracing::info / tracing::error) and initialize a tracing_subscriber in example mains so logs are emitted. Remove the minimal binary that only printed a greeting. These changes enforce consistent, structured logging and prevent accidental print/debug output from slipping into the codebase. * Fix clippy findings in connection * Remove expect from actor harness default * Guard payload advance against over-slicing * Make fragment slicing bounds-checked * Harden fragment payload encoding/decoding * Bounds-check frame length conversions * Guard length prefix writes against over-slicing * Guard preamble reads with checked buffer slices * Handle DLQ lock poisoning without expect * Remove panics and allow select lint in queue recv * Bounds-check rewind stream leftovers * Allow select! lint in runtime paths * Replace select lint allow in connection * Use if-let for fragment chunk slicing * Handle fragment header length without casts * Simplify prefix encoding in conversion helpers * Collapse rate validation branching in push queues * Replace select allow lint in runtime * Allow select lint via expect in push queues * Enable lints for panic prone operations * Use infallible test app factory * Propagate push fixture errors in session registry tests * Guard middleware order test against missing frames * Make echo example infallible and lint-clean * Avoid panics in metadata serializer tests * Propagate errors in metadata tests * Harden metadata routing example * Propagate errors in correlation id tests * Use first helper in session registry test * Use io::Error::other in metadata routing * Propagate errors in connection actor error tests * Propagate errors in connection actor tests * Propagate errors in push policy and fragmentation tests * Guard response tests against indexing panics * Propagate errors in lifecycle tests * Propagate errors in push policy tests * Make packet enum example fallible * Propagate errors in multi-packet streaming tests * Return errors in metadata tests * Propagate errors in stream end tests * Propagate errors in wireframe protocol tests * Handle errors in ping pong example * Handle multi-packet streaming without panics * Handle queue fixture errors in shutdown tests * Avoid get-first in routes tests * Return errors instead of panics in push tests * test(fragmentation): refactor tests for improved error handling and robustness Refactored tests in fragment_transport.rs and multi_packet.rs to use unified error handling via custom TestError enums and TestResult type aliases. Introduced proper error propagation in async tests and helper functions, reducing panics and expect calls. Enhanced test reliability and maintainability by converting infallible code panics into proper Result error chains. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * refactor(tests): refactor preamble tests to use Result and handle errors properly - Introduce `TestResult` alias for standardized error handling. - Update async test functions and helpers to return `TestResult` and use `?` for error propagation. - Replace multiple `.expect()` calls with error propagation to improve test robustness and clarity. - Add helper functions `take_sender_io` and `recv_within` to streamline sender handling and timed receive operations. - Clean up locking code to handle potential poisoning gracefully. - Overall improve error handling and reduce panics in preamble reading tests. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * test(tests): improve test error reporting and code clarity - Add a custom Assertion error variant for clearer test failure messages in fragment_transport.rs. - Replace assert_eq! macros with explicit error returns for payload mismatches. - Refactor frame access in response.rs tests to use .first().expect() for clarity and consistency. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * test(tests): refactor test assertions for clearer error reporting Replaced `assert!` and `assert_eq!` macros in tests with explicit error returns providing detailed failure messages. This change improves test diagnostics by making assertion failures produce descriptive errors instead of panics, aiding in debugging test failures in fragment_transport and push test modules. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * Propagate errors through cucumber worlds * Handle shutdown in ping-pong example * Return errors for empty multi-packet streams * Return errors in correlation id tests * Handle preamble validation errors * Guard rate limiter priority ordering * Make fragmentation tests fallible * Avoid panics in correlation steps * Make fragment reassembly helpers fallible * Propagate errors in fragment world * Return errors from fragment cucumber steps * Log echo app build failures * Propagate errors in shutdown tests * Tighten push policy warning assertions * Simplify multi-packet world errors * Make panic world setup fallible * Propagate errors in panic steps * Document errors in correlation world * Document errors in fragment reassembly helpers * Document fragment world fallible helpers * Document stream end world errors * Alias wireframe protocol queue result * Return errors in fairness tests * Propagate errors in connection tests * Avoid indexing in accept loop test * Use safe access in fragment tests * Handle short slices in frame tests * Adjust panic tests in connection handler * Handle shutdown in ping-pong example * Refactor accept loop backoff helpers * Add granular assertions for connection snapshots * Borrow backoff call log * Propagate snapshot failures * Clarify refactoring guidance wording * Simplify accept loop flow * Avoid cloning fragmenter per frame * Propagate response write failures * Cover fragment payload truncation cases * Guard fragmenter bounds with test * Return errors for invalid rewind offsets * Test frame prefix error paths * Group accept iteration handles * Simplify response fallible flow * Expose fragment cursor for testing * Trace connection drops in multi_packet example * Tidy extractor fixtures * Fix extractor and lifecycle lint issues * Factor fragment decode error helper * Clarify fragment slice bounds errors * Renumber clippy lint sections * Clarify unsupported size test messages * Improve accept loop test helpers * Propagate echo example errors and shutdown * Centralise TestResult alias in common * Simplify rewind slice bounds check * Simplify ActorHarness default * Documented harness default expectation * Clarify frame conversion error expectations * Simplify fragment payload bounds check * Add graceful shutdown to packet_enum example * Propagate preamble test server errors * Use shared TestResult in wireframe_protocol tests * Use shared TestResult in stream_end tests * Use shared TestResult in middleware_order tests * Use shared TestResult in metadata tests * Use shared TestResult in lifecycle tests * Use shared TestResult in correlation_id tests * Use shared TestResult in connection_actor_errors tests * Use shared TestResult in connection_actor_fairness tests * Use shared TestResult in connection_actor_shutdown tests * Use shared TestResult in session_registry tests * Use shared TestResult in connection tests * Use shared TestResult in push tests * refactor(tests): consolidate TestResult type into common module Replaced the duplicate definitions of the TestResult type alias in multiple test files with a shared import from the new tests/common module. This improves code consistency and reduces redundancy by centralizing error handling types in test code. Additionally, updated test modules to use the common TestResult and adjusted error conversions accordingly. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * test(fragment_transport): map errors to allow usage of ? in test functions Refactor error handling in test functions to use .map_err(Into::into) for consistent error conversion. This allows the use of the ? operator with various error types, improving test code clarity and ergonomics. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * Fix multi_packet test errors * Fix fragment_transport error conversions * Propagate teardown errors in lifecycle tests * Refactor envelope decode failure handling * Clarify defensive checks in frame conversion * Tidy session registry fixture and lint handling * Guard test clock locks with expected lint * Tighten frame conversion and preamble handling * Tidy rate limiting, preamble IO, and test helpers * Document preamble buffer slice safety * Scope test util lint handling * Clarify connection actor fairness assertions * Propagate push queue config errors * Harden preamble slicing and tidy must_use * Address review assertions in metadata and routes * Apply review fixes across tests * Align fixtures and fragmentation helpers with review * Exercise unused_listener helper * Return errors instead of panics in push tests * Align multi_packet tests with shared TestResult * Simplify timeout iteration purge * Simplify single-frame decode in routes test * Handle push rate limiter assertions without panics * Return explicit errors in multi_packet empty stream checks * Make lifecycle tests fail with Result errors instead of panics * Convert metadata tests to error returns for clearer diagnostics * Handle single-frame route test without panic * Return errors in push rate limiter tests * Use assertions for multi_packet empty stream diagnostics * Assert callback counts in lifecycle tests * Restore assert-based diagnostics in fragment transport tests * Restore assertions in push rate limiter tests * Assert closed errors in push queue tests * Simplify route echo test frame assertions * Reduce error mapping boilerplate in multi_packet tests * Align test assertions and error naming per review * Add timeouts and assertion cleanups * Clean up middleware and session registry tests * Improve wireframe protocol test assertions * Simplify correlation world verification logic * Fail fast when panic world app setup fails * Align response context field visibility * Consolidate rstest fixture lint suppressions * Improve connection fragmentation test assertions * Assert correlation ids directly in tests * Apply additional lint-driven cleanups * Refactor u64_to_bytes helpers * Tighten push timeouts and routes assertions * Improve lifecycle helper assertions * Guard fragment transport responses with timeouts * Use assertions in metadata tests * Propagate route setup errors and tighten streaming assertions * Tighten middleware, routes, and response tests * Address review nits in payload decoding and correlation tests * Refactor fragment transport round-trip tests * Propagate response test errors and simplify multi-packet overflow * refactor(frame): simplify write_bytes_with_endianness and improve test slice handling This change removes the redundant size parameter in `write_bytes_with_endianness`, deriving size from the prefix slice length instead. In tests/routes.rs, changed frame extraction to use slice pattern matching for clearer and safer handling. Also added a log warning when closing connections after too many deserialization failures for better observability. Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com> * Clarify oversized prefix test * Improve missing frame error message * Guard length conversion prefixes * Require single terminator frame in correlation test * Improve send_response error context in test * Tighten routing tests and prefix handling * Apply review fixes across fragmentation and routing * Polish decode handling and tracing init * Simplify decode envelope error handling * Refine routing test params and server addr handling * Handle ctrl_c errors in packet_enum * Propagate connection errors to callers * Log ctrl_c errors and tidy connection docs --------- Co-authored-by: Payton McIntosh <pmcintosh@df12.net> Co-authored-by: terragon-labs[bot] <terragon-labs[bot]@users.noreply.github.com>
1 parent 52e463e commit bab9842

74 files changed

Lines changed: 3689 additions & 2106 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.markdownlint-cli2.jsonc

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
{
2-
// Ignore MD013 (line length) inside tables since reflowing
3-
// Markdown tables often breaks formatting and readability.
42
"config": {
3+
"MD004": { "style": "dash" },
4+
"MD010": { "code_blocks": false },
55
"MD013": {
66
"line_length": 80,
77
"code_block_line_length": 120,
8-
"tables": false
8+
"tables": false,
9+
"headings": false
910
},
10-
"MD040": false
11-
}
11+
"MD029": { "style": "ordered" }
12+
},
13+
"ignores": ["**/.venv/**", ".node_modules/**", "**/node_modules/**", "**/target/**"]
1214
}

AGENTS.md

Lines changed: 73 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Code Style and Structure
44

5-
- **Code is for humans.** Write your code with clarity and empathy—assume a
5+
- **Code is for humans.** Write code with clarity and empathy—assume a
66
tired teammate will need to debug it at 3 a.m.
77
- **Comment *why*, not *what*.** Explain assumptions, edge cases, trade-offs, or
88
complexity. Don't echo the obvious.
@@ -43,8 +43,10 @@
4343
relevant file(s) in the `docs/` directory to reflect the latest state.
4444
**Ensure the documentation remains accurate and current.**
4545
- Documentation must use en-GB-oxendict ("-ize" / "-yse" / "-our") spelling
46-
and grammar. (EXCEPTION: the naming of the "LICENSE" file, which is to be
47-
left unchanged for community consistency.)
46+
and grammar. (EXCEPTION: the filename `LICENSE` is left unchanged for
47+
community consistency.)
48+
- A documentation style guide is provided at
49+
`docs/documentation-style-guide.md`.
4850

4951
## Change Quality & Committing
5052

@@ -68,7 +70,7 @@
6870
- **Imperative Mood:** Use the imperative mood in the subject line (e.g.,
6971
"Fix bug", "Add feature" instead of "Fixed bug", "Added feature").
7072
- **Subject Line:** The first line should be a concise summary of the change
71-
(ideally 50 characters or less).
73+
(ideally 50 characters or fewer).
7274
- **Body:** Separate the subject from the body with a blank line. Subsequent
7375
lines should explain the *what* and *why* of the change in more detail,
7476
including rationale, goals, and scope. Wrap the body at 72 characters.
@@ -79,7 +81,7 @@
7981
## Refactoring Heuristics & Workflow
8082

8183
- **Recognizing Refactoring Needs:** Regularly assess the codebase for potential
82-
refactoring opportunities. Consider refactoring when you observe:
84+
refactoring opportunities. Perform refactoring when you observe:
8385
- **Long Methods/Functions:** Functions or methods that are excessively long
8486
or try to do too many things.
8587
- **Duplicated Code:** Identical or very similar code blocks appearing in
@@ -103,7 +105,7 @@
103105
- **Separate Atomic Refactors:** If refactoring is deemed necessary:
104106
- Perform the refactoring as a **separate, atomic commit** *after* the
105107
functional change commit.
106-
- Ensure the refactoring adheres to the testing guidelines (behavioral tests
108+
- Ensure refactoring adheres to the testing guidelines (behavioural tests
107109
pass before and after, unit tests added for new units).
108110
- Ensure the refactoring commit itself passes all quality gates.
109111

@@ -114,26 +116,26 @@ management. Contributors should follow these best practices when working on the
114116
project:
115117

116118
- Run `make check-fmt`, `make lint`, and `make test` before committing. These
117-
targets wrap the following commands so contributors understand the exact
119+
targets wrap the following commands, so contributors understand the exact
118120
behaviour and policy enforced:
119121
- `make check-fmt` executes:
120122

121-
```
123+
```sh
122124
cargo fmt --workspace -- --check
123125
```
124126

125127
validating formatting across the entire workspace without modifying files.
126128
- `make lint` executes:
127129

128-
```
130+
```sh
129131
cargo clippy --workspace --all-targets --all-features -- -D warnings
130132
```
131133

132134
linting every target with all features enabled and denying all Clippy
133135
warnings.
134136
- `make test` executes:
135137

136-
```
138+
```sh
137139
cargo test --workspace
138140
```
139141

@@ -147,40 +149,34 @@ project:
147149
adhering to separation of concerns and CQRS.
148150
- Where a function has too many parameters, group related parameters in
149151
meaningfully named structs.
150-
- Where a function is returning a large error consider using `Arc` to reduce the
151-
amount of data returned.
152+
- Where a function is returning a large error, consider using `Arc` to reduce
153+
the amount of data returned.
152154
- Write unit and behavioural tests for new functionality. Run both before and
153155
after making any change.
154156
- Every module **must** begin with a module level (`//!`) comment explaining the
155157
module's purpose and utility.
156158
- Document public APIs using Rustdoc comments (`///`) so documentation can be
157159
generated with cargo doc.
158160
- Prefer immutable data and avoid unnecessary `mut` bindings.
159-
- Handle errors with the `Result` type instead of panicking where feasible.
160161
- Use explicit version ranges in `Cargo.toml` and keep dependencies up-to-date.
161-
- Avoid `unsafe` code unless absolutely necessary and document any usage
162-
clearly.
162+
- Avoid `unsafe` code unless absolutely necessary, and document any usage
163+
clearly with a "SAFETY" comment.
163164
- Place function attributes **after** doc comments.
164165
- Do not use `return` in single-line functions.
165166
- Use predicate functions for conditional criteria with more than two branches.
166167
- Lints must not be silenced except as a **last resort**.
167168
- Lint rule suppressions must be tightly scoped and include a clear reason.
168-
- Prefer `expect` over `allow`.
169-
- Use `rstest` fixtures for shared setup.
170-
- Replace duplicated tests with `#[rstest(...)]` parameterised cases.
171-
- Prefer `mockall` for mocks/stubs.
172-
- Prefer `.expect()` over `.unwrap()`.
173169
- Use `concat!()` to combine long string literals rather than escaping newlines
174170
with a backslash.
175-
- Prefer single line versions of functions where appropriate. I.e.,
171+
- Prefer single line versions of functions where appropriate. i.e.,
176172
177-
```
173+
```rust
178174
pub fn new(id: u64) -> Self { Self(id) }
179175
```
180176
181177
Instead of:
182178
183-
```
179+
```rust
184180
pub fn new(id: u64) -> Self {
185181
Self(id)
186182
}
@@ -190,16 +186,30 @@ project:
190186
`newt-hype` when introducing many homogeneous wrappers that share behaviour;
191187
add small shims such as `From<&str>` and `AsRef<str>` for string-backed
192188
wrappers. For path-centric wrappers implement `AsRef<Path>` alongside
193-
`into_inner()` and `to_path_buf()`; avoid attempting
189+
`into_inner()` and `to_path_buf()`, avoid attempting
194190
`impl From<Wrapper> for PathBuf` because of the orphan rule. Prefer explicit
195191
tuple structs whenever bespoke validation or tailored trait surfaces are
196-
required, customising `Deref`, `AsRef`, and `TryFrom` per type. Use
192+
required, customizing `Deref`, `AsRef`, and `TryFrom` per type. Use
197193
`the-newtype` when defining traits and needing blanket implementations that
198194
apply across wrappers satisfying `Newtype + AsRef/AsMut<Inner>`, or when
199195
establishing a coherent internal convention that keeps trait forwarding
200196
consistent without per-type boilerplate. Combine approaches: lean on
201197
`newt-hype` for the common case, tuple structs for outliers, and
202-
`the-newtype` to unify behaviour when you own the trait definitions.
198+
`the-newtype` to unify behaviour when owning the trait definitions.
199+
- Use `cap_std` and `cap_std::fs_utf8` / `camino` in place of `std::fs` and
200+
`std::path` for enhanced cross-platform support and capability-oriented
201+
filesystem access.
202+
203+
### Testing
204+
205+
- Use `rstest` fixtures for shared setup.
206+
- Replace duplicated tests with `#[rstest(...)]` parameterized cases.
207+
- Prefer `mockall` for ad hoc mocks/stubs.
208+
- For testing of functionality depending upon environment variables, dependency
209+
injection and the `mockable` crate are the preferred option.
210+
- If mockable cannot be used, env mutations in tests MUST be wrapped in shared
211+
guards and mutexes placed in a shared `test_utils` or `test_helpers` crate.
212+
Direct environment mutation is FORBIDDEN in tests.
203213
204214
### Dependency Management
205215
@@ -225,6 +235,18 @@ project:
225235
- **Never export the opaque type from a library**. Convert to domain enums at
226236
API boundaries, and to `eyre` only in the main `main()` entrypoint or
227237
top-level async task.
238+
- In tests, prefer `.expect(...)` over `.unwrap()` to surface clearer failure
239+
diagnostics.
240+
- In production code and shared fixtures, avoid `.expect()` entirely: return
241+
`Result` and use `?` to propagate errors instead of panicking.
242+
- Keep `expect_used` **strict**; do not suppress the lint.
243+
- Recognize that `allow-expect-in-tests = true` **doesn’t cover** helpers
244+
outside `#[cfg(test)]` or `#[test]`; avoid `expect` in such fixtures.
245+
- Use `anyhow`/`eyre` with `.context(...)` to **preserve backtraces** and
246+
provide clear, typed failure paths.
247+
- Update helpers (e.g., `set_dir`) to **return errors** rather than panicking.
248+
- Consume fallible fixtures in `rstest` by **making the test return `Result`**
249+
and applying `?` to the fixture.
228250

229251
## Markdown Guidance
230252

@@ -243,39 +265,39 @@ project:
243265

244266
The following tooling is available in this environment:
245267

246-
- `mbake` A Makefile validator. Run using `mbake validate Makefile`.
247-
- `strace` Traces system calls and signals made by a process; useful for
268+
- `mbake` A Makefile validator. Run using `mbake validate Makefile`.
269+
- `strace` Traces system calls and signals made by a process; useful for
248270
debugging runtime behaviour and syscalls.
249-
- `gdb` The GNU Debugger, for inspecting and controlling programs as they
271+
- `gdb` The GNU Debugger, for inspecting and controlling programs as they
250272
execute (or post-mortem via core dumps).
251-
- `ripgrep` Fast, recursive text search tool (`grep` alternative) that
273+
- `ripgrep` Fast, recursive text search tool (`grep` alternative) that
252274
respects `.gitignore` files.
253-
- `ltrace` Traces calls to dynamic library functions made by a process.
254-
- `valgrind` Suite for detecting memory leaks, profiling, and debugging
275+
- `ltrace` Traces calls to dynamic library functions made by a process.
276+
- `valgrind` Suite for detecting memory leaks, profiling, and debugging
255277
low-level memory errors.
256-
- `bpftrace` High-level tracing tool for eBPF, using a custom scripting
278+
- `bpftrace` High-level tracing tool for eBPF, using a custom scripting
257279
language for kernel and application tracing.
258-
- `lsof` Lists open files and the processes using them.
259-
- `htop` Interactive process viewer (visual upgrade to `top`).
260-
- `iotop` Displays and monitors I/O usage by processes.
261-
- `ncdu` NCurses-based disk usage viewer for finding large files/folders.
262-
- `tree` Displays directory structure as a tree.
263-
- `bat` `cat` clone with syntax highlighting, Git integration, and paging.
264-
- `delta` Syntax-highlighted pager for Git and diff output.
265-
- `tcpdump` Captures and analyses network traffic at the packet level.
266-
- `nmap` Network scanner for host discovery, port scanning, and service
280+
- `lsof` Lists open files and the processes using them.
281+
- `htop` Interactive process viewer (visual upgrade to `top`).
282+
- `iotop` Displays and monitors I/O usage by processes.
283+
- `ncdu` NCurses-based disk usage viewer for finding large files/folders.
284+
- `tree` Displays directory structure as a tree.
285+
- `bat` `cat` clone with syntax highlighting, Git integration, and paging.
286+
- `delta` Syntax-highlighted pager for Git and diff output.
287+
- `tcpdump` Captures and analyses network traffic at the packet level.
288+
- `nmap` Network scanner for host discovery, port scanning, and service
267289
identification.
268-
- `lldb` LLVM debugger, alternative to `gdb`.
269-
- `eza` Modern `ls` replacement with more features and better defaults.
270-
- `fzf` Interactive fuzzy finder for selecting files, commands, etc.
271-
- `hyperfine` Command-line benchmarking tool with statistical output.
272-
- `shellcheck` Linter for shell scripts, identifying errors and bad practices.
273-
- `fd` Fast, user-friendly `find` alternative with sensible defaults.
274-
- `checkmake` Linter for `Makefile`s, ensuring they follow best practices and
290+
- `lldb` LLVM debugger, alternative to `gdb`.
291+
- `eza` Modern `ls` replacement with more features and better defaults.
292+
- `fzf` Interactive fuzzy finder for selecting files, commands, etc.
293+
- `hyperfine` Command-line benchmarking tool with statistical output.
294+
- `shellcheck` Linter for shell scripts, identifying errors and bad practices.
295+
- `fd` Fast, user-friendly `find` alternative with sensible defaults.
296+
- `checkmake` Linter for `Makefile`s, ensuring they follow best practices and
275297
conventions.
276-
- `srgn` [Structural grep](https://github.com/alexpovel/srgn), searches code
298+
- `srgn` [Structural grep](https://github.com/alexpovel/srgn), searches code
277299
and enables editing by syntax tree patterns.
278-
- `difft` **(Difftastic)** Semantic diff tool that compares code structure
300+
- `difft` **(Difftastic)** Semantic diff tool that compares code structure
279301
rather than just text differences.
280302

281303
## Key Takeaway

Cargo.toml

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,10 @@ log = "0.4.28"
3939
dashmap = "6.1.0"
4040
leaky-bucket = "1.1.2"
4141
tracing = { version = "0.1.41", features = ["log", "log-always"] }
42-
tracing-subscriber = "0.3"
42+
tracing-subscriber = "0.3.18"
4343
metrics = { version = "0.24.2", optional = true }
4444
thiserror = "2.0.16"
45-
static_assertions = "1"
45+
static_assertions = "1.1.0"
4646
derive_more = { version = "2.0.1", features = ["display", "from"] }
4747

4848
[dev-dependencies]
@@ -85,11 +85,45 @@ cucumber-tests = []
8585
test-support = []
8686

8787
[lints.clippy]
88-
pedantic = "warn"
88+
pedantic = { level = "warn", priority = -1 }
89+
90+
# 1. hygiene
91+
allow_attributes = "deny"
92+
allow_attributes_without_reason = "deny"
93+
blanket_clippy_restriction_lints = "deny"
94+
cognitive_complexity = "deny"
95+
needless_pass_by_value = "deny"
96+
implicit_hasher = "deny"
97+
98+
# 2. debugging leftovers
99+
dbg_macro = "deny"
100+
print_stdout = "deny"
101+
print_stderr = "deny"
102+
103+
# 3. panic-prone operations
104+
unwrap_used = "deny"
105+
expect_used = "deny"
106+
indexing_slicing = "deny"
107+
string_slice = "deny"
108+
integer_division = "deny"
109+
integer_division_remainder_used = "deny"
110+
panic_in_result_fn = "deny"
111+
unreachable = "deny"
89112

90113
[lints.rust]
114+
unknown_lints = "deny"
115+
renamed_and_removed_lints = "deny"
91116
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
92117

118+
[lints.rustdoc]
119+
missing_crate_level_docs = "deny"
120+
broken_intra_doc_links = "deny"
121+
private_intra_doc_links = "deny"
122+
bare_urls = "deny"
123+
invalid_html_tags = "deny"
124+
invalid_codeblock_attributes = "deny"
125+
unescaped_backticks = "deny"
126+
93127
[[example]]
94128
name = "echo"
95129
path = "examples/echo.rs"

Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ CRATE ?= wireframe
44
CARGO ?= cargo
55
BUILD_JOBS ?=
66
CLIPPY_FLAGS ?= --all-targets --all-features -- -D warnings
7+
RUSTDOC_FLAGS ?= --cfg docsrs -D warnings
78
MDLINT ?= markdownlint
89
NIXIE ?= nixie
910

@@ -29,6 +30,7 @@ target/%/lib$(CRATE).rlib: ## Build library in debug or release
2930
$@
3031

3132
lint: ## Run Clippy with warnings denied
33+
RUSTDOCFLAGS="$(RUSTDOC_FLAGS)" $(CARGO) doc --no-deps
3234
$(CARGO) clippy $(CLIPPY_FLAGS)
3335

3436
fmt: ## Format Rust and Markdown sources

clippy.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Align with CodeScene’s ceiling
2+
cognitive-complexity-threshold = 9 # default is 25
3+
too-many-arguments-threshold = 4 # default is 7
4+
too-many-lines-threshold = 70 # default is 100
5+
excessive-nesting-threshold = 4 # default is off
6+
7+
allow-expect-in-tests = true

examples/async_stream.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
use async_stream::try_stream;
88
use futures::StreamExt;
9+
use tracing::info;
910
use wireframe::response::Response;
1011

1112
#[derive(bincode::Encode, bincode::BorrowDecode, Debug, PartialEq)]
@@ -22,10 +23,12 @@ fn stream_response() -> Response<Frame> {
2223

2324
#[tokio::main]
2425
async fn main() {
26+
tracing_subscriber::fmt::init();
27+
2528
let Response::Stream(mut stream) = stream_response() else {
2629
return;
2730
};
2831
while let Some(Ok(frame)) = stream.next().await {
29-
println!("received frame: {frame:?}");
32+
info!(?frame, "received frame");
3033
}
3134
}

0 commit comments

Comments
 (0)