-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
526 lines (504 loc) · 19.7 KB
/
Copy pathProgram.cs
File metadata and controls
526 lines (504 loc) · 19.7 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
523
524
525
526
using HarMockApi;
using HarMockApi.Services;
using Microsoft.AspNetCore.SignalR;
using System.Text.Json;
CliOptions? cli = null;
if (Cli.IsCli(args))
{
try { cli = Cli.Parse(args); }
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}\nRun 'har-mock help' for usage.");
Environment.ExitCode = 2;
return;
}
if (cli.Command is "help" or "--help" or "-h") { Cli.Help(); Environment.ExitCode = 0; return; }
if (cli.Command is "version" or "--version") { Console.WriteLine("har-mock 1.0.0"); Environment.ExitCode = 0; return; }
if (cli.Command is "push" or "list" or "delete")
{
Environment.ExitCode = await Cli.ExecuteRemoteAsync(cli);
return;
}
}
var webArgs = cli?.Command == "run" ? Array.Empty<string>() : args;
var builder = WebApplication.CreateBuilder(webArgs);
if (cli?.Command == "run")
{
builder.WebHost.UseUrls($"http://127.0.0.1:{cli.Port}");
builder.Configuration["HarMock:DataPath"] = Path.Combine(Path.GetTempPath(), "har-mock", Guid.NewGuid().ToString("N"));
}
builder.Services.AddSingleton<HarParser>();
builder.Services.AddSingleton<HarStore>();
builder.Services.AddSingleton<HarActivityLogger>();
builder.Services.AddSignalR();
builder.Services.AddHealthChecks();
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.WriteIndented = true);
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = builder.Configuration.GetValue("HarMock:MaxUploadBytes", 100L * 1024 * 1024) + 1024 * 1024);
var app = builder.Build();
var store = app.Services.GetRequiredService<HarStore>();
var logger = app.Services.GetRequiredService<HarActivityLogger>();
await store.InitializeAsync();
if (cli?.Command == "run")
{
await using var localHar = File.OpenRead(cli.File!);
var imported = await store.LoadAsync("default", "default", localHar, cli.Host, default);
Console.WriteLine($"✓ Loaded {Path.GetFileName(cli.File)}");
Console.WriteLine($"✓ {imported.Environment.Routes} routes");
Console.WriteLine($"✓ Mock API: http://127.0.0.1:{cli.Port}");
Console.WriteLine(" Press Ctrl+C to stop.\n");
}
// Repo-bundled HARs: Har/{application}/{environment}.har. Loaded only when not already persisted.
var bundled = Path.Combine(app.Environment.ContentRootPath, "Har");
if (Directory.Exists(bundled))
foreach (var file in Directory.EnumerateFiles(bundled, "*.har", SearchOption.AllDirectories))
{
var rel = Path.GetRelativePath(bundled, file).Split(Path.DirectorySeparatorChar);
if (rel.Length != 2) continue;
var application = rel[0]; var environment = Path.GetFileNameWithoutExtension(rel[1]);
if (!Names.Valid(application) || !Names.Valid(environment) || store.Get(application, environment) is not null) continue;
await using var fs = File.OpenRead(file); try { await store.LoadAsync(application, environment, fs, null, default); } catch (Exception ex) { app.Logger.LogWarning(ex, "Could not load bundled HAR {File}", file); }
}
app.MapHealthChecks("/health");
var management = app.MapGroup("/_har");
management.AddEndpointFilter(async (context, next) =>
{
var configured = app.Configuration["HarMock:ManagementApiKey"];
if (string.IsNullOrEmpty(configured)) return await next(context);
var http = context.HttpContext;
if (!http.Request.Headers.TryGetValue("X-Api-Key", out var supplied) || !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(System.Text.Encoding.UTF8.GetBytes(configured), System.Text.Encoding.UTF8.GetBytes(supplied.ToString())))
return Results.Json(new { error = "Management API key required." }, statusCode: 401);
return await next(context);
});
management.MapGet("/", (HttpRequest r) => Results.Text(Html.Index(store.List(), logger.Recent(), $"{r.Scheme}://{r.Host}"), "text/html"));
management.MapGet("/environments", () => Results.Ok(store.List()));
management.MapGet("/activity", () => Results.Ok(logger.Recent()));
app.MapHub<HarActivityHub>("/hubs/har-mock");
management.MapGet("/{application}/{environment}", (string application, string environment) => store.Get(application, environment) is { } info ? Results.Ok(info) : Results.NotFound());
management.MapPost("/{application}/{environment}", async (string application, string environment, HttpRequest request, HarStore s, CancellationToken ct) =>
{
try
{
Stream source;
if (request.HasFormContentType) { var form = await request.ReadFormAsync(ct); var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); if (file is null) return Results.BadRequest(new { error = "Multipart request must contain a HAR file in field 'file'." }); source = file.OpenReadStream(); }
else source = request.Body;
var result = await s.LoadAsync(application, environment, source, request.Query["host"].FirstOrDefault(), ct);
return Results.Ok(result);
}
catch (Exception ex) when (ex is JsonException or InvalidDataException or ArgumentException) { return Results.BadRequest(new { error = ex.Message }); }
});
management.MapDelete("/{application}/{environment}", (string application, string environment) => store.Remove(application, environment) ? Results.NoContent() : Results.NotFound());
// Local CLI mode exposes the HAR at the root so the application only changes its origin/base URL.
if (cli?.Command == "run")
app.Map("/{**path}", async (string? path, HttpContext ctx, HarStore s) =>
{
var mockPath = "/" + (path ?? "");
var match = await s.MatchAsync("default", "default", ctx.Request, mockPath, ctx.RequestAborted);
logger.Record("default", "default", ctx.Request.Method, mockPath, match.Found ? match.Response?.StatusCode ?? 200 : 404, match.Found, match.Found ? "matched" : (match.Reason ?? "miss"));
await WriteMockAsync(ctx, match, "default", "default", mockPath);
});
else
// Shared mode uses application/environment namespaces. The prefix is stripped before HAR matching.
app.Map("/{application}/{environment}/{**path}", async (string application, string environment, string? path, HttpContext ctx, HarStore s) =>
{
var mockPath = "/" + (path ?? "");
var match = await s.MatchAsync(application, environment, ctx.Request, mockPath, ctx.RequestAborted);
logger.Record(application, environment, ctx.Request.Method, mockPath, match.Found ? match.Response?.StatusCode ?? 200 : 404, match.Found, match.Found ? "matched" : (match.Reason ?? "miss"));
await WriteMockAsync(ctx, match, application, environment, mockPath);
});
app.Run();
static async Task WriteMockAsync(HttpContext ctx, MatchResult match, string application, string environment, string mockPath)
{
if (!match.Found || match.Response is null)
{
ctx.Response.StatusCode = 404;
await ctx.Response.WriteAsJsonAsync(new { error = "No HAR response matched this request.", reason = match.Reason, application, environment, method = ctx.Request.Method, path = mockPath, query = ctx.Request.QueryString.Value, closestMatches = match.Suggestions }, ctx.RequestAborted);
return;
}
var response = match.Response; ctx.Response.StatusCode = response.StatusCode;
if (!string.IsNullOrWhiteSpace(response.ContentType)) ctx.Response.ContentType = response.ContentType;
foreach (var h in response.Headers)
{
if (h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase) || h.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) || h.Key.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase) || h.Key.Equals("Connection", StringComparison.OrdinalIgnoreCase)) continue;
try { ctx.Response.Headers[h.Key] = h.Value; } catch { }
}
ctx.Response.ContentLength = response.Body.LongLength;
if (!HttpMethods.IsHead(ctx.Request.Method)) await ctx.Response.Body.WriteAsync(response.Body, ctx.RequestAborted);
}
static class Html
{
public static string Index(IReadOnlyList<HarMockApi.Models.EnvironmentInfo> envs, IReadOnlyList<HarActivityEntry> activity, string origin) => $$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HAR Mock // status</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js"></script>
<style>
:root {
--bg: #090909;
--bg-2: #12110a;
--panel: #121210;
--panel-2: #18170d;
--line: #5c4d14;
--line-soft: rgba(249, 211, 66, 0.28);
--fg: #ffd749;
--fg-soft: #ffe292;
--muted: #e4c867;
--white: #fff7cf;
--shadow: rgba(255, 205, 60, 0.35);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at top, rgba(255, 214, 74, 0.12), transparent 42%),
linear-gradient(180deg, #11110d 0%, var(--bg) 100%);
color: var(--fg);
font: 15px/1.5 "Consolas", "SFMono-Regular", "Menlo", monospace;
}
body {
min-height: 100vh;
padding: 32px 20px;
}
.wrap {
max-width: 1100px;
margin: 0 auto;
border: 1px solid var(--line-soft);
background: linear-gradient(180deg, rgba(18,18,16,0.98), rgba(12,12,10,0.98));
box-shadow: 0 0 0 1px rgba(255, 215, 90, 0.12), 0 0 30px rgba(255, 215, 90, 0.12);
position: relative;
overflow: hidden;
}
.wrap::before {
content: "";
position: absolute;
inset: 0;
background: repeating-linear-gradient(
to bottom,
rgba(255, 215, 90, 0.04),
rgba(255, 215, 90, 0.04) 2px,
transparent 2px,
transparent 4px
);
pointer-events: none;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid var(--line-soft);
padding: 12px 18px;
background: rgba(17, 14, 6, 0.9);
letter-spacing: 0.16em;
text-transform: uppercase;
font-size: 11px;
color: var(--muted);
position: relative;
z-index: 1;
}
.topbar-left {
display: flex;
align-items: center;
gap: 10px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--fg);
box-shadow: 0 0 10px rgba(255, 215, 90, 0.8);
}
.main {
padding: 24px 20px 20px;
position: relative;
z-index: 1;
}
.headline {
display: flex;
justify-content: space-between;
gap: 20px;
align-items: end;
margin-bottom: 18px;
border-bottom: 1px solid var(--line-soft);
padding-bottom: 16px;
}
h1 {
margin: 0;
font-weight: 700;
font-size: clamp(23px, 2.9vw, 38px);
letter-spacing: 0.12em;
text-transform: uppercase;
text-shadow: 0 0 14px rgba(255, 215, 90, 0.2);
}
.status {
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--fg-soft);
border: 1px solid var(--line-soft);
background: rgba(255, 215, 90, 0.06);
padding: 8px 10px;
box-shadow: inset 0 0 14px rgba(255, 215, 90, 0.08);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin: 20px 0 22px;
}
.card {
background: linear-gradient(180deg, rgba(29, 27, 17, 0.9), rgba(18, 18, 14, 0.9));
border: 1px solid var(--line-soft);
padding: 14px 16px;
box-shadow: inset 0 0 18px rgba(255, 215, 90, 0.03);
}
.label {
color: var(--muted);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.12em;
margin-bottom: 10px;
}
.value {
font-size: 20px;
color: var(--white);
word-break: break-word;
}
.upload-panel {
margin-top: 22px;
border: 1px solid var(--line-soft);
background: rgba(11, 11, 9, 0.96);
padding: 12px;
}
.upload-header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 10px;
border-bottom: 1px solid var(--line-soft);
text-transform: uppercase;
letter-spacing: 0.12em;
font-size: 11px;
color: var(--muted);
}
.upload-grid {
display: grid;
grid-template-columns: 160px 160px 1fr auto;
gap: 10px;
margin-top: 12px;
align-items: center;
}
.upload-grid input, .upload-grid button {
width: 100%;
background: rgba(255, 215, 90, 0.04);
color: var(--white);
border: 1px solid var(--line-soft);
padding: 9px 10px;
font: inherit;
}
.upload-grid button {
cursor: pointer;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--fg);
background: rgba(255, 215, 90, 0.1);
}
.upload-status {
margin-top: 10px;
color: var(--fg-soft);
min-height: 20px;
font-size: 12px;
}
.feed {
margin-top: 22px;
border: 1px solid var(--line-soft);
background: rgba(11, 11, 9, 0.96);
max-height: 320px;
overflow: auto;
font-size: 13px;
}
.feed-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
border-bottom: 1px solid var(--line-soft);
text-transform: uppercase;
letter-spacing: 0.12em;
font-size: 11px;
color: var(--muted);
background: rgba(255, 215, 90, 0.04);
}
.feed-entry {
display: grid;
grid-template-columns: 130px 90px 100px 140px 1fr 52px;
gap: 10px;
padding: 8px 12px;
border-bottom: 1px solid rgba(255, 215, 90, 0.08);
font-family: "Consolas", "SFMono-Regular", monospace;
}
.feed-entry:last-child { border-bottom: none; }
.feed-entry .ok { color: #b8ff7d; }
.feed-entry .miss { color: #ff9b7a; }
.codeblock {
background: #0f0f0d;
border: 1px solid var(--line);
padding: 16px 18px;
margin: 18px 0 24px;
white-space: pre-wrap;
word-break: break-word;
color: var(--fg-soft);
}
code {
font-family: "Consolas", "SFMono-Regular", monospace;
background: rgba(249, 211, 66, 0.08);
border: 1px solid rgba(249, 211, 66, 0.14);
padding: 2px 6px;
color: var(--fg-soft);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
border: 1px solid var(--line);
background: var(--panel);
}
th, td {
text-align: left;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
th {
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 11px;
background: rgba(249, 211, 66, 0.05);
}
tr:last-child td { border-bottom: none; }
.muted { color: var(--muted); }
@media (max-width: 700px) {
.headline { display:block; }
.status { margin-top: 12px; display:inline-block; }
th, td { padding: 8px 10px; }
}
</style>
</head>
<body>
<div class="wrap">
<div class="topbar">
<div class="topbar-left"><span class="dot"></span>HarMock // console</div>
</div>
<div class="main">
<div class="headline">
<h1>HAR Mock</h1>
<div class="status">status: online</div>
</div>
<div class="grid">
<div class="card">
<div class="label">server</div>
<div class="value">{{origin}}</div>
</div>
<div class="card">
<div class="label">environments</div>
<div class="value">{{envs.Count}}</div>
</div>
<div class="card">
<div class="label">routes</div>
<div class="value">{{envs.Sum(e => e.Routes)}}</div>
</div>
</div>
<div class="codeblock">
POST {{origin}}/_har/{{"{application}/"}}{{"{environment}"}}
# with multipart field "file"
curl -X POST "{{origin}}/_har/checkout/qa" \
-F "file=@checkout.har"
curl "{{origin}}/checkout/qa/api/cart"
</div>
<div class="upload-panel">
<div class="upload-header"><span>upload HAR</span><span>browser</span></div>
<form id="uploadForm" class="upload-grid">
<input id="uploadApp" type="text" value="demo" aria-label="application name" placeholder="app" />
<input id="uploadEnv" type="text" value="qa" aria-label="environment name" placeholder="env" />
<input id="uploadFile" type="file" accept=".har,application/json" aria-label="HAR file" />
<button type="submit">upload</button>
</form>
<div id="uploadStatus" class="upload-status">ready for upload</div>
</div>
<div class="feed">
<div class="feed-header"><span>activity</span><span id="feed-count">{{activity.Count}} events</span></div>
<div id="feed-body">
{{string.Join("", activity.Select(e => $"<div class=\"feed-entry\"><span>{E(e.Timestamp[..19].Replace("T", " "))}</span><span>{E(e.Method)}</span><span>{E(e.Application)}/{E(e.Environment)}</span><span>{E(e.Path)}</span><span class=\"{(e.Matched ? "ok" : "miss")}\">{E(e.Outcome)} = {e.StatusCode}</span><span>{(e.Matched ? "hit" : "miss")}</span></div>"))}}
</div>
</div>
<table>
<thead>
<tr>
<th>App</th>
<th>Env</th>
<th>Routes</th>
<th>Primary host</th>
<th>Base URL</th>
</tr>
</thead>
<tbody>
{{string.Join("", envs.Select(e => $"<tr><td>{E(e.Application)}</td><td>{E(e.Environment)}</td><td>{e.Routes}</td><td>{E(e.PrimaryHost ?? "")}</td><td><code>{E(origin)}/{E(e.Application)}/{E(e.Environment)}</code></td></tr>"))}}
</tbody>
</table>
</div>
</div>
<script>
const feedBody = document.getElementById('feed-body');
const feedCount = document.getElementById('feed-count');
const uploadForm = document.getElementById('uploadForm');
const uploadStatus = document.getElementById('uploadStatus');
const addEntry = (entry) => {
const row = document.createElement('div');
row.className = 'feed-entry';
const hit = entry.matched ? 'ok' : 'miss';
row.innerHTML = `<span>${new Date(entry.timestamp).toLocaleString()}</span><span>${entry.method}</span><span>${entry.application}/${entry.environment}</span><span>${entry.path}</span><span class="${hit}">${entry.outcome} = ${entry.statusCode}</span><span>${entry.matched ? 'hit' : 'miss'}</span>`;
feedBody.prepend(row);
while (feedBody.children.length > 40) feedBody.removeChild(feedBody.lastChild);
feedCount.textContent = `${feedBody.children.length} events`;
};
uploadForm.addEventListener('submit', async (event) => {
event.preventDefault();
const app = document.getElementById('uploadApp').value.trim() || 'demo';
const env = document.getElementById('uploadEnv').value.trim() || 'qa';
const file = document.getElementById('uploadFile').files[0];
if (!file) {
uploadStatus.textContent = 'choose a HAR file first';
return;
}
const formData = new FormData();
formData.append('file', file);
uploadStatus.textContent = 'uploading...';
try {
const response = await fetch(`/_har/${encodeURIComponent(app)}/${encodeURIComponent(env)}`, {
method: 'POST',
body: formData
});
const data = await response.json().catch(() => ({}));
uploadStatus.textContent = response.ok ? `uploaded ${app}/${env}` : (data.error || 'upload failed');
if (response.ok) {
setTimeout(() => window.location.reload(), 300);
}
} catch (err) {
uploadStatus.textContent = 'upload failed';
}
});
const connection = new signalR.HubConnectionBuilder()
.withUrl('/hubs/har-mock')
.withAutomaticReconnect()
.build();
connection.on('activity', addEntry);
connection.start().catch(err => console.error('SignalR connect failed', err));
</script>
</body>
</html>
""";
private static string E(string s) => System.Net.WebUtility.HtmlEncode(s);
}