| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | namespace AsyncResponse.Channels.NATS; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// The single source of truth for NATS subject and Key-Value key shapes used by the channel and the |
| | | 7 | | /// recovery store. Correlation ids are arbitrary strings, but NATS subject tokens and KV keys accept |
| | | 8 | | /// only a restricted character set, so ids are encoded with URL-safe Base64 (alphabet |
| | | 9 | | /// <c>A–Z a–z 0–9 - _</c>, no padding) — every character of which is legal in both a subject token |
| | | 10 | | /// and a KV key. Subject/key shapes are a storage contract: changing them orphans in-flight recovery |
| | | 11 | | /// state. |
| | | 12 | | /// </summary> |
| | 507 | 13 | | internal sealed class NatsSubjectSchema(string _subjectPrefix) |
| | | 14 | | { |
| | | 15 | | /// <summary>The response subject a waiter subscribes to and a publisher requests on.</summary> |
| | 1081 | 16 | | public string ResponseSubject(string correlationId) => $"{_subjectPrefix}.response.{Encode(correlationId)}"; |
| | | 17 | | |
| | | 18 | | /// <summary>The Key-Value key under which a correlation id's recovery state is stored.</summary> |
| | 934 | 19 | | public static string RecoveryKey(string correlationId) => Encode(correlationId); |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Recovers the original correlation id from a recovery Key-Value key. Returns the key verbatim |
| | | 23 | | /// when it is not valid encoded content (e.g. a key written by an older/foreign producer). |
| | | 24 | | /// </summary> |
| | 26 | 25 | | public static string CorrelationIdFromRecoveryKey(string recoveryKey) => Decode(recoveryKey) ?? recoveryKey; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// UTF-8 that FAILS on ill-formed input instead of substituting U+FFFD, in both directions. |
| | | 29 | | /// The default encoder's substitution is a correctness problem at this particular boundary: the |
| | | 30 | | /// bytes it produces are the subject a waiter subscribes to and the key its recovery state is |
| | | 31 | | /// stored under, so two ids the engine considers different — an unpaired surrogate and a |
| | | 32 | | /// literal U+FFFD — would share one subject and one key, and one conversation's response would |
| | | 33 | | /// reach the other's waiter. Validation rejects such ids at the public boundary; this makes the |
| | | 34 | | /// collision unreachable from anywhere else, including ids read back from an older store. |
| | | 35 | | /// </summary> |
| | 13 | 36 | | private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: t |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Encodes an arbitrary string to a NATS-safe token using URL-safe Base64 without padding. |
| | | 40 | | /// Implemented over <see cref="Convert.ToBase64String(byte[])"/> so it works identically on every |
| | | 41 | | /// target framework. |
| | | 42 | | /// </summary> |
| | | 43 | | public static string Encode(string value) |
| | | 44 | | { |
| | 2043 | 45 | | ArgumentException.ThrowIfNullOrWhiteSpace(value); |
| | | 46 | | |
| | 2037 | 47 | | var base64 = Convert.ToBase64String(StrictUtf8.GetBytes(value)); |
| | | 48 | | // '+' and '/' are illegal in NATS subject tokens / KV keys; '=' padding is dropped. |
| | 2035 | 49 | | return base64.Replace('+', '-').Replace('/', '_').TrimEnd('='); |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | /// <summary>Decodes a token produced by <see cref="Encode"/>, or returns <c>null</c> when it is not decodable.</sum |
| | | 53 | | public static string? Decode(string token) |
| | | 54 | | { |
| | 46 | 55 | | if (string.IsNullOrEmpty(token)) |
| | 2 | 56 | | return null; |
| | | 57 | | |
| | 44 | 58 | | var base64 = token.Replace('-', '+').Replace('_', '/'); |
| | 44 | 59 | | switch (base64.Length % 4) |
| | | 60 | | { |
| | 32 | 61 | | case 2: base64 += "=="; break; |
| | 28 | 62 | | case 3: base64 += "="; break; |
| | 2 | 63 | | case 1: return null; // never produced by Encode |
| | | 64 | | } |
| | | 65 | | |
| | | 66 | | try |
| | | 67 | | { |
| | 42 | 68 | | return StrictUtf8.GetString(Convert.FromBase64String(base64)); |
| | | 69 | | } |
| | 8 | 70 | | catch (Exception exception) when (exception is FormatException or DecoderFallbackException) |
| | | 71 | | { |
| | | 72 | | // Not base64, or base64 of something that is not UTF-8 — either way a key this schema |
| | | 73 | | // did not write. Callers fall back to treating the key verbatim. |
| | 8 | 74 | | return null; |
| | | 75 | | } |
| | 42 | 76 | | } |
| | | 77 | | } |