Files
spark/src/client/spark/core/Diagnostics/ShellDiagnosticsServiceServer.cs
T

194 lines
7.3 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using bts.api.core;
using IronPython.Runtime.Types;
using mbts;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace bts.api.diagnostic {
class ShellDiagnosticsServiceServer : ShellDiagnosticServiceBase {
readonly ServiceContext _context;
readonly List<ShellScriptServer> _hosts = new List<ShellScriptServer>();
public ShellDiagnosticsServiceServer(CompositionContainer container, ServiceContext context) : base(context, Environment.MachineName) {
Console.WriteLine($"Started {Environment.MachineName}");
_context = context;
this.container = container;
}
public override async Task<ShellScriptHostHandle> create(VoidMessage request) {
var uuid = Guid.NewGuid().ToString();
_hosts.Add(new ShellScriptServer(_context, this, uuid));
await Task.Yield();
return new ShellScriptHostHandle {
Id = uuid
};
}
public CompositionContainer container { get; }
internal async void terminate(ShellScriptServer target) {
_hosts.Remove(target);
await Task.Delay(TimeSpan.FromSeconds(1));
Disposable.dispose(ref target);
}
}
class ShellScriptServer : ShellScriptHostBase {
readonly ShellDiagnosticsServiceServer _parent;
readonly ScriptEngine _engine = IronPython.Hosting.Python.CreateEngine();
int _log_line = 1;
readonly ScriptScope _scope;
readonly StringBuilder _pending = new StringBuilder();
readonly OutputPublisher _out;
readonly Thread _thread;
Dispatcher _dispatcher;
public ShellScriptServer(ServiceContext context, ShellDiagnosticsServiceServer parent, string qualifier) : base(context, qualifier) {
_parent = parent;
_out = make_output_publisher();
_scope = _engine.CreateScope();
_scope.SetVariable("id", qualifier);
_scope.SetVariable("log", new Action<dynamic>(log));
_scope.SetVariable("shell_object", new Func<object,object>(o => get_export(o,null)));
_scope.SetVariable("shell_objects", new Func<object,object>(o => get_exports(o,null)));
_scope.SetVariable("shell_named_object", new Func<object,string,object>(get_export));
_scope.SetVariable("shell_named_objects", new Func<object,string,object>(get_exports));
_thread = new Thread(_ => {
_dispatcher = Dispatcher.CurrentDispatcher;
Thread.CurrentThread.Name = $"ShellScriptServer-{qualifier}";
Dispatcher.Run();
});
}
public override Task<VoidMessage> dispose(VoidMessage request) {
log("Finished", true);
_parent.terminate(this);
_dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
return Task.FromResult(new VoidMessage());
}
dynamic get_export(object arg, string qualifier) {
Type t = TypeFromObj(arg);
if (t != null) {
(var type_args, var val_args) = args_from_qualifier(qualifier);
MethodInfo method = typeof(CompositionContainer).GetMethod("GetExportedValueOrDefault", type_args);
MethodInfo generic = method.MakeGenericMethod(t);
return generic.Invoke(_parent.container, val_args);
}
return null;
}
// pass in a singular type and get back a list
dynamic get_exports(object arg, string qualifier) {
Type t = TypeFromObj(arg);
if (t != null) {
_parent.container.GetExportedValues<int>();
(var type_args, var val_args) = args_from_qualifier(qualifier);
MethodInfo method = typeof(CompositionContainer).GetMethod("GetExportedValues", type_args);
MethodInfo generic = method.MakeGenericMethod(t);
return generic.Invoke(_parent.container, val_args);
}
return null;
}
private static Type TypeFromObj(object arg) {
Type t = arg as Type;
if (t == null && arg is string s) {
t = Type.GetType(s);
}
if (t == null && arg is PythonType pt) {
t = pt.__clrtype__();
}
return t;
}
private static (Type[], object[]) args_from_qualifier(string qualifier) {
if (string.IsNullOrEmpty(qualifier)) {
return (new Type[0], new object[0]);
}
return (new Type[] { typeof(string) }, new object[] { qualifier });
}
internal void log(object msg) {
log(msg?.ToString(), false);
}
internal void log(string msg, bool isEnd) {
Console.WriteLine(msg);
_out.append(new ScriptLines {
Id = Interlocked.Increment(ref _log_line),
Lines = { msg ?? "null" },
End = isEnd
});
}
ScriptResultMessage run_code(ScriptSource code) {
try {
object result = code.Execute(_scope);
return new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" };
}
catch (Exception e) {
//log($"Exception: {e.Message}");
return (new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message });
}
}
public override Task<ScriptResultMessage> run(ScriptLines request) {
var tcs = new TaskCompletionSource<ScriptResultMessage>();
void ret(ScriptResultMessage r) {
tcs.TrySetResult(r);
}
_dispatcher.BeginInvoke(() => {
// append lines to _pending
foreach (var line in request.Lines) {
_pending.AppendLine(line);
}
// CreateScriptSource from pending
var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode);
var parse_result = code.GetCodeProperties();
if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) {
parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete;
}
// todo: If code is 'incomplete' but we have 2 blank lines run it!
switch (parse_result) {
// If 'complete' run code
case ScriptCodeParseResult.Complete:
_pending.Clear();
ret(run_code(code));
break;
// if 'invalid' return error
case ScriptCodeParseResult.Invalid:
Console.WriteLine("Invalid");
_pending.Clear();
ret(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() });
break;
// otherwise continue buffering
default:
Console.WriteLine("Incomplete");
ret(new ScriptResultMessage { Res = ScriptResult.Incomplete });
break;
}
});
return tcs.Task;
}
}
}