nsip 0.4.0

NSIP Search API client for nsipsearch.nsip.org/api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# Customization Guide

This guide covers how to customize the `nsip` beyond the initial setup. For basic configuration (renaming the crate, updating metadata), see the main README.

---

## Table of Contents

1. [Adding New Modules]#1-adding-new-modules
2. [Removing Example Code]#2-removing-example-code
3. [Library-Only vs Binary Crate]#3-library-only-vs-binary-crate
4. [Adjusting Lint Strictness]#4-adjusting-lint-strictness
5. [Adjusting Supply Chain Policy]#5-adjusting-supply-chain-policy
6. [Modifying Release Targets]#6-modifying-release-targets
7. [Docker Customization]#7-docker-customization
8. [Adding Property-Based Tests]#8-adding-property-based-tests

---

## 1. Adding New Modules

### Create the module file

Create a new file under `crates/`. For example, `crates/parser.rs`:

```rust
//! Parser module for nsip.

use crate::{Error, Result};

/// Parses the given input string into a structured value.
///
/// # Arguments
///
/// * `input` - The raw input to parse.
///
/// # Returns
///
/// The parsed output.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if the input is malformed.
///
/// # Examples
///
/// ```rust
/// use nsip::parser::parse;
///
/// let result = parse("valid input")?;
/// assert!(!result.is_empty());
/// # Ok::<(), nsip::Error>(())
/// ```
pub fn parse(input: &str) -> Result<String> {
    if input.is_empty() {
        return Err(Error::InvalidInput("input cannot be empty".to_string()));
    }
    Ok(input.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_valid() {
        let result = parse("hello");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "hello");
    }

    #[test]
    fn test_parse_empty() {
        let result = parse("");
        assert!(matches!(result, Err(Error::InvalidInput(_))));
    }
}
```

### Register the module in `crates/lib.rs`

Add a `pub mod` declaration at the top of `crates/lib.rs`:

```rust
pub mod parser;
```

### Add integration tests

Create or extend a file in `tests/`. For example, `tests/parser_test.rs`:

```rust
use nsip::parser::parse;

#[test]
fn test_parse_integration() {
    let result = parse("test input");
    assert!(result.is_ok());
}
```

### Checklist

- [ ] Module file created in `crates/`
- [ ] `pub mod` added to `crates/lib.rs`
- [ ] All public items have doc comments with `# Examples`
- [ ] Unit tests in `#[cfg(test)]` module within the file
- [ ] Integration tests added to `tests/`
- [ ] `cargo test` passes
- [ ] `cargo clippy --all-targets --all-features` passes
- [ ] `cargo doc --no-deps` builds without warnings

---

## 2. Removing Example Code

The template ships with placeholder functions (`add`, `divide`) and a `Config` builder to demonstrate patterns. Once you are ready to add your own code, remove them.

### Step 1: Clean up `crates/lib.rs`

Remove the `add` and `divide` functions, the `Config` struct and its `impl` blocks, and the entire `#[cfg(test)] mod tests` block. Keep the `Error` enum and the `Result` type alias -- you will likely need them.

Your `crates/lib.rs` should look like this after cleanup:

```rust
#![doc = include_str!("../README.md")]

use thiserror::Error;

/// Error type for `nsip` operations.
#[derive(Error, Debug)]
pub enum Error {
    /// Invalid input was provided.
    #[error("invalid input: {0}")]
    InvalidInput(String),

    /// An operation failed.
    #[error("operation '{operation}' failed: {cause}")]
    OperationFailed {
        /// The operation that failed.
        operation: String,
        /// The underlying cause.
        cause: String,
    },
}

/// Result type alias for `nsip` operations.
pub type Result<T> = std::result::Result<T, Error>;

// Add your modules and public API here.
```

### Step 2: Update or remove `crates/main.rs`

If you keep a binary target, rewrite `crates/main.rs` to remove references to the example functions:

```rust
//! Binary entry point for `nsip`.

#![allow(clippy::print_stdout, clippy::print_stderr)]

use std::process::ExitCode;

fn run() -> Result<(), nsip::Error> {
    // Your application logic here
    Ok(())
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("Error: {e}");
            ExitCode::FAILURE
        },
    }
}
```

If you do not need a binary, see [Library-Only vs Binary Crate](#3-library-only-vs-binary-crate) below.

### Step 3: Clean up integration tests

Remove or rewrite `tests/integration_test.rs`. Delete the example tests that reference `add`, `divide`, and `Config`, and replace them with tests for your own API.

### Step 4: Update README.md

Remove the example usage snippets in `README.md` that reference `add`, `divide`, and `Config`. Replace them with documentation for your own public API.

---

## 3. Library-Only vs Binary Crate

### Removing the binary target

If your crate is library-only, remove the binary configuration:

1. Delete `crates/main.rs`.

2. Remove the `[[bin]]` section from `Cargo.toml`:

   ```toml
   # Delete these lines:
   [[bin]]
   name = "nsip"
   path = "crates/main.rs"
   ```

3. Remove the binary-related steps from the Docker and release workflows if you do not need them.

### Adding additional binaries

Add extra `[[bin]]` sections to `Cargo.toml`:

```toml
[[bin]]
name = "nsip"
path = "crates/main.rs"

[[bin]]
name = "nsip_cli"
path = "crates/cli.rs"
```

Each binary gets its own entry point file under `crates/`. Remember to add `#![allow(clippy::print_stdout, clippy::print_stderr)]` at the top of each binary file since the lint configuration forbids print macros in library code.

### Using a workspace for multiple crates

For larger projects, convert to a Cargo workspace. Replace the top-level `Cargo.toml` with a workspace manifest:

```toml
[workspace]
resolver = "2"
members = [
    "crates/core",
    "crates/cli",
    "crates/server",
]

[workspace.package]
edition = "2024"
rust-version = "1.92"
license = "MIT"
repository = "https://github.com/zircote/nsip"

[workspace.lints.rust]
unsafe_code = "forbid"
missing_docs = "warn"

[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
unwrap_used = "deny"
expect_used = "deny"
panic = "deny"
```

Each member crate then has its own `Cargo.toml` that inherits workspace settings:

```toml
[package]
name = "nsip_core"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true

[lints]
workspace = true
```

---

## 4. Adjusting Lint Strictness

### Lint groups in `Cargo.toml`

The template enables four Clippy lint groups in `[lints.clippy]`:

| Group | What it covers |
|-------|---------------|
| `all` | Standard Clippy lints (correctness, style, complexity, performance) |
| `pedantic` | Stricter, opinionated lints (naming conventions, API design, documentation) |
| `nursery` | Experimental lints that may have false positives |
| `cargo` | Cargo manifest issues (missing fields, feature misuse) |

To relax the overall strictness, remove a group or change its level:

```toml
[lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
# nursery = { level = "warn", priority = -1 }   # Commented out to disable
cargo = { level = "warn", priority = -1 }
```

### Allowing specific lints per item

Use `#[allow()]` attributes to suppress a lint for a specific function, struct, or module:

```rust
#[allow(clippy::cast_possible_truncation)]
fn to_u32(value: u64) -> u32 {
    value as u32
}
```

For an entire module:

```rust
#[allow(clippy::too_many_lines)]
mod complex_module {
    // ...
}
```

### Denied lints

The template denies these lints at the crate level:

```toml
unwrap_used = "deny"     # Use Result and ? instead
expect_used = "deny"     # Use Result and ? instead
panic = "deny"           # Never panic in library code
todo = "deny"            # Complete all implementations
unimplemented = "deny"   # Complete all implementations
dbg_macro = "deny"       # Remove debug macros before committing
print_stdout = "deny"    # Use tracing or log instead
print_stderr = "deny"    # Use tracing or log instead
```

To relax any of these, change `"deny"` to `"warn"` or `"allow"`:

```toml
todo = "warn"            # Allow TODOs with a warning
```

Note that `print_stdout` and `print_stderr` are already allowed in `crates/main.rs` via file-level attributes. This is intentional -- binary entry points typically need to print output.

### `clippy.toml` thresholds

The `clippy.toml` file controls numeric thresholds for various lints:

| Setting | Default | Purpose |
|---------|---------|---------|
| `cognitive-complexity-threshold` | 25 | Maximum cognitive complexity per function |
| `excessive-nesting-threshold` | 4 | Maximum nesting depth |
| `too-many-lines-threshold` | 100 | Maximum function length |
| `too-many-arguments-threshold` | 7 | Maximum function parameters |
| `max-struct-bools` | 3 | Maximum bool fields in a struct |
| `max-fn-params-bools` | 3 | Maximum bool parameters in a function |
| `pass-by-value-size-limit` | 256 | Byte threshold to warn about passing large types by value |
| `type-complexity-threshold` | 250 | Threshold for overly complex types |

Adjust these to match your project's needs. For example, to allow longer functions:

```toml
too-many-lines-threshold = 200
```

Test code is exempt from several strict lints via these settings in `clippy.toml`:

```toml
allow-dbg-in-tests = true
allow-expect-in-tests = true
allow-unwrap-in-tests = true
allow-print-in-tests = true
```

### `rustfmt.toml` options

Key formatting settings you may want to adjust:

| Setting | Default | Purpose |
|---------|---------|---------|
| `max_width` | 100 | Maximum line width |
| `tab_spaces` | 4 | Spaces per indentation level |
| `imports_granularity` | `"Crate"` | How imports are grouped (`Crate`, `Module`, `Item`, `One`) |
| `group_imports` | `"StdExternalCrate"` | Import grouping order (std, external, crate) |
| `wrap_comments` | true | Wrap long comments to fit `comment_width` |
| `trailing_comma` | `"Vertical"` | Add trailing commas in multi-line constructs |
| `edition` | `"2024"` | Rust edition for parsing |

To change line width to 120 characters:

```toml
max_width = 120
comment_width = 120
```

---

## 5. Adjusting Supply Chain Policy

The `deny.toml` file configures `cargo-deny` to audit your dependency tree.

### Adding allowed licenses

The `[licenses]` section lists allowed SPDX license identifiers. To add a new license:

```toml
[licenses]
allow = [
    "MIT",
    "Apache-2.0",
    "Apache-2.0 WITH LLVM-exception",
    "BSD-2-Clause",
    "BSD-3-Clause",
    "ISC",
    "Zlib",
    "MPL-2.0",
    "Unicode-DFS-2016",
    "Unicode-3.0",
    "CC0-1.0",
    "BSL-1.0",
    "0BSD",
    "LGPL-3.0",        # <-- Added
]
```

For crates with non-standard license files, add a `[[licenses.clarify]]` entry:

```toml
[[licenses.clarify]]
name = "some_crate"
expression = "MIT AND BSD-2-Clause"
license-files = [{ path = "LICENSE", hash = 0x12345678 }]
```

### Exempting specific advisories

If a security advisory does not apply to your usage, add its ID to the `ignore` list:

```toml
[advisories]
ignore = [
    "RUSTSEC-2024-XXXX",   # Reason: only affects feature X which we don't use
]
```

Always include a comment explaining why the advisory is exempted.

### Banning specific crates

The `[bans]` section prevents specific crates from entering your dependency tree:

```toml
[bans]
deny = [
    { name = "openssl", wrappers = [], reason = "Use rustls for TLS instead" },
    { name = "atty", wrappers = [], reason = "Use std::io::IsTerminal instead (available in Rust 1.70+)" },
    { name = "some_crate", wrappers = [], reason = "Known to be unmaintained" },
]
```

The `wrappers` field allows exceptions when a banned crate is only used as a transitive dependency of a specific wrapper crate:

```toml
{ name = "openssl", wrappers = ["openssl-sys"], reason = "Only allow via openssl-sys" }
```

### Configuring source restrictions

By default, only crates.io is allowed as a registry source:

```toml
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []
```

To allow a private registry or specific git repositories:

```toml
allow-registry = [
    "https://github.com/rust-lang/crates.io-index",
    "https://my-company.example.com/cargo/index",
]

allow-git = [
    "https://github.com/zircote/private-crate",
]
```

### Verifying changes

After modifying `deny.toml`, run the checks:

```bash
cargo deny check
```

---

## 6. Modifying Release Targets

The release workflow (`.github/workflows/release.yml`) builds binaries for multiple platforms using a matrix strategy.

### Default targets

| Target | OS Runner | Architecture |
|--------|-----------|-------------|
| `x86_64-unknown-linux-gnu` | `ubuntu-latest` | Linux x86_64 |
| `aarch64-unknown-linux-gnu` | `ubuntu-latest` | Linux ARM64 (cross-compiled) |
| `x86_64-apple-darwin` | `macos-latest` | macOS x86_64 |
| `aarch64-apple-darwin` | `macos-latest` | macOS ARM64 (Apple Silicon) |
| `x86_64-pc-windows-msvc` | `windows-latest` | Windows x86_64 |

### Adding a target

Add a new entry to the `matrix.include` array in `release.yml`:

```yaml
- os: ubuntu-latest
  target: x86_64-unknown-linux-musl
  artifact_name: nsip
  asset_name: nsip-linux-musl-amd64
```

For musl targets, you will also need to install the musl toolchain:

```yaml
- name: Install musl tools
  if: matrix.target == 'x86_64-unknown-linux-musl'
  run: |
    sudo apt-get update
    sudo apt-get install -y musl-tools
```

### Removing a target

Delete the corresponding entry from `matrix.include`. For example, to drop Windows support, remove:

```yaml
# Delete this block:
- os: windows-latest
  target: x86_64-pc-windows-msvc
  artifact_name: nsip.exe
  asset_name: nsip-windows-amd64.exe
```

Also remove the target from `deny.toml`'s `[graph].targets` list so supply chain checks stay aligned.

### Cross-compilation requirements

Cross-compilation for `aarch64-unknown-linux-gnu` requires:

- `gcc-aarch64-linux-gnu` installed on the runner
- The `CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER` environment variable set to `aarch64-linux-gnu-gcc`

Both are already configured in the workflow. For other cross-compilation targets, you will need to install the appropriate cross-compilation toolchain and set the corresponding linker environment variable.

---

## 7. Docker Customization

The `Dockerfile` uses a multi-stage build:

1. **Builder stage** (`rust:1.92-slim`) -- compiles the binary with release optimizations.
2. **Runtime stage** (`gcr.io/distroless/cc-debian12`) -- minimal image containing only the binary.

### Changing the base image

To use a different runtime base image (for example, Debian slim instead of distroless):

```dockerfile
# Runtime stage
FROM debian:bookworm-slim

RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates && \
    rm -rf /var/lib/apt/lists/*

RUN useradd --create-home appuser
USER appuser

COPY --from=builder /app/target/release/nsip /usr/local/bin/nsip

ENTRYPOINT ["/usr/local/bin/nsip"]
```

Distroless is preferred for production because it contains no shell or package manager, reducing the attack surface. Use Debian slim if you need to debug inside the container or require additional runtime dependencies.

### Adding runtime dependencies

If your binary links against shared libraries at runtime, install them in the runtime stage. With distroless, you are limited to what is available in the base image. For additional libraries, switch to a Debian-based runtime:

```dockerfile
FROM debian:bookworm-slim

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    ca-certificates \
    libpq5 \
    && rm -rf /var/lib/apt/lists/*
```

### Modifying the builder stage

The builder stage uses a dependency caching strategy: it first copies `Cargo.toml` and `Cargo.lock`, builds with dummy source files to cache dependencies, then copies the real source and rebuilds. This means dependency downloads are cached across builds as long as `Cargo.toml`/`Cargo.lock` do not change.

If you add new source directories (for example, a workspace with multiple crates), update the dummy source creation:

```dockerfile
# Create dummy source to cache dependencies
RUN mkdir -p crates/core/src crates/cli/src && \
    echo "pub fn dummy() {}" > crates/core/src/lib.rs && \
    echo "fn main() {}" > crates/cli/src/main.rs
```

And update the copy step:

```dockerfile
COPY crates/ ./crates/
```

### Adding build-time dependencies

If your project needs additional system libraries at compile time, add them in the builder stage:

```dockerfile
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    pkg-config \
    libssl-dev \
    libpq-dev \
    protobuf-compiler \
    && rm -rf /var/lib/apt/lists/*
```

---

## 8. Adding Property-Based Tests

The template already includes `proptest` as a dev-dependency and ships with example property tests in `tests/integration_test.rs`.

### Where property tests live

Property tests can be placed in:

- **Unit tests**: Inside `crates/*.rs` in a `#[cfg(test)]` module
- **Integration tests**: Inside `tests/` files, typically in a submodule

The template demonstrates the integration test approach:

```rust
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn add_is_commutative(a in any::<i32>(), b in any::<i32>()) {
            let a = i64::from(a);
            let b = i64::from(b);
            prop_assert_eq!(add(a, b), add(b, a));
        }

        #[test]
        fn add_zero_is_identity(n in any::<i64>()) {
            prop_assert_eq!(add(n, 0), n);
            prop_assert_eq!(add(0, n), n);
        }
    }
}
```

### Writing effective property tests

Focus on **invariants** -- properties that must always hold regardless of input:

```rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn roundtrip_serialize_deserialize(input in "\\PC{1,100}") {
        let serialized = serialize(&input)?;
        let deserialized = deserialize(&serialized)?;
        prop_assert_eq!(input, deserialized);
    }

    #[test]
    fn output_is_always_valid(input in any::<u64>()) {
        let result = transform(input);
        prop_assert!(is_valid(&result));
    }
}
```

### Custom strategies

For domain-specific types, define custom generators:

```rust
use proptest::prelude::*;

fn valid_config() -> impl Strategy<Value = Config> {
    (any::<bool>(), 1..100u32, 1..3600u64).prop_map(|(verbose, retries, timeout)| {
        Config::new()
            .with_verbose(verbose)
            .with_max_retries(retries)
            .with_timeout(timeout)
    })
}

proptest! {
    #[test]
    fn config_always_has_positive_timeout(config in valid_config()) {
        prop_assert!(config.timeout_secs > 0);
    }
}
```

### Configuration

Proptest behavior can be tuned via a `proptest.toml` file or the `ProptestConfig` struct. Create `proptest.toml` in the project root to adjust the number of test cases:

```toml
# Number of successful test cases required (default: 256)
cases = 512

# Maximum number of shrink iterations (default: 4096)
max_shrink_iters = 8192
```

For detailed guidance on property-based testing strategies, see [docs/testing/PROPERTY-BASED-TESTING.md](../testing/PROPERTY-BASED-TESTING.md).