| | | 1 | | using System; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | namespace InferenceEngine.Core.Worker; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Serializes <typeparamref name="TInput"/>/<typeparamref name="TOutput"/> across the |
| | | 8 | | /// out-of-process IPC boundary. The default <see cref="SystemTextJsonWorkerSerializer{TInput,TOutput}"/> |
| | | 9 | | /// handles <see cref="byte"/>[] as base64 (System.Text.Json's built-in) and POCOs as JSON. |
| | | 10 | | /// </summary> |
| | | 11 | | public interface IWorkerSerializer<TInput, TOutput> |
| | | 12 | | { |
| | | 13 | | string SerializeInput(TInput input); |
| | | 14 | | TInput DeserializeInput(string serialized); |
| | | 15 | | string SerializeOutput(TOutput output); |
| | | 16 | | TOutput DeserializeOutput(string serialized); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Default <see cref="IWorkerSerializer{TInput,TOutput}"/> using <see cref="JsonSerializer"/>. |
| | | 21 | | /// <see cref="byte"/>[] is serialized as a base64 string (System.Text.Json's built-in behavior), |
| | | 22 | | /// so <c>byte[]</c>→<c>List<T></c> engines (e.g. ONNX detection) work out of the box. |
| | | 23 | | /// </summary> |
| | | 24 | | public sealed class SystemTextJsonWorkerSerializer<TInput, TOutput> : IWorkerSerializer<TInput, TOutput> |
| | | 25 | | { |
| | 2 | 26 | | private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) |
| | 2 | 27 | | { |
| | 2 | 28 | | IncludeFields = true, |
| | 2 | 29 | | }; |
| | | 30 | | |
| | 10 | 31 | | public string SerializeInput(TInput input) => JsonSerializer.Serialize(input, Options); |
| | | 32 | | |
| | | 33 | | public TInput DeserializeInput(string serialized) => |
| | 6 | 34 | | JsonSerializer.Deserialize<TInput>(serialized, Options) |
| | 6 | 35 | | ?? throw new InvalidOperationException("Deserialized worker input was null."); |
| | | 36 | | |
| | 4 | 37 | | public string SerializeOutput(TOutput output) => JsonSerializer.Serialize(output, Options); |
| | | 38 | | |
| | | 39 | | public TOutput DeserializeOutput(string serialized) => |
| | 6 | 40 | | JsonSerializer.Deserialize<TOutput>(serialized, Options) |
| | 6 | 41 | | ?? throw new InvalidOperationException("Deserialized worker output was null."); |
| | | 42 | | } |