Path: redb-route/redb.Route/Serialization/ZipMessageSerializer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Serialization/ZipMessageSerializer.cs ---- using System.IO.Compression; namespace redb.Route.Serialization; /// /// Zip as a data format: Marshal("application/zip") packs the body into a single-entry archive /// (entry name from the constructor, default body); Unmarshal reads the first entry. /// public sealed class ZipMessageSerializer : BinaryWrapperSerializer { /// Content type the format is registered under by default. public const string DefaultContentType = "application/zip"; private readonly string _entryName; private readonly CompressionLevel _level; private readonly long _maxDecodedBytes; /// Creates the format. /// Name of the single archive entry written by Marshal. /// Compression level (default ). /// Cap on the decompressed size (default , 128 MB); an entry that expands past it is refused. public ZipMessageSerializer(string entryName = "body", CompressionLevel level = CompressionLevel.Optimal, long maxDecodedBytes = DefaultMaxDecodedBytes) { ArgumentException.ThrowIfNullOrWhiteSpace(entryName); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxDecodedBytes); _entryName = entryName; _level = level; _maxDecodedBytes = maxDecodedBytes; } /// public override string ContentType => DefaultContentType; /// public override IReadOnlyCollection MediaTypes => [DefaultContentType, "application/x-zip-compressed"]; /// protected override string FormatName => "Zip"; /// protected override byte[] Encode(byte[] payload) { using var output = new MemoryStream(); using (var archive = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true)) { using var entry = archive.CreateEntry(_entryName, _level).Open(); entry.Write(payload); } return output.ToArray(); } /// protected override byte[] Decode(byte[] data) { using var input = new MemoryStream(data, writable: false); using var archive = new ZipArchive(input, ZipArchiveMode.Read); // Directory entries (empty Name) carry no data; the format reads exactly one file entry — a // multi-entry archive is refused rather than silently reduced to whichever entry came first. var files = archive.Entries.Where(e => !string.IsNullOrEmpty(e.Name)).ToList(); if (files.Count == 0) throw new InvalidDataException("the archive has no file entries"); if (files.Count > 1) throw new InvalidDataException($"the archive has {files.Count} entries; Unmarshal reads a single-entry archive"); using var stream = files[0].Open(); return ReadBounded(stream, _maxDecodedBytes, FormatName); } }