Repository navigation
Expand file tree
/
Copy pathSerializerUtilities.ClientSerializers.cs
More file actions
208 lines (176 loc) · 10 KB
/
Copy pathSerializerUtilities.ClientSerializers.cs
File metadata and controls
208 lines (176 loc) · 10 KB
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
203
204
205
206
207
208
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Testing.Platform.ServerMode;
/// <summary>
/// Client-side additions to the server's <see cref="SerializerUtilities"/>.
/// </summary>
/// <remarks>
/// The server (platform) registers serializers for the messages it <i>sends</i> and deserializers for the
/// messages it <i>receives</i>. A client is the mirror image: it must serialize the request arguments the
/// server only ever deserializes, and deserialize the response arguments the server only ever serializes.
/// This partial adds exactly those missing directions and overrides the generic <see cref="RpcMessage"/>
/// decoder with a client-oriented one (the server's drops notification params).
/// <para>
/// It is compiled ONLY into the client package, never linked into the platform, so the server is untouched.
/// Because it is a partial of <see cref="SerializerUtilities"/> it can reach the private
/// <c>Serializers</c>/<c>Deserializers</c> dictionaries and private helper methods.
/// </para>
/// </remarks>
internal static partial class SerializerUtilities
{
private static readonly object ClientSerializersLock = new();
private static volatile bool s_clientSerializersRegistered;
/// <summary>
/// Registers the client-only serializers/deserializers. Idempotent. MUST be called before
/// <see cref="FormatterUtilities.CreateFormatter"/> so the System.Text.Json formatter (on .NET) snapshots
/// the request-argument serializer types when it is constructed.
/// </summary>
public static void RegisterClientSerializers()
{
if (s_clientSerializersRegistered)
{
return;
}
lock (ClientSerializersLock)
{
if (s_clientSerializersRegistered)
{
return;
}
RegisterClientSerializersCore();
// Publish LAST: set the flag only after every registration is in place, so a racing caller that
// reads the (volatile) flag without the lock can never observe a half-populated serializer set.
// The Serializers/Deserializers dictionaries are not concurrent, and FormatterUtilities snapshots
// them when it is constructed, so a torn read here would silently drop a serializer.
s_clientSerializersRegistered = true;
}
}
private static void RegisterClientSerializersCore()
{
// --- Request-argument serializers (the server only deserializes these; the client sends them). ---
Serializers[typeof(ClientInfo)] = new ObjectSerializer<ClientInfo>(info => new Dictionary<string, object?>
{
[JsonRpcStrings.Name] = info.Name,
[JsonRpcStrings.Version] = info.Version,
});
Serializers[typeof(ClientCapabilities)] = new ObjectSerializer<ClientCapabilities>(capabilities =>
{
Dictionary<string, object?> testingCapabilities = new()
{
[JsonRpcStrings.DebuggerProvider] = capabilities.DebuggerProvider,
};
if (capabilities.IsStateful is { } isStateful)
{
testingCapabilities[JsonRpcStrings.IsStateful] = isStateful;
}
return new Dictionary<string, object?>
{
[JsonRpcStrings.Testing] = testingCapabilities,
};
});
Serializers[typeof(InitializeRequestArgs)] = new ObjectSerializer<InitializeRequestArgs>(args =>
{
Dictionary<string, object?> properties = new()
{
[JsonRpcStrings.ProcessId] = args.ProcessId,
[JsonRpcStrings.ClientInfo] = Serialize(args.ClientInfo),
[JsonRpcStrings.Capabilities] = Serialize(args.Capabilities),
};
if (args.ProtocolVersions is not null)
{
properties[JsonRpcStrings.ProtocolVersions] = args.ProtocolVersions;
}
return properties;
});
Serializers[typeof(DiscoverRequestArgs)] = new ObjectSerializer<DiscoverRequestArgs>(SerializeRequestArgs);
Serializers[typeof(RunRequestArgs)] = new ObjectSerializer<RunRequestArgs>(SerializeRequestArgs);
// Exit is a parameterless notification; register an (empty) serializer so a caller may pass an
// ExitRequestArgs instance as the notification params without tripping the missing-serializer path.
Serializers[typeof(ExitRequestArgs)] = new ObjectSerializer<ExitRequestArgs>(_ => new Dictionary<string, object?>());
// A server-initiated request (e.g. client/attachDebugger) may be answered with a NON-null result.
// ResponseMessage serialization resolves the serializer by the result's runtime type, so register a
// pass-through for the dictionary shape a handler returns; without it a non-null result would throw
// KeyNotFoundException and hang the response write. Handlers that answer a server request MUST return
// a Dictionary<string, object?> (or null); any other runtime type has no registered serializer.
Serializers[typeof(Dictionary<string, object?>)] = new ObjectSerializer<Dictionary<string, object?>>(result => result);
// --- Response deserializers (the server only serializes these; the client decodes them). ---
Deserializers[typeof(Artifact)] = new ObjectDeserializer<Artifact>(properties => new Artifact(
Uri: GetOptionalPropertyFromJson(properties, JsonRpcStrings.Uri) as string ?? string.Empty,
Producer: GetOptionalPropertyFromJson(properties, JsonRpcStrings.Producer) as string ?? string.Empty,
Type: GetOptionalPropertyFromJson(properties, JsonRpcStrings.Type) as string ?? string.Empty,
DisplayName: GetOptionalPropertyFromJson(properties, JsonRpcStrings.DisplayName) as string ?? string.Empty,
Description: GetOptionalPropertyFromJson(properties, JsonRpcStrings.Description) as string));
Deserializers[typeof(DiscoverResponseArgs)] = new ObjectDeserializer<DiscoverResponseArgs>(_ => new DiscoverResponseArgs());
Deserializers[typeof(RunResponseArgs)] = new ObjectDeserializer<RunResponseArgs>(properties =>
{
var attachments = GetOptionalPropertyFromJson(properties, JsonRpcStrings.Attachments) as ICollection<object>;
Artifact[] artifacts = attachments?
.OfType<IDictionary<string, object?>>()
.Select(attachment => Deserialize<Artifact>(attachment))
.ToArray() ?? [];
return new RunResponseArgs(artifacts);
});
// --- Override the generic RpcMessage decoder with a client-oriented one. ---
// The server's decoder (SerializerUtilities.Deserializers.cs) is written from the server's point of
// view: its method switch only knows the requests a *server* receives and returns null (dropping the
// params) for every other method. A client instead receives notifications
// (testing/testUpdates/tests, client/log, telemetry/update, testing/testUpdates/attachments) and
// server-initiated requests (client/attachDebugger, client/launchDebugger) whose params it must keep.
// We therefore preserve the raw params dictionary and let the client typed-deserialize per method.
Deserializers[typeof(RpcMessage)] = new ObjectDeserializer<RpcMessage>(properties =>
{
ValidateJsonRpcHeader(properties);
if (properties.ContainsKey(JsonRpcStrings.Error)
&& properties.TryGetValue(JsonRpcStrings.Id, out object? errorId)
&& errorId is null)
{
return Deserialize<ErrorMessage>(properties);
}
if (properties.TryGetValue(JsonRpcStrings.Method, out object? methodObj) && methodObj is not null)
{
string method = (string)methodObj;
bool hasId = properties.TryGetValue(JsonRpcStrings.Id, out object? idObj);
if (hasId && idObj is null)
{
throw new MessageFormatException($"'{JsonRpcStrings.Id}' field cannot be null");
}
// Keep the params as the raw dictionary; the client decodes it based on the method name.
object? @params = GetOptionalPropertyFromJson(properties, JsonRpcStrings.Params);
int? id = !hasId
? null
: GetIdFromJson(idObj) ?? throw new MessageFormatException("id field should be a string or an int");
return id.HasValue
? new RequestMessage(id.Value, method, @params) { StringId = idObj as string }
: new NotificationMessage(method, @params);
}
else if (properties.TryGetValue(JsonRpcStrings.Error, out _))
{
return Deserialize<ErrorMessage>(properties);
}
else if (properties.TryGetValue(JsonRpcStrings.Result, out object? resultObj))
{
object? idObj = GetRequiredPropertyFromJson<object?>(properties, JsonRpcStrings.Id);
var result = resultObj as IDictionary<string, object?>;
int id = GetIdFromJson(idObj) ?? throw new MessageFormatException("id field should be a string or an int");
return new ResponseMessage(id, result) { StringId = idObj as string };
}
throw new MessageFormatException();
});
}
private static IDictionary<string, object?> SerializeRequestArgs(RequestArgsBase args)
{
Dictionary<string, object?> properties = new()
{
[JsonRpcStrings.RunId] = args.RunId.ToString(),
};
if (args.TestNodes is not null)
{
properties[JsonRpcStrings.Tests] = args.TestNodes.Select(node => Serialize(node)).ToList<object>();
}
if (args.GraphFilter is not null)
{
properties[JsonRpcStrings.Filter] = args.GraphFilter;
}
return properties;
}
}