nu_plugin_nw_ulid 0.2.0

Production-grade ULID (Universally Unique Lexicographically Sortable Identifier) utilities plugin for Nushell with cryptographically secure operations, enterprise-grade security, and streaming support
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
# nu_plugin_nw_ulid Developer Guide

This guide is for developers who want to contribute to nu_plugin_nw_ulid or understand its internal architecture.

## Table of Contents

1. [Architecture Overview]#architecture-overview
2. [Development Setup]#development-setup
3. [Code Structure]#code-structure
4. [Building and Testing]#building-and-testing
5. [Plugin Development]#plugin-development
6. [Contributing Guidelines]#contributing-guidelines
7. [Performance Optimization]#performance-optimization
8. [Security Considerations]#security-considerations

## Architecture Overview

### Design Principles

nu_plugin_nw_ulid follows enterprise-grade development principles:

- **Modular Design**: Each command is implemented as a separate module
- **Security First**: All operations include security validation and context awareness
- **Performance Optimized**: Bulk processing for large datasets
- **Error Resilient**: Comprehensive error handling and graceful degradation
- **Nushell Native**: Full integration with Nushell's type system and pipeline model

### Component Architecture

The plugin entry point is `lib.rs`, which registers the `UlidPlugin` struct and its 23
commands with the Nushell plugin host. Each subcommand lives in its own file under
`commands/`, grouped by domain (see STYLE-0014 for the grouping convention). Core ULID
logic — generation, parsing, validation, and error types — lives in `ulid_engine.rs`.
Security rating and advisory logic lives in `security.rs`.

### Core Components

#### 1. Command Framework (`src/commands/`)

Each command implements the `PluginCommand` trait. See the code example in
[Command Implementation Pattern](#command-implementation-pattern) below.

#### 2. ULID Engine (`src/ulid_engine.rs`)

Core ULID operations — generation, parsing, validation, timestamp/randomness extraction —
are implemented as associated functions on `UlidEngine`. Error types are co-located in the
same file.

#### 3. Error Handling (`src/ulid_engine.rs`)

Engine functions return `UlidError`, keeping the core logic free of `nu-protocol`
dependencies. Commands convert to `LabeledError` at the call boundary (see STYLE-0016):

```rust
#[derive(Debug, Clone)]
pub enum UlidError {
    InvalidFormat { input: String, reason: String },
    InvalidInput { message: String },
    TimestampOutOfRange { timestamp: u64, max_timestamp: u64 },
    GenerationError { reason: String },
}
```

## Development Setup

### Prerequisites

- **Rust 1.89.0+** (required for Nushell 0.109.1)
- **Nushell 0.109.1+**
- **Git** for version control
- **cargo-audit** for security scanning
- **cargo-deny** for dependency management

### Environment Setup

1. **Clone the repository:**
   ```bash
   git clone https://github.com/nushell-works/nu_plugin_nw_ulid.git
   cd nu_plugin_nw_ulid
   ```

2. **Install development dependencies:**
   ```bash
   cargo install cargo-audit cargo-deny cargo-machete
   ```

3. **Set up pre-commit hooks:**
   ```bash
   # Install pre-commit
   pip install pre-commit
   
   # Install hooks
   pre-commit install
   ```

4. **Verify development environment:**
   ```bash
   # Build
   cargo build
   
   # Run tests
   cargo test
   
   # Check code quality
   cargo clippy
   cargo fmt --check
   
   # Security audit
   cargo audit
   cargo deny check
   ```

### Development Workflow

1. **Create feature branch:**
   ```bash
   git checkout -b feature/new-command
   ```

2. **Implement changes:**
   - Add/modify code
   - Write tests
   - Update documentation

3. **Run quality checks:**
   ```bash
   ./scripts/dev_check.sh
   ```

4. **Commit changes:**
   ```bash
   git add .
   git commit -m "feat: add new ULID command"
   ```

5. **Push and create PR:**
   ```bash
   git push origin feature/new-command
   ```

## Code Structure

### Command Implementation Pattern

Every command follows this structure:

```rust
// src/commands/inspect.rs (simplified)
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
    Category, LabeledError, PipelineData, Signature, SyntaxShape, Type, Value,
};

use crate::{UlidEngine, UlidPlugin};

pub struct UlidInspectCommand;

impl PluginCommand for UlidInspectCommand {
    type Plugin = UlidPlugin;

    fn name(&self) -> &str {
        "ulid inspect"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .required("ulid", SyntaxShape::String, "The ULID to analyze")
            .input_output_types(vec![(Type::Nothing, Type::Record(vec![].into()))])
            .category(Category::Strings)
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        _input: PipelineData,
    ) -> Result<PipelineData, LabeledError> {
        let ulid_str: String = call.req(0)?;

        // Engine returns UlidError; convert to LabeledError at the boundary
        let components = UlidEngine::parse(&ulid_str)
            .map_err(|e| LabeledError::new("Parse failed")
                .with_label(e.to_string(), call.head))?;

        let mut record = nu_protocol::Record::new();
        record.push("ulid", Value::string(&components.ulid, call.head));
        record.push("valid", Value::bool(components.valid, call.head));
        // ...
        Ok(Value::record(record, call.head).into_pipeline_data())
    }
}
```

### Testing Pattern

Each command should have comprehensive tests:

```rust
// tests/test_example.rs
use nu_plugin::test_helpers::*;
use nu_protocol::Value;
use crate::commands::UlidExample;

#[test]
fn test_example_single() {
    let command = UlidExample::new();
    let call = test_call();
    let input = Value::nothing(test_span());
    
    let result = command.run(&call, &input).unwrap();
    assert!(matches!(result, Value::String { .. }));
}

#[test]
fn test_example_batch() {
    let command = UlidExample::new();
    let call = test_call();
    let input = Value::list(vec![
        Value::string("test1", test_span()),
        Value::string("test2", test_span()),
    ], test_span());
    
    let result = command.run(&call, &input).unwrap();
    assert!(matches!(result, Value::List { .. }));
}

#[test]
fn test_example_error_handling() {
    let command = UlidExample::new();
    let call = test_call();
    let input = Value::int(42, test_span());
    
    let result = command.run(&call, &input);
    assert!(result.is_err());
}
```

## Building and Testing

### Build Commands

```bash
# Development build
cargo build

# Release build (optimized)
cargo build --release

# Check without building
cargo check

# Build with all features
cargo build --all-features
```

### Testing

```bash
# Run all tests
cargo test

# Run specific test module
cargo test test_generate

# Run tests with output
cargo test -- --nocapture

# Run integration tests only
cargo test --test integration_tests

# Run security tests
cargo test --test security_tests

# Run performance tests
cargo test --test performance_tests --release
```

### Benchmarking

```bash
# Run performance benchmarks
cargo bench

# Run specific benchmark
cargo bench ulid_generation

# Compare with baseline
cargo bench -- --save-baseline main
git checkout feature-branch
cargo bench -- --baseline main
```

### Code Quality

```bash
# Lint with Clippy
cargo clippy -- -D warnings

# Format code
cargo fmt

# Check formatting
cargo fmt --check

# Security audit
cargo audit

# Dependency checking
cargo deny check

# Check for unused dependencies
cargo machete
```

## Plugin Development

### Adding New Commands

1. **Create command module:**
   ```bash
   # Create new file: src/commands/new_command.rs
   ```

2. **Implement command structure:**
   ```rust
   // Follow the command pattern shown above
   pub struct UlidNewCommand;
   
   impl UlidNewCommand {
       pub fn new() -> Self { Self }
       pub fn signature(&self) -> PluginSignature { /* ... */ }
       pub fn run(&self, call: &EvaluatedCall, input: &Value) -> Result<Value, LabeledError> { /* ... */ }
   }
   ```

3. **Add to module exports:**
   ```rust
   // src/commands/mod.rs
   pub mod new_command;
   pub use new_command::UlidNewCommand;
   ```

4. **Register in plugin:**
   ```rust
   // src/lib.rs
   impl Plugin for UlidPlugin {
       fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> {
           vec![
               // existing commands...
               Box::new(UlidNewCommand::new()),
           ]
       }
   }
   ```

5. **Add tests:**
   ```rust
   // tests/test_new_command.rs
   // Add comprehensive tests
   ```

### Extending ULID Functionality

1. **Core functionality goes in `src/ulid_engine.rs`**
2. **Follow security-first principles**
3. **Add comprehensive error handling**
4. **Include performance considerations**
5. **Add security context validation**

### Performance Optimization

#### Memory Management

- Avoid loading entire datasets into memory
- Use iterators instead of collecting intermediate results

## Contributing Guidelines

### Code Style

1. **Follow Rust conventions:**
   - Use `snake_case` for functions and variables
   - Use `PascalCase` for types and structs
   - Use `SCREAMING_SNAKE_CASE` for constants

2. **Documentation:**
   - All public functions must have doc comments
   - Include examples in doc comments
   - Document error conditions

3. **Error Handling:**
   - Use Result types for fallible operations
   - Provide context in error messages
   - Don't panic in library code

4. **Testing:**
   - Unit tests for individual functions
   - Integration tests for command workflows
   - Property-based tests for core algorithms
   - Security tests for attack resistance

### Performance Guidelines

1. **Use bulk operations when possible**
2. **Enable parallel processing for CPU-intensive operations**
3. **Profile performance-critical code**

### Security Guidelines

1. **Validate all inputs**
2. **Use secure randomness for ULID generation**
3. **Implement context-aware security warnings**
4. **Sanitize error messages**
5. **Follow principle of least privilege**

### Documentation Standards

1. **Code comments for complex logic**
2. **API documentation with examples**
3. **User guide updates for new features**
4. **Security documentation for new functionality**
5. **Performance characteristics documentation**

## Performance Optimization

### Profiling

```bash
# CPU profiling
cargo install flamegraph
cargo flamegraph --bin nu_plugin_nw_ulid

# Memory profiling
valgrind --tool=massif target/release/nu_plugin_nw_ulid

# Benchmark profiling
cargo bench -- --profile-time=10
```

### Optimization Techniques

1. **Algorithm Selection:**
   - Use efficient algorithms for Base32 encoding
   - Optimize timestamp extraction
   - Implement fast validation routines

2. **Memory Management:**
   - Minimize allocations in hot paths
   - Use object pooling for frequently allocated objects
   - Implement zero-copy operations where possible

3. **Parallel Processing:**
   - Use Rayon for data parallelism
   - Implement work-stealing for load balancing
   - Consider NUMA topology for large datasets

4. **Caching:**
   - Cache parsed ULID components
   - Use lookup tables for encoding operations
   - Implement result memoization for expensive operations

## Security Considerations

### Security Validation

1. **Input Validation:**
   ```rust
   fn validate_ulid_format(ulid: &str) -> Result<(), UlidError> {
       if ulid.len() != ULID_STRING_LENGTH {
           return Err(UlidError::InvalidFormat {
               input: ulid.to_string(),
               reason: "ULID must be 26 characters".to_string(),
           });
       }
       
       Ok(())
   }
   ```

2. **Cryptographic Security:**
   ```rust
   use rand::{rngs::OsRng, RngCore};
   
   fn generate_secure_randomness() -> [u8; 10] {
       let mut rng = OsRng;
       let mut bytes = [0u8; 10];
       rng.fill_bytes(&mut bytes);
       bytes
   }
   ```

3. **Context Validation:**
   ```rust
   fn check_security_context(context: &str) -> SecurityLevel {
       match context {
           "user-session" => SecurityLevel::High,
           "api-keys" => SecurityLevel::Critical,
           "database-ids" => SecurityLevel::Medium,
           _ => SecurityLevel::Low,
       }
   }
   ```

### Attack Resistance

1. **Timing Attack Prevention:**
   - Use constant-time comparison for sensitive operations
   - Avoid early returns in validation logic
   - Implement rate limiting for repeated operations

2. **Resource Exhaustion Protection:**
   - Implement batch size limits
   - Add timeout protection for long operations

3. **Input Sanitization:**
   - Validate all input parameters
   - Escape special characters in error messages
   - Implement length limits for input data

This developer guide provides comprehensive information for contributing to nu_plugin_nw_ulid while maintaining enterprise-grade quality standards.