File size: 8,098 Bytes
f02ef17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TTT v1.4: versioned, lossless adaptive packet codec.

Wire format (13-byte header):
  magic: 4 bytes, b'TTT4'
  codec: 1 byte (0 raw, 1 gzip, 2 zstandard, 3 bzip2)
  original_size: uint32 big-endian
  crc32: uint32 big-endian, over the reconstructed original bytes
  payload: raw/compressed bytes

The decoder enforces packet/original-size limits and validates length and CRC.
"""
from __future__ import annotations

import bz2
import gzip
import io
import struct
import zlib
from dataclasses import dataclass
from typing import Final

try:
    import zstandard as zstd
except ImportError:  # allow limited local tests without the optional package
    zstd = None

MAGIC: Final[bytes] = b"TTT4"
VERSION: Final[str] = "1.4.0"
HEADER: Final[struct.Struct] = struct.Struct(">4sBII")
HEADER_BYTES: Final[int] = HEADER.size
MAX_ORIGINAL_BYTES: Final[int] = 16 * 1024 * 1024
MAX_PACKET_BYTES: Final[int] = 32 * 1024 * 1024
CODEC_NAMES: Final[dict[int, str]] = {0: "raw", 1: "gzip", 2: "zstd", 3: "bzip2"}
NAME_TO_CODEC: Final[dict[str, int]] = {v: k for k, v in CODEC_NAMES.items()}


class TTTError(ValueError):
    """Base exception for malformed or unsupported TTT packets."""


@dataclass(frozen=True)
class PacketInfo:
    mode: str
    original_size: int
    payload_size: int
    packet_size: int
    savings_vs_raw_percent: float


def _compress(data: bytes, mode: str) -> bytes:
    if mode == "raw":
        return data
    if mode == "gzip":
        return gzip.compress(data, compresslevel=9, mtime=0)
    if mode == "zstd":
        if zstd is None:
            raise TTTError("Zstandard is unavailable. Install requirements.txt.")
        return zstd.ZstdCompressor(level=9, write_checksum=True, write_content_size=True).compress(data)
    if mode == "bzip2":
        return bz2.compress(data, compresslevel=9)
    raise TTTError(f"Unknown mode: {mode}")


def encode_packet(data: bytes, mode: str = "auto") -> tuple[bytes, PacketInfo]:
    """Encode bytes into a TTT4 packet. In auto mode, choose smallest full packet."""
    if not isinstance(data, bytes):
        raise TypeError("data must be bytes")
    if len(data) > MAX_ORIGINAL_BYTES:
        raise TTTError(f"Input exceeds the {MAX_ORIGINAL_BYTES:,}-byte safety limit.")
    mode = mode.lower().strip()
    if mode == "auto":
        modes = ["raw", "gzip", "zstd", "bzip2"]
    elif mode in NAME_TO_CODEC:
        modes = [mode]
    else:
        raise TTTError("Mode must be auto, raw, gzip, zstd, or bzip2.")

    choices: list[tuple[int, bytes, str]] = []
    errors: list[str] = []
    for candidate_mode in modes:
        try:
            payload = _compress(data, candidate_mode)
            packet_size = HEADER_BYTES + len(payload)
            if packet_size <= MAX_PACKET_BYTES:
                choices.append((packet_size, payload, candidate_mode))
        except Exception as exc:
            errors.append(f"{candidate_mode}: {exc}")
    if not choices:
        detail = "; ".join(errors) if errors else "No candidate produced a valid packet."
        raise TTTError(detail)

    packet_size, payload, chosen_mode = min(choices, key=lambda item: item[0])
    crc = zlib.crc32(data) & 0xFFFFFFFF
    packet = HEADER.pack(MAGIC, NAME_TO_CODEC[chosen_mode], len(data), crc) + payload
    info = PacketInfo(
        mode=chosen_mode,
        original_size=len(data),
        payload_size=len(payload),
        packet_size=len(packet),
        savings_vs_raw_percent=(100.0 * (len(data) - len(packet)) / len(data)) if data else 0.0,
    )
    return packet, info


def _decompress_payload(mode: str, payload: bytes, expected_size: int) -> bytes:
    # Each path either caps output to expected_size+1 or explicitly checks output.
    if mode == "raw":
        result = payload
    elif mode == "gzip":
        decoder = zlib.decompressobj(wbits=16 + zlib.MAX_WBITS)
        result = decoder.decompress(payload, expected_size + 1)
        if len(result) <= expected_size and decoder.unconsumed_tail:
            result += decoder.decompress(decoder.unconsumed_tail, expected_size + 1 - len(result))
        if len(result) > expected_size:
            raise TTTError("Decoded data exceeds the declared original size.")
        if not decoder.eof:
            raise TTTError("Incomplete GZIP stream.")
        if decoder.unused_data:
            raise TTTError("Unexpected trailing bytes inside GZIP payload.")
    elif mode == "zstd":
        if zstd is None:
            raise TTTError("Zstandard is unavailable. Install requirements.txt.")
        # Stream output in bounded chunks; cap the decoder window to limit hostile frames.
        source = io.BytesIO(payload)
        dctx = zstd.ZstdDecompressor(max_window_size=(MAX_ORIGINAL_BYTES + 1023) // 1024)
        output = bytearray()
        with dctx.stream_reader(source, read_size=8192, read_across_frames=False) as reader:
            while len(output) <= expected_size:
                remaining = expected_size + 1 - len(output)
                chunk = reader.read(min(65536, remaining))
                if not chunk:
                    break
                output.extend(chunk)
        result = bytes(output)
        if len(result) > expected_size:
            raise TTTError("Decoded data exceeds the declared original size.")
    elif mode == "bzip2":
        decoder = bz2.BZ2Decompressor()
        result = decoder.decompress(payload, max_length=expected_size + 1)
        if len(result) > expected_size:
            raise TTTError("Decoded data exceeds the declared original size.")
        if not decoder.eof:
            raise TTTError("Incomplete BZIP2 stream or decoded-size limit reached.")
        if decoder.unused_data:
            raise TTTError("Unexpected trailing bytes inside BZIP2 payload.")
    else:
        raise TTTError(f"Unsupported codec: {mode}")
    if len(result) != expected_size:
        raise TTTError(f"Length mismatch: expected {expected_size} bytes, got {len(result)}.")
    return result


def decode_packet(packet: bytes) -> tuple[bytes, PacketInfo]:
    """Validate and decode a TTT4 packet to the exact original bytes."""
    if not isinstance(packet, bytes):
        raise TypeError("packet must be bytes")
    if len(packet) > MAX_PACKET_BYTES:
        raise TTTError(f"Packet exceeds the {MAX_PACKET_BYTES:,}-byte safety limit.")
    if len(packet) < HEADER_BYTES:
        raise TTTError("Packet is shorter than the TTT4 header.")
    magic, codec_id, expected_size, expected_crc = HEADER.unpack(packet[:HEADER_BYTES])
    if magic != MAGIC:
        raise TTTError("Not a TTT v1.4 packet (invalid magic).")
    if codec_id not in CODEC_NAMES:
        raise TTTError(f"Unknown codec ID: {codec_id}.")
    if expected_size > MAX_ORIGINAL_BYTES:
        raise TTTError(f"Declared output exceeds the {MAX_ORIGINAL_BYTES:,}-byte safety limit.")
    payload = packet[HEADER_BYTES:]
    mode = CODEC_NAMES[codec_id]
    try:
        data = _decompress_payload(mode, payload, expected_size)
    except TTTError:
        raise
    except Exception as exc:
        raise TTTError(f"Invalid or corrupted {mode} payload: {exc}") from exc
    actual_crc = zlib.crc32(data) & 0xFFFFFFFF
    if actual_crc != expected_crc:
        raise TTTError("Checksum mismatch: packet may be damaged or modified.")
    info = PacketInfo(
        mode=mode,
        original_size=len(data),
        payload_size=len(payload),
        packet_size=len(packet),
        savings_vs_raw_percent=(100.0 * (len(data) - len(packet)) / len(data)) if data else 0.0,
    )
    return data, info


def health_info() -> dict[str, object]:
    return {
        "status": "ok",
        "service": "TTT lossless adaptive transmitter",
        "version": VERSION,
        "packet_format": "TTT4",
        "header_bytes": HEADER_BYTES,
        "max_original_bytes": MAX_ORIGINAL_BYTES,
        "max_packet_bytes": MAX_PACKET_BYTES,
        "encodings": ["raw", "gzip"] + (["zstd"] if zstd is not None else []) + ["bzip2"],
        "auto_selection": "smallest complete packet among available encoders",
        "shared_tokenizer_vocabulary_required": False,
    }