tale-ndjson 0.4.0

A tail-compatible tool for pretty-printing ndjson files, especially logs.
Documentation
#!/usr/bin/env python3
"""
Generate realistic NDJSON log files for benchmarking tale.

Creates a mix of:
- Structured JSON logs (HTTP requests, app logs, DB queries)
- Plain text logs (stack traces, debug output)
- Malformed JSON (partial, truncated)
"""

import json
import os
from datetime import datetime, timedelta

# --- Deterministic benchmark fixtures (`just bench`) -------------------------
#
# The fixtures below are fully index-derived — sequential timestamps from
# fixed bases, cycling field values, no randomness — so every machine
# generates byte-identical files and benchmark numbers are comparable.

CANONICAL_BASE_TS = datetime(2025, 8, 17, 18, 40, 23)
MIXED_BASE_TS = datetime(2025, 8, 17, 6, 55, 6)
MESSAGE_BASE_TS = datetime(2025, 8, 17, 6, 55, 0)

CANONICAL_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"]
CANONICAL_PATHS = ["/api/users", "/api/orders", "/api/products", "/health", "/metrics"]
CANONICAL_STATUSES = [200, 201, 204, 400, 401, 403, 404, 500, 502, 503]
CANONICAL_LEVELS = ["INFO", "INFO", "INFO", "WARN", "WARN"]

MESSAGE_LEVELS = ["DEBUG", "INFO", "INFO", "INFO", "WARN"]
MESSAGE_LOGS = {
    "auth": "User authentication successful",
    "database": "Database query completed",
    "cache": "Cache miss, fetching from database",
    "worker": "Background job started",
    "scheduler": "Scheduled task executed",
    "api": "API request processed",
}
MESSAGE_MODULES = list(MESSAGE_LOGS)


def fixed_timestamp(base: datetime, offset_seconds: int) -> str:
    return (base + timedelta(seconds=offset_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")


def canonical_line(i: int, base: datetime = CANONICAL_BASE_TS) -> str:
    """A Stripe-style canonical HTTP log line (the fast parse path)."""
    return json.dumps(
        {
            "timestamp": fixed_timestamp(base, i),
            "level": CANONICAL_LEVELS[i % 5],
            "message": "Request processed",
            "method": CANONICAL_METHODS[i % 5],
            "url": f"{CANONICAL_PATHS[i % 5]}/{i}",
            "status": CANONICAL_STATUSES[i % 10],
            "elapsed": f"{10 + (i % 40)}ms",
            "size": 512 + (i % 1000),
            "request_id": f"req_{i}",
            "remote_host": f"192.168.1.{100 + (i % 155)}",
            "user_agent": "test-agent/1.0",
        },
        separators=(",", ":"),
    )


def message_line(i: int, base: datetime = MESSAGE_BASE_TS) -> str:
    """A flexible Message-style app log line (the superset parse path)."""
    module = MESSAGE_MODULES[i % len(MESSAGE_MODULES)]
    log = {
        "timestamp": fixed_timestamp(base, i),
        "level": MESSAGE_LEVELS[i % 5],
        "message": MESSAGE_LOGS[module],
        "module": module,
    }
    # Cycle a few extra field shapes so cells vary.
    shape = i % 4
    if shape == 0:
        log["user_id"] = 1000 + i
        log["duration"] = f"{1 + (i % 50)}ms"
    elif shape == 1:
        log["memory_usage"] = f"{10 + (i % 80)}MB"
    elif shape == 2:
        log["cache_hit"] = i % 2 == 0
    else:
        log["request_id"] = f"req_{i}"
    return json.dumps(log, separators=(",", ":"))


def java_line(i: int, base: datetime = MIXED_BASE_TS) -> str:
    """A log4j/slf4j-style Java record."""
    return json.dumps(
        {
            "timestamp": fixed_timestamp(base, i),
            "level": "DEBUG",
            "message": f"Processing request {i} in com.example.service.UserService",
            "logger": "com.example.service.UserService",
            "thread": f"pool-1-thread-{1 + (i % 8)}",
        },
        separators=(",", ":"),
    )


def mixed_line(i: int) -> str:
    """The mixed workload: ~10% Java, ~20% canonical, ~70% message."""
    phase = i % 10
    if phase == 0:
        return java_line(i)
    if phase in (1, 2):
        return canonical_line(i, MIXED_BASE_TS)
    return message_line(i, MIXED_BASE_TS)


def generate_deterministic(filename: str, num_lines: int, generator) -> None:
    """Write a deterministic fixture, skipping if it already exists."""
    if os.path.exists(filename):
        print(f"  {filename} already exists; skipping (delete to regenerate)")
        return
    print(f"Generating {filename} with {num_lines:,} lines...")
    with open(filename, "w") as f:
        for i in range(num_lines):
            f.write(generator(i) + "\n")
    print(f"  Complete!")


def main():
    """Generate the benchmark fixtures used by `just bench`."""
    os.makedirs("fixtures/benchmarks", exist_ok=True)
    fixtures = [
        ("fixtures/benchmarks/test_mixed_1000000_lines.log", 1_000_000, mixed_line),
        ("fixtures/benchmarks/test_canonical_120000_lines.log", 120_000, canonical_line),
        ("fixtures/benchmarks/test_message_10000_lines.log", 10_000, message_line),
    ]
    for filename, num_lines, generator in fixtures:
        generate_deterministic(filename, num_lines, generator)
    print("\nDeterministic benchmark fixtures ready.")


if __name__ == "__main__":
    main()