-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileEnvironment.cs
361 lines (292 loc) · 13.6 KB
/
FileEnvironment.cs
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Tbc.Core.Models;
using Tbc.Host.Components.Abstractions;
using Tbc.Host.Components.CommandProcessor;
using Tbc.Host.Components.CommandProcessor.Models;
using Tbc.Host.Components.FileEnvironment.Models;
using Tbc.Host.Components.FileWatcher;
using Tbc.Host.Components.FileWatcher.Models;
using Tbc.Host.Components.IncrementalCompiler;
using Tbc.Host.Components.IncrementalCompiler.Models;
using Tbc.Host.Components.TargetClient;
using Tbc.Host.Extensions;
namespace Tbc.Host.Components.FileEnvironment
{
public partial class FileEnvironment : TransientComponentBase<FileEnvironment>, IFileEnvironment, IExposeCommands, IHaveComponentsThatExposeCommands
{
public ITargetClient Client { get; }
public ICommandProcessor CommandProcessor { get; }
public IFileWatcher FileWatcher { get; }
public IIncrementalCompiler IncrementalCompiler { get; }
public IFileSystem FileSystem { get; set; }
public FileEnvironment(IRemoteClientDefinition client,
IFileWatcher fileWatcher, ICommandProcessor commandProcessor,
Func<IRemoteClientDefinition, ITargetClient> targetClientFactory,
Func<string, IIncrementalCompiler> incrementalCompilerFactory,
ILogger<FileEnvironment> logger, IFileSystem fileSystem) : base(logger)
{
Client = targetClientFactory(client);
CommandProcessor = commandProcessor;
FileSystem = fileSystem;
FileWatcher = fileWatcher;
IncrementalCompiler = incrementalCompilerFactory($"{client.Address}:{client.Port}");
IncrementalCompiler.SetRootPath(FileWatcher.WatchPath);
}
private bool _running;
public bool Terminated { get; set; }
private string? _primaryTypeHint;
private EmittedAssembly? _lastEmittedAssembly;
private string? _loadContext;
public async Task Run()
{
if (_running)
throw new InvalidOperationException("Already running");
_running = true;
Logger.LogInformation("Waiting for channel to be established with target client {Client}", Client);
await Client.WaitForConnection();
await TryLoadLoadContext();
Task.Factory.StartNew(SetupReferenceTracking, TaskCreationOptions.LongRunning)
.FireAndForgetSafeAsync();
FileWatcher
.Changes
.Where(_ => !Terminated)
.Select(IncrementalCompiler.StageFile)
.Where(x => x != null)
.SelectMany(SendAssemblyForReload!)
.Subscribe(x => Logger.Log(x.Success ? LogLevel.Information : LogLevel.Error, "Send incremental assembly outcome: {@Outcome}", x));
Logger.LogInformation("FileEnvironment for client {@Client} initialised", Client);
Task.Factory.StartNew(SetupCommandListening, TaskCreationOptions.LongRunning)
.FireAndForgetSafeAsync();
await Client.WaitForTerminalState();
Terminated = true;
Logger.LogWarning("FileEnvironment for client {@Client} terminating", Client);
}
private async Task TryLoadLoadContext()
{
if (!String.IsNullOrWhiteSpace(_loadContext))
{
var ctx = JsonConvert.DeserializeObject<PersistedContext>(
await File.ReadAllTextAsync($"{_loadContext}.json"));
foreach (var file in ctx.WatchedFiles.Select(x => new ChangedFile { Path = x, Contents = File.ReadAllText(x) }))
IncrementalCompiler.StageFile(file, silent: true);
await SetPrimaryTypeHint(ctx.PrimaryTypeHint);
}
}
public async Task Reset()
{
Logger.LogInformation("Resetting incremental compiler state");
IncrementalCompiler.ClearTrees();
IncrementalCompiler.ClearReferences();
await TryLoadLoadContext();
Task.Factory.StartNew(SetupReferenceTracking, TaskCreationOptions.LongRunning).FireAndForgetSafeAsync();
Task.Factory.StartNew(SetupCommandListening, TaskCreationOptions.LongRunning).FireAndForgetSafeAsync();
}
public async Task SetupReferenceTracking()
{
Logger.LogInformation("Setting up reference tracking for client {Client}", Client);
IncrementalCompiler.ClearReferences();
var seen = new HashSet<string>();
var tempFilePath = FileSystem.Path.GetTempFileName();
var targetHello = await Client.Hello(new HostHello { SharedHostFilePath = tempFilePath });
var sharedFilesystem = targetHello.CanAccessSharedHostFile;
var existingReferences = new List<AssemblyReference>();
if (sharedFilesystem && targetHello.UseSharedFilesystemDependencyResolution)
{
await AddSharedFilesystemReference(targetHello, existingReferences);
foreach (var refSeen in existingReferences.Select(x => x.AssemblyLocation))
seen.Add(refSeen);
// allow a little time for references to come back <:-)
// should have client tell us when all current dependencies have been sent
Task.Delay(TimeSpan.FromSeconds(.33)).ContinueWith(_ => IncrementalCompiler.DoWarmup())
.FireAndForgetSafeAsync();
}
if (targetHello.UseDependencyCache && targetHello.ApplicationIdentifier is { } appIdentifier)
ProcessDependencyCache(appIdentifier);
var iterator = await Client.AssemblyReferences(existingReferences);
try
{
await iterator.ForEachAsync(async asm =>
{
if (Terminated)
return;
if (seen.Contains(asm.AssemblyName) ||
(sharedFilesystem && !String.IsNullOrWhiteSpace(asm.AssemblyLocation) && seen.Contains(asm.AssemblyLocation)))
{
Logger.LogInformation("Not adding reference at {Path} because it has already been seen", asm.AssemblyLocation);
return;
}
else
seen.Add(asm.AssemblyName);
Logger.LogInformation(
"Adding reference to {AssemblyName} from {AssemblyLocation} for client {Client}",
asm.AssemblyName, asm.AssemblyLocation, Client.ClientDefinition);
if (sharedFilesystem && targetHello.UseSharedFilesystemDependencyResolution && asm.PeBytes is null)
asm = asm with { PeBytes = await FileSystem.File.ReadAllBytesAsync(asm.AssemblyLocation) };
IncrementalCompiler.AddMetadataReference(asm);
});
}
catch (Exception ex)
{
if (!Terminated)
Logger.LogError(ex, nameof(SetupReferenceTracking));
}
}
public async Task SetupCommandListening()
{
Logger.LogInformation("Setting up command listening for client {Client}", Client);
var iterator = await Client.CommandRequests();
try
{
var enumerator = iterator.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync() && !Terminated)
{
var request = enumerator.Current;
Logger.LogInformation(
"Received command request {@Request} from target {Client}",
request, Client.ClientDefinition);
// doh
await CommandProcessor.HandleCommand($"{request.Command} {String.Join(" ", request.Args)}");
}
}
catch (Exception ex)
{
if (!Terminated)
Logger.LogError(ex, nameof(SetupCommandListening));
}
}
public async Task<Outcome> SendAssemblyForReload(EmittedAssembly asm)
{
_lastEmittedAssembly = asm;
var req = new LoadDynamicAssemblyRequest
{
AssemblyName = asm.AssemblyName,
PeBytes = asm.Pe,
PdbBytes = asm.Pd,
PrimaryTypeName =
String.IsNullOrWhiteSpace(_primaryTypeHint)
? null
: TryResolvePrimaryType(_primaryTypeHint)
};
return await Client.RequestClientLoadAssemblyAsync(req);
}
public string? TryResolvePrimaryType(string typeHint)
=> IncrementalCompiler.TryResolvePrimaryType(typeHint);
public Task PrintTrees(bool withDetail = false)
{
IncrementalCompiler.PrintTrees(withDetail);
return Task.CompletedTask;
}
public async Task SetPrimaryTypeHint(string? maybeTypeHint)
{
_primaryTypeHint = maybeTypeHint;
if (_lastEmittedAssembly != null)
await SendAssemblyForReload(_lastEmittedAssembly);
}
string IExposeCommands.Identifier
=> $"env-{Client.ClientDefinition.Address}-{Client.ClientDefinition.Port}";
IEnumerable<TbcCommand> IExposeCommands.Commands => new List<TbcCommand>
{
new TbcCommand
{
Command = "reset",
Execute = delegate { return Reset(); }
},
new TbcCommand
{
Command = "primary",
Execute = async (cmd, args) => { await SetPrimaryTypeHint(args[0]); }
},
new TbcCommand
{
Command = "run-on-target",
Execute = async (cmd, args) =>
{
var req = new ExecuteCommandRequest
{
Command = cmd
};
foreach (var arg in args)
req.Args.Add(arg);
var outcome = await Client.RequestClientExecAsync(req);
Logger.LogInformation("Command {Command} success: {@Outcome}", cmd, outcome.Success);
foreach (var message in outcome.Messages)
Logger.LogInformation("{Message}", message.Message);
}
},
new TbcCommand
{
Command = "context",
Execute = (_, args) =>
{
if (!args.Any())
Logger.LogWarning("Need subcommand for context operation");
var sub = args[0];
switch (sub)
{
case "load":
var toLoad = args[1];
SetLoadContext(toLoad);
break;
case "save":
var toSave = args[1];
SaveContext(toSave);
break;
default:
Logger.LogWarning("Don't know how to handle subcommand '{SubCommand}' of context", sub);
break;
}
return Task.CompletedTask;
}
}
};
public void SaveContext(string saveIdentifier)
{
var ctx = new PersistedContext
{
PrimaryTypeHint = _primaryTypeHint,
WatchedFiles = IncrementalCompiler.StagedFiles
};
File.WriteAllText($"{saveIdentifier}.json", ctx.ToJson());
}
public void SetLoadContext(string saveIdentifier)
{
_loadContext = saveIdentifier;
Reset().FireAndForgetSafeAsync();
}
public IEnumerable<IExposeCommands> Components
=> new object [] { IncrementalCompiler, FileWatcher }.OfType<IExposeCommands>();
private static void ProcessDependencyCache(string appId)
{
// todo :)
}
private async Task AddSharedFilesystemReference(TargetHello targetHello, List<AssemblyReference> existingReferences)
{
Logger.LogInformation("Target and host share filesystem, attempting to preload dependencies");
var files = FileSystem.Directory.GetFiles(targetHello.RootAssemblyPath, "*.dll");
foreach (var f in files)
{
var reference = new AssemblyReference
{
AssemblyLocation = f,
ModificationTime = FileSystem.FileInfo.FromFileName(f).LastWriteTime,
PeBytes = await FileSystem.File.ReadAllBytesAsync(f)
};
IncrementalCompiler.AddMetadataReference(reference);
existingReferences.Add(reference);
}
}
}
public class PersistedContext
{
public string? PrimaryTypeHint { get; set; }
public List<string> WatchedFiles { get; set; } = new();
}
}