forked from dotnet/interactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVariableRouter.cs
More file actions
187 lines (166 loc) · 6.8 KB
/
VariableRouter.cs
File metadata and controls
187 lines (166 loc) · 6.8 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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.Events;
using Microsoft.DotNet.Interactive.Formatting;
namespace Microsoft.DotNet.Interactive.Http;
internal class VariableRouter : IRouter
{
private static readonly JsonSerializerOptions SerializerOptions;
static VariableRouter()
{
SerializerOptions = new JsonSerializerOptions
{
WriteIndented = false,
NumberHandling = JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.AllowNamedFloatingPointLiterals,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Converters = { new DataDictionaryConverter() }
};
}
private readonly Kernel _kernel;
public VariableRouter(Kernel kernel)
{
_kernel = kernel ?? throw new ArgumentNullException(nameof(kernel));
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return null;
}
public async Task RouteAsync(RouteContext context)
{
if (context.HttpContext.Request.Method == HttpMethods.Get)
{
await SingleVariableRequest(context);
}
else if (context.HttpContext.Request.Method == HttpMethods.Post)
{
await BatchVariableRequest(context);
}
}
private async Task BatchVariableRequest(RouteContext context)
{
var segments =
context.HttpContext
.Request
.Path
.Value
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 1 && segments[0] == "variables")
{
using var reader = new StreamReader(context.HttpContext.Request.Body);
var source = await reader.ReadToEndAsync();
var query = JsonDocument.Parse(source).RootElement;
var response = new Dictionary<string,object>();
foreach (var kernelProperty in query.EnumerateObject())
{
var kernelName = kernelProperty.Name;
var propertyBag = new Dictionary<string,object>();
response[kernelName] = propertyBag;
var targetKernel = GetKernel(kernelName);
if (targetKernel is null)
{
context.Handler = async httpContext =>
{
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsync($"kernel {kernelName} not found");
await httpContext.Response.CompleteAsync();
};
return;
}
if (targetKernel.KernelInfo.SupportedKernelCommands.Any(c =>c.Name == nameof(RequestValue)))
{
foreach (var variableName in kernelProperty.Value.EnumerateArray().Select(v => v.GetString()))
{
var value = await GetValueAsync(targetKernel, variableName);
if (value is {})
{
propertyBag[variableName] = JsonDocument.Parse(value.Value).RootElement;
}
else
{
context.Handler = async httpContext =>
{
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsync($"variable {variableName} not found on kernel {kernelName}");
await httpContext.Response.CompleteAsync();
};
return;
}
}
}
else
{
context.Handler = async httpContext =>
{
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsync($"kernel {kernelName} doesn't support RequestValue");
await httpContext.Response.CompleteAsync();
};
return;
}
}
context.Handler = async httpContext =>
{
httpContext.Response.ContentType = JsonFormatter.MimeType;
await using (var writer = new StreamWriter(httpContext.Response.Body))
{
await writer.WriteAsync(JsonSerializer.Serialize( response, SerializerOptions));
}
await httpContext.Response.CompleteAsync();
};
}
}
private static async Task<FormattedValue> GetValueAsync(Kernel targetKernel, string variableName)
{
var result = await targetKernel.SendAsync(new RequestValue(variableName));
if (result.Events[0] is ValueProduced { Value: { } value })
{
return new FormattedValue(JsonFormatter.MimeType, value.ToDisplayString(JsonFormatter.MimeType));
}
return null;
}
private async Task SingleVariableRequest(RouteContext context)
{
var segments =
context.HttpContext
.Request
.Path
.Value
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (segments.FirstOrDefault() == "variables")
{
var kernelName = segments[1];
var variableName = segments[2];
var targetKernel = GetKernel(kernelName);
if (targetKernel?.SupportsCommandType(typeof(RequestValue)) == true)
{
var value = await GetValueAsync(targetKernel, variableName);
if (value is { })
{
context.Handler = async httpContext =>
{
await using (var writer = new StreamWriter(httpContext.Response.Body))
{
httpContext.Response.ContentType = JsonFormatter.MimeType;
await writer.WriteAsync(value.Value);
}
await httpContext.Response.CompleteAsync();
};
}
}
}
}
private Kernel GetKernel(string kernelName) => _kernel.FindKernelByName(kernelName);
}