-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRemoteModule.cs
More file actions
522 lines (478 loc) · 17 KB
/
Copy pathRemoteModule.cs
File metadata and controls
522 lines (478 loc) · 17 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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
using System.ComponentModel;
using System.Threading.Channels;
using Repl;
using Results = Repl.Results;
namespace HostingRemoteSample;
/// <summary>
/// REPL module demonstrating shared settings, messaging, and session tracking.
/// </summary>
internal sealed class RemoteModule(
ISettingsService settings,
IMessageBus bus,
SessionTracker tracker) : IReplModule
{
public void Map(IReplMap map)
{
map.Context(
"settings",
[Description("Read and write shared settings")]
(IReplMap m) =>
{
m.Map(
"show {key}",
[Description("Read a setting value")]
(string key) =>
settings.Get(key) is { } value
? Results.Ok($"{key} = {value}")
: Results.NotFound($"Setting '{key}' not found."));
m.Map(
"set {key} {value}",
[Description("Write a setting value")]
(string key, string value) =>
{
settings.Set(key, value);
return Results.Success($"Setting '{key}' updated to '{value}'.");
});
});
map.Map(
"send {message}",
[Description("Publish a message to all watching sessions")]
(
[Description("Message to send")]
string message) =>
{
var sender = $"session-{Environment.CurrentManagedThreadId}";
bus.Publish(sender, message);
return Results.Ok("Message sent.");
});
map.Map(
"watch",
[Description("Subscribe to messages (press Enter to stop)")]
async (IReplInteractionChannel channel, CancellationToken ct) =>
{
var messages = Channel.CreateUnbounded<string>();
void Handler(string sender, string msg) =>
messages.Writer.TryWrite($"[{sender}] {msg}");
bus.OnMessage += Handler;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var displayTask = DisplayMessagesAsync(messages.Reader, channel, cts.Token);
await channel.AskTextAsync("watch-stop", "Watching... press Enter to stop");
await cts.CancelAsync();
await displayTask.ConfigureAwait(false);
}
finally
{
bus.OnMessage -= Handler;
messages.Writer.Complete();
}
return Results.Ok("Stopped watching.");
});
map.Map(
"who",
[Description("List connected sessions")]
() =>
{
var sessions = tracker.GetAllNames();
return sessions.Count == 0
? Results.Ok("No active sessions.")
: Results.Ok(string.Join('\n', sessions));
});
map.Map(
"configure",
[Description("Configure server features (interactive multi-choice)")]
async (IReplInteractionChannel channel, CancellationToken ct) =>
{
string[] featureNames = ["Authentication", "Logging", "Caching", "Metrics"];
var selected = await channel.AskMultiChoiceAsync(
"features",
"Enable features:",
["_Authentication", "_Logging", "_Caching", "_Metrics"],
defaultIndices: [0, 1]);
var labels = selected.Select(i => featureNames[i]);
return Results.Ok($"Enabled: {string.Join(", ", labels)}.");
});
map.Map(
"maintenance",
[Description("Toggle maintenance mode (interactive choice with mnemonics)")]
async (IReplInteractionChannel channel, CancellationToken ct) =>
{
var current = settings.Get("maintenance") ?? "off";
await channel.WriteStatusAsync($"Maintenance is currently: {current}", ct);
var action = await channel.AskChoiceAsync(
"action",
"What would you like to do?",
["_Enable maintenance", "_Disable maintenance", "_Cancel"],
defaultIndex: 2);
if (action is 0 or 1)
{
var value = action == 0 ? "on" : "off";
settings.Set("maintenance", value);
return Results.Success($"Maintenance set to '{value}'.");
}
return Results.Ok("Cancelled.");
});
map.Context(
"feedback",
[Description("Demonstrate hosted user feedback states")]
(IReplMap m) =>
{
m.Map(
"demo",
[Description("Run a successful feedback sequence with progress, warning, and indeterminate states")]
async (IReplInteractionChannel channel, IReplSessionInfo session, CancellationToken ct) =>
{
await channel.WriteNoticeAsync(
session.TerminalCapabilities.HasFlag(TerminalCapabilities.ProgressReporting)
? "Advanced progress reporting is available for this hosted session."
: "This client is using the text fallback for progress updates.",
ct).ConfigureAwait(false);
await BeginFeedbackDemoAsync(
channel,
"Press Enter to run a smooth feedback demo. You will see normal progress, a waiting phase, a warning phase, and a clean finish to 100%.",
"feedback-demo-start",
ct).ConfigureAwait(false);
await AnimateProgressAsync(
channel,
"Preparing session",
startPercent: 0,
endPercent: 30,
FeedbackStepDuration.InitialProgress,
ct).ConfigureAwait(false);
await channel.WriteIndeterminateProgressAsync(
"Waiting for remote worker",
"Negotiating with upstream services",
ct).ConfigureAwait(false);
await DelayFeedbackStepAsync(FeedbackStepDuration.Indeterminate, ct).ConfigureAwait(false);
await AnimateWarningProgressAsync(
channel,
"Retrying sync",
startPercent: 44,
endPercent: 72,
"Transient network jitter",
FeedbackStepDuration.Warning,
ct).ConfigureAwait(false);
await AnimateProgressAsync(
channel,
"Finalizing",
startPercent: 73,
endPercent: 96,
FeedbackStepDuration.NormalProgress,
ct).ConfigureAwait(false);
await AnimateProgressAsync(
channel,
"Completed",
startPercent: 97,
endPercent: 100,
FeedbackStepDuration.CompletedRamp,
ct).ConfigureAwait(false);
await DelayFeedbackStepAsync(FeedbackStepDuration.Completed, ct).ConfigureAwait(false);
await channel.WriteNoticeAsync("Feedback demo completed.", ct).ConfigureAwait(false);
return Results.Success("Feedback demo completed.");
});
m.Map(
"fail",
[Description("Run a failing feedback sequence with warning, error, and problem output")]
async (IReplInteractionChannel channel, CancellationToken ct) =>
{
await channel.WriteNoticeAsync(
"Starting an error-state demo. This run is expected to end in a simulated failure state.",
ct).ConfigureAwait(false);
await BeginFeedbackDemoAsync(
channel,
"Press Enter to run a demo that intentionally ends in an error state. You will see normal progress, then a warning, then a final simulated failure.",
"feedback-fail-start",
ct).ConfigureAwait(false);
await AnimateProgressAsync(
channel,
"Preparing session",
startPercent: 0,
endPercent: 28,
FeedbackStepDuration.InitialProgress,
ct).ConfigureAwait(false);
await AnimateWarningProgressAsync(
channel,
"Retrying sync",
startPercent: 36,
endPercent: 58,
"Remote worker timed out",
FeedbackStepDuration.Warning,
ct).ConfigureAwait(false);
await AnimateErrorProgressAsync(
channel,
"Remote job failed",
startPercent: 66,
endPercent: 82,
"Final retry exhausted",
FeedbackStepDuration.Error,
ct).ConfigureAwait(false);
await channel.WriteProblemAsync(
"Remote feedback demo failed",
"The remote worker stayed unavailable after several retries.",
"remote_feedback_failed",
ct).ConfigureAwait(false);
await channel.WriteNoticeAsync(
"Error-state demo complete. The failure shown above was intentional.",
ct).ConfigureAwait(false);
return Results.Success("Error-state demo completed. The failure shown above was intentional.");
});
});
map.Map(
"debug",
[Description("Show terminal capabilities for this session")]
(IReplSessionInfo session) => new StatusRow[]
{
new("AnsiSupported", session.AnsiSupported.ToString(), session.AnsiSupported ? "ok" : "warning"),
new(
"ProgressReporting",
session.TerminalCapabilities.HasFlag(TerminalCapabilities.ProgressReporting) ? "supported" : "text fallback",
session.TerminalCapabilities.HasFlag(TerminalCapabilities.ProgressReporting) ? "ok" : "idle"),
new("Capabilities", session.TerminalCapabilities.ToString(), "ok"),
new("WindowSize", session.WindowSize is { } sz ? $"{sz.Width}x{sz.Height}" : "unknown", "ok"),
new("Terminal", session.TerminalIdentity ?? "unknown", "ok"),
new("Transport", session.TransportName ?? "local", "ok"),
});
map.Map(
"sessions",
[Description("List active sessions with transport and activity details")]
(IReplSessionInfo session) =>
{
tracker.UpdateFromSession(session);
var sessions = tracker.GetAll();
return sessions.Count == 0
? (object)Results.Ok("No active sessions.")
: sessions.Select(ToSessionRow).ToArray();
});
map.Map(
"status",
[Description("Show system status (adapts to terminal width)")]
(IReplSessionInfo session) =>
{
tracker.UpdateFromSession(session);
var sessions = tracker.GetAll();
return new StatusRow[]
{
new("Sessions", $"{sessions.Count} active", sessions.Count > 0 ? "ok" : "idle"),
new("Settings", $"{settings.Count} keys", "ok"),
new("Maintenance", settings.Get("maintenance") ?? "unknown", settings.Get("maintenance") == "on" ? "warning" : "ok"),
new("Uptime", FormatUptime(), "ok"),
new("Screen", session.WindowSize is { } sz ? $"{sz.Width}x{sz.Height}" : "unknown", "ok"),
new(
"Feedback",
session.TerminalCapabilities.HasFlag(TerminalCapabilities.ProgressReporting)
? "advanced VT progress"
: "text fallback",
session.TerminalCapabilities.HasFlag(TerminalCapabilities.ProgressReporting) ? "ok" : "idle"),
new("Transport", FormatTransport(session), "ok"),
new("Terminal", FormatTerminal(session), "ok"),
new("Server", Environment.MachineName, "ok"),
new("Runtime", $".NET {Environment.Version}", "ok"),
};
});
}
private static SessionRow ToSessionRow(SessionSnapshot session)
{
var now = DateTimeOffset.UtcNow;
var connectedFor = now - session.ConnectedAtUtc;
var idleFor = now - session.LastSeenUtc;
return new SessionRow(
Name: session.Name,
Transport: session.Transport,
Remote: string.IsNullOrWhiteSpace(session.RemotePeer) ? "unknown" : session.RemotePeer!,
Screen: session.Screen ?? "unknown",
Terminal: FormatTerminal(session),
ConnectedFor: FormatDuration(connectedFor),
IdleFor: FormatDuration(idleFor));
}
private static string FormatUptime()
{
var uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);
return FormatDuration(uptime);
}
private static string FormatTerminal(IReplSessionInfo session)
{
var caps = session.TerminalCapabilities;
var identity = session.TerminalIdentity;
if (!string.IsNullOrWhiteSpace(identity))
{
return caps == TerminalCapabilities.None
? identity
: $"{identity} ({caps})";
}
return caps == TerminalCapabilities.None ? "unknown" : caps.ToString();
}
private static string FormatTransport(IReplSessionInfo session)
{
var transport = session.TransportName ?? "console";
if (string.IsNullOrWhiteSpace(session.RemotePeer))
{
return transport;
}
return $"{transport} ({session.RemotePeer})";
}
private static string FormatDuration(TimeSpan value)
{
if (value.TotalHours >= 1)
{
return $"{(int)value.TotalHours}h {value.Minutes}m";
}
if (value.TotalMinutes >= 1)
{
return $"{value.Minutes}m {value.Seconds}s";
}
return $"{Math.Max(0, value.Seconds)}s";
}
private static string FormatTerminal(SessionSnapshot session)
{
if (!string.IsNullOrWhiteSpace(session.Terminal))
{
return session.Capabilities == TerminalCapabilities.None
? session.Terminal
: $"{session.Terminal} ({session.Capabilities})";
}
return session.Capabilities == TerminalCapabilities.None
? "unknown"
: session.Capabilities.ToString();
}
private sealed record SessionRow(
[property: System.ComponentModel.DataAnnotations.Display(Name = "Session")] string Name,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Transport")] string Transport,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Remote")] string Remote,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Screen")] string Screen,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Terminal")] string Terminal,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Connected")] string ConnectedFor,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Idle")] string IdleFor);
private sealed record StatusRow(
[property: System.ComponentModel.DataAnnotations.Display(Name = "Component")] string Component,
[property: System.ComponentModel.DataAnnotations.Display(Name = "Value")] string Value,
[property: System.ComponentModel.DataAnnotations.Display(Name = "State")] string State);
private static async Task DisplayMessagesAsync(
ChannelReader<string> reader,
IReplInteractionChannel channel,
CancellationToken cancellationToken)
{
try
{
await foreach (var msg in reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
await channel.WriteStatusAsync(msg, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
// Expected when user presses Enter.
}
}
private static Task DelayFeedbackStepAsync(TimeSpan duration, CancellationToken cancellationToken) =>
Task.Delay(duration, cancellationToken);
private static async Task AnimateProgressAsync(
IReplInteractionChannel channel,
string label,
double startPercent,
double endPercent,
TimeSpan duration,
CancellationToken cancellationToken)
{
await AnimateProgressCoreAsync(
startPercent,
endPercent,
duration,
static (progressChannel, progressLabel, percent, _, ct) => progressChannel.WriteProgressAsync(progressLabel, percent, ct),
channel,
label,
details: null,
cancellationToken).ConfigureAwait(false);
}
private static async Task AnimateWarningProgressAsync(
IReplInteractionChannel channel,
string label,
double startPercent,
double endPercent,
string details,
TimeSpan duration,
CancellationToken cancellationToken)
{
await AnimateProgressCoreAsync(
startPercent,
endPercent,
duration,
static (progressChannel, progressLabel, percent, progressDetails, ct) =>
progressChannel.WriteWarningProgressAsync(progressLabel, percent, progressDetails!, ct),
channel,
label,
details,
cancellationToken).ConfigureAwait(false);
}
private static async Task AnimateErrorProgressAsync(
IReplInteractionChannel channel,
string label,
double startPercent,
double endPercent,
string details,
TimeSpan duration,
CancellationToken cancellationToken)
{
await AnimateProgressCoreAsync(
startPercent,
endPercent,
duration,
static (progressChannel, progressLabel, percent, progressDetails, ct) =>
progressChannel.WriteErrorProgressAsync(progressLabel, percent, progressDetails!, ct),
channel,
label,
details,
cancellationToken).ConfigureAwait(false);
}
private static async Task BeginFeedbackDemoAsync(
IReplInteractionChannel channel,
string instructions,
string promptName,
CancellationToken cancellationToken)
{
await channel.WriteStatusAsync(instructions, cancellationToken).ConfigureAwait(false);
await channel.AskTextAsync(promptName, "Press Enter to start").ConfigureAwait(false);
}
private static async Task AnimateProgressCoreAsync(
double startPercent,
double endPercent,
TimeSpan duration,
Func<IReplInteractionChannel, string, double, string?, CancellationToken, ValueTask> writer,
IReplInteractionChannel channel,
string label,
string? details,
CancellationToken cancellationToken)
{
var clampedStart = Math.Clamp(startPercent, 0d, 100d);
var clampedEnd = Math.Clamp(endPercent, 0d, 100d);
var direction = clampedEnd >= clampedStart ? 1 : -1;
var range = Math.Abs(clampedEnd - clampedStart);
var stepCount = Math.Max(1, (int)Math.Ceiling(range / 1.5d));
var interval = TimeSpan.FromMilliseconds(Math.Max(45d, duration.TotalMilliseconds / stepCount));
var stepSize = stepCount == 0 ? range : range / stepCount;
var percent = clampedStart;
while (true)
{
await writer(channel, label, percent, details, cancellationToken).ConfigureAwait(false);
if (Math.Abs(percent - clampedEnd) < double.Epsilon)
{
break;
}
await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
var nextPercent = percent + (stepSize * direction);
percent = direction > 0
? Math.Min(clampedEnd, nextPercent)
: Math.Max(clampedEnd, nextPercent);
}
}
private static class FeedbackStepDuration
{
public static readonly TimeSpan InitialProgress = TimeSpan.FromSeconds(1.4);
public static readonly TimeSpan Indeterminate = TimeSpan.FromSeconds(1.4);
public static readonly TimeSpan Warning = TimeSpan.FromSeconds(1.4);
public static readonly TimeSpan NormalProgress = TimeSpan.FromSeconds(1.2);
public static readonly TimeSpan CompletedRamp = TimeSpan.FromSeconds(0.4);
public static readonly TimeSpan Completed = TimeSpan.FromSeconds(1.2);
public static readonly TimeSpan Error = TimeSpan.FromSeconds(1.2);
}
}