refactor: Replace stream arg tuples with dedicated type
This commit is contained in:
1 parent
c9b4b523bb
commit
bb7f16089f
47 files changed
+648
-212
No files matched your search
@@ -22,7 +22,7 @@ public class ApplyStream : ViewStream {
|
||||
apply = Apply;
|
||||
|
||||
object? Apply(IBlueRow r) {
|
||||
var res = applyEvaluator.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
||||
var res = applyEvaluator.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) });
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ public class CummulativeSumTable : IBlueRowCollection {
|
||||
}
|
||||
|
||||
public class CummulativeSumTableEvaluator : IFunctionEvaluator {
|
||||
public object? Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public object? Evaluate(string functionId, IEnumerable<StreamArgument> args) {
|
||||
if (args.TryGetFirst(out var a)) {
|
||||
var table = a.Value as IBlueRowCollection;
|
||||
if (table is not null) {
|
||||
|
||||
@@ -116,7 +116,7 @@ public class GroupByApplyStream : ViewStream {
|
||||
Log.assert(group.table.state.Count > 0);
|
||||
var hash = hashIndex.GetOrAdd(group.group_key, _ => hashCounter++);
|
||||
var groupRowCollection = new TableUpdateGroupingRowCollection<TGroupKey>(group, group.table.state.Values.First().schema);
|
||||
var applyArgs = new (string?, int?, object?)[] { ("rows", 0, groupRowCollection) };
|
||||
var applyArgs = new StreamArgument[] { ("rows", 0, groupRowCollection) };
|
||||
var res = apply.Evaluate(string.Empty, applyArgs);
|
||||
if (res is IBlueRow resSingleRow) {
|
||||
UpdateGroupTable(group.group_key, new SingleRowTable(resSingleRow));
|
||||
@@ -156,7 +156,7 @@ public class GroupByApplyStream : ViewStream {
|
||||
return inputStream.AsObservable().AsTables().GroupTable(r => r.Id(), GroupKey).Subscribe(observer);
|
||||
|
||||
EquatableKeyWrapper GroupKey(IBlueRow r) {
|
||||
var groupByArgs = new (string?, int?, object?)[] { ("row", 0, r) };
|
||||
var groupByArgs = new StreamArgument[] { ("row", 0, r) };
|
||||
var groupKey = new EquatableKeyWrapper(groupBy.Evaluate(string.Empty, groupByArgs) ?? DBNull.Value);
|
||||
return groupKey;
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ public static class DataStreamExtensions {
|
||||
return ColumnInjectionTable.Create(source, new IInjectedColumn[] { newColumn });
|
||||
|
||||
object? GetValue(IBlueRow row) =>
|
||||
eval.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, row) });
|
||||
eval.Evaluate(string.Empty, new StreamArgument[] { (null, 0, row) });
|
||||
}
|
||||
|
||||
public static ViewStream Filter(this ViewStream viewStream, string filterExpression) =>
|
||||
|
||||
@@ -13,6 +13,6 @@ class FilterEvaluator : IStreamFilter {
|
||||
this.evaluator = evaluator;
|
||||
|
||||
public bool filter(IBlueRow dr) =>
|
||||
evaluator.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, dr) })
|
||||
evaluator.Evaluate(string.Empty, new StreamArgument[] { (null, 0, dr) })
|
||||
as bool? ?? throw new InvalidOperationException("FunctionEvaluator did not return bool");
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public class RemoteQueryStreamFactory : IDataStreamFactory {
|
||||
public RemoteQueryStreamFactory(TableStreamFactory tableStreamFactory) =>
|
||||
this.tableStreamFactory = tableStreamFactory;
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) {
|
||||
if (SupportedStreams.RemoteQuery.IsMatch(streamId)) {
|
||||
return createTable(args);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public class RemoteQueryStreamFactory : IDataStreamFactory {
|
||||
yield return SupportedStreams.RemoteQuery;
|
||||
}
|
||||
|
||||
ViewStream? createTable(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? createTable(IEnumerable<StreamArgument> args) {
|
||||
var lines = args.Select(a => a.Value as string ?? a.Value?.ToString() ?? string.Empty).ToArray();
|
||||
return new RemoteQueryStream(tableStreamFactory, lines);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ class CompositeDataStreamFactory : IDataStreamFactory, IHostedService {
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
streamFactories.SelectMany(f => f.GetSupportedStreams());
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) =>
|
||||
streamFactories.Where(f => f.CanCreate(streamId))
|
||||
.Select(f => f.Create(streamId, args))
|
||||
.ExceptNull()
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ public class CompositeExtensionFunctionEvaluator : IExtensionFunctionEvaluator {
|
||||
evaluators.Add(evaluator);
|
||||
}
|
||||
|
||||
public object? Evaluate(string functionId, object target, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public object? Evaluate(string functionId, object target, IEnumerable<StreamArgument> args) {
|
||||
var targetType = target.GetType();
|
||||
foreach (var eval in evaluators) {
|
||||
if (eval.SupportedFunctions.Contains(functionId) && targetType.IsAssignableTo(eval.TargetType)) {
|
||||
|
||||
@@ -18,7 +18,7 @@ public class DataStreamFactory : IDataStreamFactory {
|
||||
return dsf.factories.Count == 1 ? dsf.factories[0] : dsf;
|
||||
}
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) =>
|
||||
factories.Where(sf => sf.GetSupportedStreams().Any(m => m.IsMatch(streamId)))
|
||||
.Select(sf => sf.Create(streamId, args))
|
||||
.ExceptNull()
|
||||
@@ -29,17 +29,24 @@ public class DataStreamFactory : IDataStreamFactory {
|
||||
|
||||
public void Add(IDataStreamFactory streamFactory) =>
|
||||
factories.Add(streamFactory);
|
||||
|
||||
class EmptyDataStreamFactory : IDataStreamFactory {
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
null;
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
Enumerable.Empty<IDataStreamMetadata>();
|
||||
}
|
||||
}
|
||||
|
||||
public static class DataStreamFactoryExtensions {
|
||||
public static void Add(this DataStreamFactory streamFactory, IDataStreamMetadata metadata, Func<ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = SingleDataStreamFactory.FromDelegate(metadata, singleStreamfactory);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add(this DataStreamFactory streamFactory, IDataStreamMetadata metadata, Func<IEnumerable<StreamArgument>, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = new SingleDataStreamFactory(metadata, singleStreamfactory);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add(this DataStreamFactory streamFactory, string name, Func<IEnumerable<StreamArgument>, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = new SingleDataStreamFactory(new DataStreamMetadata() { Name = name }, singleStreamfactory);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add<TParams>(this DataStreamFactory streamFactory, IDataStreamMetadata metadata, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = new SingleDataStreamFactory<TParams>(metadata, singleStreamfactory, logger);
|
||||
streamFactory.Add(sf);
|
||||
@@ -50,11 +57,6 @@ public static class DataStreamFactoryExtensions {
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add(this DataStreamFactory streamFactory, string name, Func<IEnumerable<(string?, int?, object?)>, ViewStream?> singleStreamfactory) {
|
||||
var sf = new SingleDataStreamFactory(new DataStreamMetadata() { Name = name }, singleStreamfactory);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add<TParams>(this DataStreamFactory streamFactory, string[] names, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
if (names.Length == 0) {
|
||||
throw new ArgumentException("StreamFactory must have at least one name", nameof(names));
|
||||
@@ -64,15 +66,18 @@ public static class DataStreamFactoryExtensions {
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add<TParams>(this DataStreamFactory streamFactory, string[] names, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null, StreamFactoryArgStore.TryGetParamsDelegate<TParams>? tryGetParams = null) {
|
||||
public static void Add<TParams>(this DataStreamFactory streamFactory, string[] names, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null, StreamArgumentsParser.TryParse<TParams>? tryParse = null) {
|
||||
if (names.Length == 0) {
|
||||
throw new ArgumentException("StreamFactory must have at least one name", nameof(names));
|
||||
}
|
||||
var meta = new DataStreamMetadata() { Name = names[0], AlternateNames = names.Skip(1).ToList() };
|
||||
var sf = new SingleDataStreamFactory<TParams>(meta, singleStreamfactory, logger, tryGetParams);
|
||||
var parser = tryParse is null
|
||||
? new StreamArgumentsParser<TParams>()
|
||||
: StreamArgumentsParser.FromDelegate(tryParse);
|
||||
var sf = new SingleDataStreamFactory<TParams>(meta, singleStreamfactory, parser, logger);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static ViewStream? Create(this IDataStreamFactory streamFactory, string streamId, params object?[] args) =>
|
||||
streamFactory.Create(streamId, args.Select((a, i) => ((string?)null, (int?)i, a)));
|
||||
streamFactory.Create(streamId, args.Select((a, i) => new StreamArgument(null, i, a)));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System;
|
||||
|
||||
public class DateTimeArgumentParser : IStreamArgumentParser {
|
||||
public bool CanParse(StreamArgument arg, Type outputType) =>
|
||||
outputType == typeof(DateTime) || outputType == typeof(DateTime?);
|
||||
|
||||
public bool TryParse(StreamArgument arg, Type outputType, out object result, out string error) {
|
||||
result = null;
|
||||
error = null;
|
||||
var val = arg.Value;
|
||||
switch (val) {
|
||||
case DateTime dt:
|
||||
result = dt;
|
||||
return true;
|
||||
case string str: {
|
||||
if (DateTime.TryParse(str, out var dt)) {
|
||||
result = dt;
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
if (outputType == typeof(DateTime?)) {
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
error = "Failed to parse DateTime arg";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,12 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
readonly Dictionary<string, List<((string? Name, Type? Type)[] Signature, Func<T, List<(string?, int?, object?)>, object?> Evaluate)>> evaluators = new();
|
||||
readonly Dictionary<string, List<((string? Name, Type? Type)[] Signature, Func<T, List<StreamArgument>, object?> Evaluate)>> evaluators = new();
|
||||
|
||||
public IEnumerable<string> SupportedFunctions =>
|
||||
evaluators.Keys;
|
||||
|
||||
public object? Evaluate(string functionId, T target, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public object? Evaluate(string functionId, T target, IEnumerable<StreamArgument> args) {
|
||||
if (!evaluators.TryGetValue(functionId, out var fnEvals)) {
|
||||
throw new ArgumentException($"Failed to find evaluator for function '{functionId}'", nameof(functionId));
|
||||
}
|
||||
@@ -58,7 +58,7 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
var sig = Array.Empty<(string?, Type?)>();
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> args) =>
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> args) =>
|
||||
evaluate(target);
|
||||
}
|
||||
|
||||
@@ -66,11 +66,11 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
var sig = new (string?, Type?)[] { (null, typeof(T1)) };
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 1) {
|
||||
throw new ArgumentException($"Expected exactly 1 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1);
|
||||
@@ -81,14 +81,14 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
var sig = new (string?, Type?)[] { (null, typeof(T1)), (null, typeof(T2)) };
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 2) {
|
||||
throw new ArgumentException($"Expected exactly 2 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2);
|
||||
@@ -99,17 +99,17 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
var sig = new (string?, Type?)[] { (null, typeof(T1)), (null, typeof(T2)), (null, typeof(T3)) };
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 3) {
|
||||
throw new ArgumentException($"Expected exactly 3 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3);
|
||||
@@ -125,20 +125,20 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
};
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 4) {
|
||||
throw new ArgumentException($"Expected exactly 4 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[3].Item3, out T4 arg4)) {
|
||||
if (!ConvertUtils.try_convert(argList[3].Value, out T4 arg4)) {
|
||||
throw new ArgumentException($"Failed to convert fourth arg to type '{typeof(T4)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3, arg4);
|
||||
@@ -155,23 +155,23 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
};
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 5) {
|
||||
throw new ArgumentException($"Expected exactly 5 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[3].Item3, out T4 arg4)) {
|
||||
if (!ConvertUtils.try_convert(argList[3].Value, out T4 arg4)) {
|
||||
throw new ArgumentException($"Failed to convert fourth arg to type '{typeof(T4)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[4].Item3, out T5 arg5)) {
|
||||
if (!ConvertUtils.try_convert(argList[4].Value, out T5 arg5)) {
|
||||
throw new ArgumentException($"Failed to convert fifth arg to type '{typeof(T5)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3, arg4, arg5);
|
||||
@@ -189,26 +189,26 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
};
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 6) {
|
||||
throw new ArgumentException($"Expected exactly 6 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[3].Item3, out T4 arg4)) {
|
||||
if (!ConvertUtils.try_convert(argList[3].Value, out T4 arg4)) {
|
||||
throw new ArgumentException($"Failed to convert fourth arg to type '{typeof(T4)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[4].Item3, out T5 arg5)) {
|
||||
if (!ConvertUtils.try_convert(argList[4].Value, out T5 arg5)) {
|
||||
throw new ArgumentException($"Failed to convert fifth arg to type '{typeof(T5)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[5].Item3, out T6 arg6)) {
|
||||
if (!ConvertUtils.try_convert(argList[5].Value, out T6 arg6)) {
|
||||
throw new ArgumentException($"Failed to convert sixth arg to type '{typeof(T6)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3, arg4, arg5, arg6);
|
||||
@@ -227,29 +227,29 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
};
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 7) {
|
||||
throw new ArgumentException($"Expected exactly 7 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[3].Item3, out T4 arg4)) {
|
||||
if (!ConvertUtils.try_convert(argList[3].Value, out T4 arg4)) {
|
||||
throw new ArgumentException($"Failed to convert fourth arg to type '{typeof(T4)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[4].Item3, out T5 arg5)) {
|
||||
if (!ConvertUtils.try_convert(argList[4].Value, out T5 arg5)) {
|
||||
throw new ArgumentException($"Failed to convert fifth arg to type '{typeof(T5)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[5].Item3, out T6 arg6)) {
|
||||
if (!ConvertUtils.try_convert(argList[5].Value, out T6 arg6)) {
|
||||
throw new ArgumentException($"Failed to convert sixth arg to type '{typeof(T6)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[6].Item3, out T7 arg7)) {
|
||||
if (!ConvertUtils.try_convert(argList[6].Value, out T7 arg7)) {
|
||||
throw new ArgumentException($"Failed to convert seventh arg to type '{typeof(T7)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
|
||||
@@ -260,32 +260,32 @@ public class ExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator<T> {
|
||||
var sig = new (string?, Type?)[] { (null, typeof(T1)), (null, typeof(T2)), (null, typeof(T3)) };
|
||||
evaluators.GetOrAdd(functionId, _ => new(1)).Add((sig, EvaluateWrapper));
|
||||
|
||||
object? EvaluateWrapper(T target, List<(string?, int?, object?)> argList) {
|
||||
object? EvaluateWrapper(T target, List<StreamArgument> argList) {
|
||||
if (argList.Count != 8) {
|
||||
throw new ArgumentException($"Expected exactly 8 args (got {argList.Count})", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[0].Item3, out T1 arg1)) {
|
||||
if (!ConvertUtils.try_convert(argList[0].Value, out T1 arg1)) {
|
||||
throw new ArgumentException($"Failed to convert first arg to type '{typeof(T1)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[1].Item3, out T2 arg2)) {
|
||||
if (!ConvertUtils.try_convert(argList[1].Value, out T2 arg2)) {
|
||||
throw new ArgumentException($"Failed to convert second arg to type '{typeof(T2)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[2].Item3, out T3 arg3)) {
|
||||
if (!ConvertUtils.try_convert(argList[2].Value, out T3 arg3)) {
|
||||
throw new ArgumentException($"Failed to convert third arg to type '{typeof(T3)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[3].Item3, out T4 arg4)) {
|
||||
if (!ConvertUtils.try_convert(argList[3].Value, out T4 arg4)) {
|
||||
throw new ArgumentException($"Failed to convert fourth arg to type '{typeof(T4)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[4].Item3, out T5 arg5)) {
|
||||
if (!ConvertUtils.try_convert(argList[4].Value, out T5 arg5)) {
|
||||
throw new ArgumentException($"Failed to convert fifth arg to type '{typeof(T5)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[5].Item3, out T6 arg6)) {
|
||||
if (!ConvertUtils.try_convert(argList[5].Value, out T6 arg6)) {
|
||||
throw new ArgumentException($"Failed to convert sixth arg to type '{typeof(T6)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[6].Item3, out T7 arg7)) {
|
||||
if (!ConvertUtils.try_convert(argList[6].Value, out T7 arg7)) {
|
||||
throw new ArgumentException($"Failed to convert seventh arg to type '{typeof(T7)}'", nameof(argList));
|
||||
}
|
||||
if (!ConvertUtils.try_convert(argList[7].Item3, out T8 arg8)) {
|
||||
if (!ConvertUtils.try_convert(argList[7].Value, out T8 arg8)) {
|
||||
throw new ArgumentException($"Failed to convert eighth arg to type '{typeof(T8)}'", nameof(argList));
|
||||
}
|
||||
return evaluate(target, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
|
||||
|
||||
@@ -14,7 +14,7 @@ public static class FunctionEvaluator {
|
||||
this.evaluate = evaluate;
|
||||
}
|
||||
|
||||
public object Evaluate(string functionId, IEnumerable<(string Name, int? Index, object Value)> args) {
|
||||
public object Evaluate(string functionId, IEnumerable<StreamArgument> args) {
|
||||
foreach (var a in args) {
|
||||
if (a is T ta) {
|
||||
return evaluate(ta);
|
||||
|
||||
@@ -9,12 +9,12 @@ using System.Linq;
|
||||
public interface IDataStreamFactory : IFunctionEvaluator {
|
||||
IEnumerable<IDataStreamMetadata> GetSupportedStreams();
|
||||
|
||||
ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
ViewStream? Create(string streamId, IEnumerable<StreamArgument> args);
|
||||
|
||||
bool CanCreate(string streamId) =>
|
||||
GetSupportedStreams().Any(s => s.IsMatch(streamId));
|
||||
|
||||
object? IFunctionEvaluator.Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
object? IFunctionEvaluator.Evaluate(string functionId, IEnumerable<StreamArgument> args) =>
|
||||
Create(functionId, args);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ using System.Collections.Generic;
|
||||
|
||||
public interface IFunctionEvaluator {
|
||||
bool CanCompile => false;
|
||||
object? Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
object? Evaluate(string functionId, IEnumerable<StreamArgument> args);
|
||||
void Compile() =>
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
@@ -18,9 +18,9 @@ public interface IExtensionFunctionEvaluator : IFunctionEvaluator {
|
||||
|
||||
public IEnumerable<string> SupportedFunctions { get; }
|
||||
|
||||
object? Evaluate(string functionId, object target, IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
object? Evaluate(string functionId, object target, IEnumerable<StreamArgument> args);
|
||||
|
||||
object? IFunctionEvaluator.Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
object? IFunctionEvaluator.Evaluate(string functionId, IEnumerable<StreamArgument> args) {
|
||||
var en = args.GetEnumerator();
|
||||
if (!en.MoveNext()) {
|
||||
throw new ArgumentException("Expected at least 1 arg (first arg is the target obj)", nameof(args));
|
||||
@@ -31,7 +31,7 @@ public interface IExtensionFunctionEvaluator : IFunctionEvaluator {
|
||||
}
|
||||
return Evaluate(functionId, targetObj, RemainingArgs());
|
||||
|
||||
IEnumerable<(string? Name, int? Index, object? Value)> RemainingArgs() {
|
||||
IEnumerable<StreamArgument> RemainingArgs() {
|
||||
while (en.MoveNext()) {
|
||||
yield return en.Current;
|
||||
}
|
||||
@@ -42,8 +42,8 @@ public interface IExtensionFunctionEvaluator : IFunctionEvaluator {
|
||||
public interface IExtensionFunctionEvaluator<T> : IExtensionFunctionEvaluator {
|
||||
Type IExtensionFunctionEvaluator.TargetType => typeof(T);
|
||||
|
||||
object? Evaluate(string functionId, T target, IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
object? Evaluate(string functionId, T target, IEnumerable<StreamArgument> args);
|
||||
|
||||
object? IExtensionFunctionEvaluator.Evaluate(string functionId, object target, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
object? IExtensionFunctionEvaluator.Evaluate(string functionId, object target, IEnumerable<StreamArgument> args) =>
|
||||
Evaluate(functionId, ExceptionAssert.Argument.Is<T>(target), args);
|
||||
}
|
||||
@@ -8,9 +8,9 @@ using System.Collections.Generic;
|
||||
public interface ISingleStreamFactory : IDataStreamFactory {
|
||||
IDataStreamMetadata Metadata { get; }
|
||||
|
||||
ViewStream? Create(IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
ViewStream? Create(IEnumerable<StreamArgument> args);
|
||||
|
||||
ViewStream? IDataStreamFactory.Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
ViewStream? IDataStreamFactory.Create(string streamId, IEnumerable<StreamArgument> args) =>
|
||||
Metadata.IsMatch(streamId) ? Create(args) : null;
|
||||
|
||||
IEnumerable<IDataStreamMetadata> IDataStreamFactory.GetSupportedStreams() =>
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
public interface IStreamArgumentParser {
|
||||
bool TryParse(string? name, string? valueStr, out object? result);
|
||||
bool CanParse(StreamArgument arg, Type outputType);
|
||||
|
||||
bool TryParse(StreamArgument arg, Type outputType, out object? result, out string? error);
|
||||
}
|
||||
|
||||
public interface IStreamArgumentParser<T> : IStreamArgumentParser {
|
||||
bool IStreamArgumentParser.CanParse(StreamArgument arg, Type outputType) =>
|
||||
outputType == typeof(T) || outputType.IsAssignableFrom(typeof(T));
|
||||
|
||||
bool TryParse(StreamArgument arg, [MaybeNullWhen(false)]out T? result, out string? error);
|
||||
|
||||
bool IStreamArgumentParser.TryParse(StreamArgument arg, Type outputType, out object? result, out string? error) {
|
||||
if (outputType != typeof(T) || !outputType.IsAssignableFrom(typeof(T))) {
|
||||
result = null;
|
||||
error = $"OutputType '{outputType}' is assignable from type '{typeof(T)}'";
|
||||
return false;
|
||||
}
|
||||
bool rv = TryParse(arg, out T? resultT, out error);
|
||||
result = resultT;
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
public interface IStreamArgumentsParser {
|
||||
bool TryParse(IReadOnlyList<StreamArgument> args, [NotNullWhen(true)]out object? result, out string? error);
|
||||
}
|
||||
|
||||
public interface IStreamArgumentsParser<T> : IStreamArgumentsParser {
|
||||
bool TryParse(IReadOnlyList<StreamArgument> args, [NotNullWhen(true)]out T? result, out string? error);
|
||||
|
||||
bool IStreamArgumentsParser.TryParse(IReadOnlyList<StreamArgument> args, [NotNullWhen(true)]out object? result, out string? error) {
|
||||
bool rv = TryParse(args, out T? resultT, out error);
|
||||
result = resultT;
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class IdentityFunctionEvaluator : IFunctionEvaluator {
|
||||
public object? Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public object? Evaluate(string functionId, IEnumerable<StreamArgument> args) {
|
||||
var argList = args.Select(a => a.Value).ToList();
|
||||
return argList.Count switch {
|
||||
0 => null,
|
||||
|
||||
@@ -110,7 +110,7 @@ public class PrimitiveManager : IDataStreamFactory {
|
||||
return result is not null;
|
||||
}
|
||||
|
||||
public ViewStream Create(string streamId, IEnumerable<(string Name, int? Index, object Value)> args) =>
|
||||
public ViewStream Create(string streamId, IEnumerable<StreamArgument> args) =>
|
||||
TryResolveType(streamId, out var type) ? Create(type, args) : null;
|
||||
|
||||
/// <summary>
|
||||
@@ -120,7 +120,7 @@ public class PrimitiveManager : IDataStreamFactory {
|
||||
/// <param name="args">args can be null or an empty ICollection if the paramterless constructor
|
||||
/// is the desired one</param>
|
||||
/// <returns></returns>
|
||||
public ViewStream Create(Type type, IEnumerable<(string Name, int? Index, object Value)> args) {
|
||||
public ViewStream Create(Type type, IEnumerable<StreamArgument> args) {
|
||||
var ctrs = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
|
||||
var argList = args.ToList();
|
||||
const int MAX_ALLOWED_ARGS = 64;
|
||||
@@ -153,9 +153,9 @@ public class PrimitiveManager : IDataStreamFactory {
|
||||
static bool TryAssignConstructorArgs(
|
||||
ConstructorInfo ctr,
|
||||
int minArgCount,
|
||||
List<(string Name, int? Index, object Value)> argList,
|
||||
List<(string Name, int? Index, object Value)> indexedArgs,
|
||||
List<(string Name, int? Index, object Value)> namedArgs,
|
||||
List<StreamArgument> argList,
|
||||
List<StreamArgument> indexedArgs,
|
||||
List<StreamArgument> namedArgs,
|
||||
[NotNullWhen(true)] out object[] ctrArgs
|
||||
) {
|
||||
ctrArgs = null;
|
||||
|
||||
@@ -9,16 +9,23 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
class SingleDataStreamFactory : ISingleStreamFactory {
|
||||
readonly Func<IEnumerable<(string?, int?, object?)>, ViewStream?> factory;
|
||||
readonly Func<IEnumerable<StreamArgument>, ViewStream?> factory;
|
||||
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<IEnumerable<(string?, int?, object?)>, ViewStream?> factory) {
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<IEnumerable<StreamArgument>, ViewStream?> factory) {
|
||||
Metadata = metadata;
|
||||
this.factory = factory;
|
||||
}
|
||||
|
||||
public IDataStreamMetadata Metadata { get; }
|
||||
|
||||
public ViewStream? Create(IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
public static SingleDataStreamFactory FromDelegate(IDataStreamMetadata metadata, Func<ViewStream?> factory) {
|
||||
return new SingleDataStreamFactory(metadata, FactoryWrapper);
|
||||
|
||||
ViewStream? FactoryWrapper(IEnumerable<StreamArgument> _) =>
|
||||
factory();
|
||||
}
|
||||
|
||||
public ViewStream? Create(IEnumerable<StreamArgument> args) =>
|
||||
factory(args);
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
@@ -27,23 +34,27 @@ class SingleDataStreamFactory : ISingleStreamFactory {
|
||||
|
||||
class SingleDataStreamFactory<TParams> : ISingleStreamFactory {
|
||||
readonly Func<TParams, ViewStream?> factory;
|
||||
readonly IStreamArgumentsParser<TParams> parser;
|
||||
readonly ILogger? logger;
|
||||
readonly StreamFactoryArgStore.TryGetParamsDelegate<TParams> tryGetParams;
|
||||
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<TParams, ViewStream?> factory)
|
||||
: this(metadata, factory, null) { }
|
||||
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<TParams, ViewStream?> factory, ILogger? logger, StreamFactoryArgStore.TryGetParamsDelegate<TParams>? tryGetParams = null) {
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<TParams, ViewStream?> factory, ILogger? logger)
|
||||
: this(metadata, factory, new StreamArgumentsParser<TParams>(), logger) { }
|
||||
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<TParams, ViewStream?> factory, IStreamArgumentsParser<TParams> parser, ILogger? logger) {
|
||||
Metadata = metadata;
|
||||
this.factory = factory;
|
||||
this.parser = parser;
|
||||
this.logger = logger;
|
||||
this.tryGetParams = tryGetParams ?? new(StreamFactoryArgStore.TryGetParams);
|
||||
}
|
||||
|
||||
public IDataStreamMetadata Metadata { get; }
|
||||
|
||||
public ViewStream? Create(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
if (!tryGetParams(args, out TParams? streamParams, out var err)) {
|
||||
public ViewStream? Create(IEnumerable<StreamArgument> args) {
|
||||
var argList = args as IReadOnlyList<StreamArgument> ?? args.ToReadOnlyList();
|
||||
if (!parser.TryParse(argList, out TParams? streamParams, out var err)) {
|
||||
logger?.LogInvalidParams(Metadata.Name, err);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
public record StreamArgument(string? Name, int? Index, object? Value) {
|
||||
public static implicit operator (string? Name, int? Index, object? Value)(StreamArgument arg) =>
|
||||
(arg.Name, arg.Index, arg.Value);
|
||||
|
||||
public static implicit operator StreamArgument((string? Name, int? Index, object? Value) arg) =>
|
||||
(arg.Name, arg.Index, arg.Value);
|
||||
|
||||
public static StreamArgument Empty => new(null, null, null);
|
||||
|
||||
public void Deconstruct(out string? name, out int? index, out object? value) {
|
||||
name = Name;
|
||||
index = Index;
|
||||
value = Value;
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,11 @@ namespace Bts.DataStreamCore;
|
||||
|
||||
using System;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
|
||||
public class StreamArgumentAttribute : Attribute {
|
||||
object? defaultValue;
|
||||
bool hasDefaultValue;
|
||||
|
||||
public StreamArgumentAttribute(params string[] names) {
|
||||
Names = names;
|
||||
RegexNames = Array.Empty<string>();
|
||||
@@ -16,4 +19,12 @@ public class StreamArgumentAttribute : Attribute {
|
||||
public bool IsRequired { get; set; }
|
||||
public bool AllowCommaSeparatedAliases { get; set; } = true;
|
||||
public Type? ParserType { get; set; }
|
||||
public object? DefaultValue {
|
||||
get => defaultValue;
|
||||
set {
|
||||
defaultValue = value;
|
||||
hasDefaultValue = true;
|
||||
}
|
||||
}
|
||||
public bool HasDefaultValue => hasDefaultValue;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Constructor)]
|
||||
public class StreamArgumentConstructorAttribute : Attribute {
|
||||
public StreamArgumentConstructorAttribute()
|
||||
: this(true) { }
|
||||
|
||||
public StreamArgumentConstructorAttribute(bool isVisible) {
|
||||
IsVisible = isVisible;
|
||||
}
|
||||
|
||||
public bool IsVisible { get; }
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using bts;
|
||||
using bts.collections;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
public static class StreamArgumentsParser {
|
||||
public delegate bool TryParse<T>(IEnumerable<StreamArgument> args, [NotNullWhen(true)] out T? result, [NotNullWhen(false)] out string? errorMessage);
|
||||
|
||||
public static IStreamArgumentsParser<T> FromValue<T>(T value) where T : notnull {
|
||||
return FromDelegate<T>(TryParse);
|
||||
|
||||
bool TryParse(IEnumerable<StreamArgument> args, [NotNullWhen(true)] out T result, [NotNullWhen(false)] out string? errorMessage) {
|
||||
result = value;
|
||||
errorMessage = null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static IStreamArgumentsParser<T> FromDelegate<T>(TryParse<T> tryParse) =>
|
||||
new DelegateImpl<T>(tryParse);
|
||||
|
||||
class DelegateImpl<T> : IStreamArgumentsParser<T> {
|
||||
readonly TryParse<T> tryParse;
|
||||
|
||||
public DelegateImpl(TryParse<T> tryParse) =>
|
||||
this.tryParse = tryParse;
|
||||
|
||||
public bool TryParse(IReadOnlyList<StreamArgument> args, [NotNullWhen(true)] out T? result, out string? error) =>
|
||||
tryParse(args, out result, out error);
|
||||
}
|
||||
}
|
||||
|
||||
public class StreamArgumentsParser<T> : IStreamArgumentsParser<T> {
|
||||
public bool TryParse(IReadOnlyList<StreamArgument> args, [NotNullWhen(true)] out T? result, out string? error) {
|
||||
// indexedArgs has every arg with a non-null index.
|
||||
// namedArgs has every arg with a non-null/empty name (except those with non-null indices).
|
||||
// unnamedArgs have the others.
|
||||
// Use the index as an id to prevent using the same arg twice. All named and
|
||||
// indexed params must bind to a specific param in a constructor (the one with
|
||||
// the matching name and/or index). Unnamed/indexed params are then bound to the
|
||||
// remaining params (in the same order relative to their enumeration).
|
||||
var allArgs = args.ToImmutableList();
|
||||
if (!allArgs.Select(a => a.Name).WhereNot(string.IsNullOrEmpty).IsDistinct()) {
|
||||
throw new ArgumentException("Arg names are not unique");
|
||||
}
|
||||
if (!allArgs.Select(a => a.Index).SelectWhereValues().IsDistinct()) {
|
||||
throw new ArgumentException("Arg indices are not unique", nameof(args));
|
||||
}
|
||||
int nArgs = args.Count;
|
||||
error = null;
|
||||
// Constructor params with default values may be omitted from the input 'args'. Therefore,
|
||||
// 'minArgCount' >= 'argList.Count'.
|
||||
var minArgCount = Math.Max(allArgs.Select(a => a.Index).SelectWhereValues().MaxOrDefault(), nArgs);
|
||||
var streamType = typeof(T);
|
||||
var ctrs = streamType.GetConstructors();
|
||||
foreach (var ctr in ctrs) {
|
||||
var ctrAtt = ctr.GetCustomAttribute<StreamArgumentConstructorAttribute>();
|
||||
if (ctrAtt is not null && !ctrAtt.IsVisible) {
|
||||
continue;
|
||||
}
|
||||
var ps = ctr.GetParameters();
|
||||
if (ps.Length < minArgCount) {
|
||||
continue;
|
||||
}
|
||||
if (TryAssignConstructorArgs(ps, allArgs, out var ctrArgs, out var unusedArgs)) {
|
||||
if (unusedArgs.Any(a => string.IsNullOrEmpty(a.Name))) {
|
||||
continue;
|
||||
}
|
||||
var resObj = ctr.Invoke(ctrArgs);
|
||||
result = (T)resObj;
|
||||
var resProps = typeof(T).GetProperties()
|
||||
.Select(p => (Prop: p, Att: p.GetCustomAttribute<StreamArgumentAttribute>()))
|
||||
.Where(p => p.Att is not null)
|
||||
.Select(p => (p.Prop, Att: p.Att!))
|
||||
.ToImmutableList();
|
||||
foreach (var arg in unusedArgs) {
|
||||
// var argName = arg.Name;
|
||||
// if (string.IsNullOrEmpty(argName)) {
|
||||
// continue;
|
||||
// }
|
||||
var argName = arg.Name!;
|
||||
if (resProps.TryGetFirst(pTup => IsNameMatch(argName, pTup), out var pTup, out var pIndex)) {
|
||||
resProps = resProps.RemoveAt(pIndex);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
bool IsNameMatch(string argName, (PropertyInfo Prop, StreamArgumentAttribute Att) propTup) {
|
||||
var (pi, att) = propTup;
|
||||
if (att is null) {
|
||||
return false;
|
||||
}
|
||||
var names = att.Names;
|
||||
if (names is not null && names.Contains(argName, StringComparer.CurrentCultureIgnoreCase)) {
|
||||
return true;
|
||||
}
|
||||
var rxNames = att.RegexNames;
|
||||
if (rxNames is not null && rxNames.Any(rx => Regex.IsMatch(argName, rx))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
result = default;
|
||||
return false;
|
||||
|
||||
static bool TryAssignConstructorArgs(
|
||||
ParameterInfo[] ctrParams,
|
||||
ImmutableList<StreamArgument> args,
|
||||
[NotNullWhen(true)] out object?[]? ctrArgs,
|
||||
out ImmutableList<StreamArgument> unusedArgs
|
||||
) {
|
||||
ctrArgs = null;
|
||||
var ctrArgList = new List<object?>();
|
||||
int nArgs = args.Count;
|
||||
// Use locUsedArgs var inside lambdas (can't use ref params)
|
||||
var locUsedArgs = new HashSet<int>();
|
||||
for (int i = 0; i < ctrParams.Length; i++) {
|
||||
var ctrParam = ctrParams[i];
|
||||
var paramType = ctrParams[i].ParameterType;
|
||||
var att = ctrParam.GetCustomAttribute<StreamArgumentAttribute>();
|
||||
var parserType = att?.ParserType;
|
||||
var parser = parserType is null
|
||||
? null
|
||||
: Activator.CreateInstance(parserType) as IStreamArgumentParser;
|
||||
// Try to match indexed args first, then named args, then fallback to (all) args.
|
||||
// indexedArgs.TryRemoveFirst()
|
||||
int argIdx = -1;
|
||||
int idx = 0;
|
||||
foreach (var a in args) {
|
||||
if (!CanAssignInputArg(ctrParam, a, parser)) {
|
||||
continue;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(a.Name) || a.Index.HasValue) {
|
||||
// We're done. Names/indices are unambiguous. This arg MUST bind to this param.
|
||||
argIdx = idx;
|
||||
break;
|
||||
}
|
||||
if (argIdx == -1) {
|
||||
// If we don't find a matching named/indexed param, we'll use this one.
|
||||
argIdx = idx;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
if (argIdx != -1) {
|
||||
var arg = args[argIdx];
|
||||
args = args.RemoveAt(argIdx);
|
||||
var val = arg.Value;
|
||||
if (parser is not null) {
|
||||
if (!parser.TryParse(arg, ctrParam.ParameterType, out var parsedVal, out var err)) {
|
||||
throw new InvalidOperationException($"Failed to parse param '{ctrParam.Name}'");
|
||||
}
|
||||
val = parsedVal;
|
||||
}
|
||||
ctrArgList.Add(val);
|
||||
} else if (att is not null && att.HasDefaultValue) {
|
||||
ctrArgList.Add(att.DefaultValue);
|
||||
} else if (ctrParam.HasDefaultValue) {
|
||||
ctrArgList.Add(ctrParam.DefaultValue);
|
||||
} else {
|
||||
unusedArgs = args;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Log.assert(ctrArgList.Count == ctrParams.Length);
|
||||
ctrArgs = ctrArgList.ToArray();
|
||||
unusedArgs = args;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool CanAssignInputArg(ParameterInfo pi, StreamArgument arg, IStreamArgumentParser? parser = null) {
|
||||
if (!string.IsNullOrEmpty(arg.Name) && arg.Name != pi.Name) {
|
||||
return false;
|
||||
}
|
||||
if (arg.Index.HasValue && arg.Index.Value != pi.Position) {
|
||||
return false;
|
||||
}
|
||||
if (parser is not null) {
|
||||
return parser.CanParse(arg, pi.ParameterType);
|
||||
}
|
||||
if (arg.Value is null) {
|
||||
if (!pi.ParameterType.IsValueType && !pi.ParameterType.IsNullable()) {
|
||||
return false;
|
||||
}
|
||||
} else if (!pi.ParameterType.IsAssignableFrom(arg.Value.GetType())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,19 +21,19 @@ using System.Text.RegularExpressions;
|
||||
public class StreamFactoryArgStore {
|
||||
readonly ILogger? logger;
|
||||
readonly string streamType;
|
||||
ImmutableList<(string? Name, int? Index, object? Value)> args;
|
||||
ImmutableList<StreamArgument> args;
|
||||
|
||||
public StreamFactoryArgStore(IEnumerable<(string? Name, int? Index, object? Value)> args, string? streamType = null, ILogger? logger = null) {
|
||||
public StreamFactoryArgStore(IEnumerable<StreamArgument> args, string? streamType = null, ILogger? logger = null) {
|
||||
this.args = args.ToImmutableList();
|
||||
this.streamType = streamType ?? "anonStream";
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public delegate bool TryGetParamsDelegate<T>(IEnumerable<(string? Name, int? Index, object? Value)> args, [NotNullWhen(true)]out T? result, [NotNullWhen(false)] out string? errorMessage);
|
||||
public delegate bool TryConvert<T>(object? obj, [NotNullWhen(true)]out T? result);
|
||||
public delegate bool TryGetParamsDelegate<T>(IEnumerable<(string? Name, int? Index, object? Value)> args, [NotNullWhen(true)] out T? result, [NotNullWhen(false)] out string? errorMessage);
|
||||
public delegate bool TryConvert<T>(object? obj, [NotNullWhen(true)] out T? result);
|
||||
|
||||
public static bool TryGetParams<T>(
|
||||
IEnumerable<(string? Name, int? Index, object? Value)> args,
|
||||
IEnumerable<StreamArgument> args,
|
||||
[NotNullWhen(true)] out T? result,
|
||||
[NotNullWhen(false)] out string? errorMessage
|
||||
) =>
|
||||
@@ -64,11 +64,11 @@ public class StreamFactoryArgStore {
|
||||
return false;
|
||||
}
|
||||
|
||||
void SetValue((string? Name, int? Index, object? Value) arg) {
|
||||
void SetValue(StreamArgument arg) {
|
||||
var (name, index, val) = arg;
|
||||
if (val is string valStr && att?.ParserType is Type parserType) {
|
||||
var parser = ExceptionAssert.of_type<IStreamArgumentParser>(Activator.CreateInstance(parserType));
|
||||
if (!parser.TryParse(name, valStr, out val)) {
|
||||
if (!parser.TryParse(arg, p.PropertyType, out val, out var err)) {
|
||||
throw new InvalidOperationException($"Failed to parse arg with custom parser of type {parserType}");
|
||||
}
|
||||
}
|
||||
@@ -230,16 +230,16 @@ public class StreamFactoryArgStore {
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
public bool TryGetRegex(string name, out (string? Name, int? Index, object? Value) result) =>
|
||||
public bool TryGetRegex(string name, out StreamArgument result) =>
|
||||
TryGet(new[] { name }, out result, checkDefaultMatch: false, checkRegexMatch: true);
|
||||
|
||||
public bool TryGetRegex(IEnumerable<string> names, out (string? Name, int? Index, object? Value) result) =>
|
||||
public bool TryGetRegex(IEnumerable<string> names, out StreamArgument result) =>
|
||||
TryGet(names, out result, checkDefaultMatch: false, checkRegexMatch: true);
|
||||
|
||||
public bool TryGet(IEnumerable<string> names, out (string? Name, int? Index, object? Value) result, bool checkDefaultMatch = true, bool checkRegexMatch = false) =>
|
||||
public bool TryGet(IEnumerable<string> names, out StreamArgument result, bool checkDefaultMatch = true, bool checkRegexMatch = false) =>
|
||||
TryGet(names, out result, out _, checkDefaultMatch, checkRegexMatch);
|
||||
|
||||
public bool TryGet(IEnumerable<string> names, out (string? Name, int? Index, object? Value) result, out int index, bool checkDefaultMatch = true, bool checkRegexMatch = false) {
|
||||
public bool TryGet(IEnumerable<string> names, out StreamArgument result, out int index, bool checkDefaultMatch = true, bool checkRegexMatch = false) {
|
||||
if (checkDefaultMatch) {
|
||||
foreach (var name in names.SelectMany(Variants)) {
|
||||
if (args.TryGetFirst(a => a.Name == name, out var a, out index)) {
|
||||
@@ -257,7 +257,7 @@ public class StreamFactoryArgStore {
|
||||
}
|
||||
}
|
||||
index = -1;
|
||||
result = default;
|
||||
result = StreamArgument.Empty;
|
||||
return false;
|
||||
|
||||
IEnumerable<string> Variants(string s) {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using Spark.Core;
|
||||
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
public class TimeSpanArgumentParser : IStreamArgumentParser {
|
||||
public static bool CanParse(StreamArgument arg, Type outputType) =>
|
||||
outputType == typeof(TimeSpan) || outputType == typeof(TimeSpan?);
|
||||
|
||||
public static bool TryParse(StreamArgument arg, Type outputType, out object? result, [NotNullWhen(false)] out string? error) {
|
||||
result = null;
|
||||
error = null;
|
||||
var val = arg.Value;
|
||||
switch (val) {
|
||||
case TimeSpan ts:
|
||||
result = ts;
|
||||
return true;
|
||||
case string str: {
|
||||
if (TimeSpan.TryParse(str, out var ts)) {
|
||||
result = ts;
|
||||
return true;
|
||||
}
|
||||
if (TimeSpanUnitParser.TryParse(str, out ts)) {
|
||||
result = ts;
|
||||
return true;
|
||||
}
|
||||
if (str.StartsWith("PT")) {
|
||||
try {
|
||||
// Parse ISO 8601 duration
|
||||
result = System.Xml.XmlConvert.ToTimeSpan(str);
|
||||
return true;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
if (outputType == typeof(TimeSpan?)) {
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
error = "Failed to parse TimeSpan arg";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IStreamArgumentParser.CanParse(StreamArgument arg, Type outputType) =>
|
||||
CanParse(arg, outputType);
|
||||
|
||||
bool IStreamArgumentParser.TryParse(StreamArgument arg, Type outputType, out object? result, [NotNullWhen(false)] out string? error) =>
|
||||
TryParse(arg, outputType, out result, out error);
|
||||
|
||||
public class IntSeconds : IStreamArgumentParser {
|
||||
public bool CanParse(StreamArgument arg, Type outputType) =>
|
||||
outputType == typeof(TimeSpan)
|
||||
|| outputType == typeof(TimeSpan?);
|
||||
|
||||
public bool TryParse(StreamArgument arg, Type outputType, out object? result, out string? error) {
|
||||
if (TimeSpanArgumentParser.TryParse(arg, outputType, out result, out error)) {
|
||||
return true;
|
||||
}
|
||||
if (outputType != typeof(TimeSpan) && outputType != typeof(TimeSpan?)) {
|
||||
error = $"Unsupported outputType {outputType} (expected {typeof(TimeSpan)}, possibly nullable)";
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
error = null;
|
||||
var val = arg.Value;
|
||||
switch (val) {
|
||||
case string valueStr: {
|
||||
if (int.TryParse(valueStr, out var secs)) {
|
||||
result = TimeSpan.FromSeconds(secs);
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case int i: {
|
||||
result = TimeSpan.FromSeconds(i);
|
||||
return true;
|
||||
}
|
||||
default: {
|
||||
result = null;
|
||||
return val is null && outputType == typeof(TimeSpan?);
|
||||
}
|
||||
}
|
||||
error = "Failed to parse TimeSpan arg";
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ public static class WellKnownStreamArgumentAliases {
|
||||
public const string ShowExpirationRegex = "^(show|include)(Exp(iration|Date)?)$";
|
||||
public const string ShowCashPerPointRegex = "^(show|include)(CashPerPoint|Cpp)$";
|
||||
|
||||
public const string ShowPriceRegex = "^(show|include)?(price|px|p)$";
|
||||
public const string ShowQuantityRegex = "^(show|include)?(quantity|qty|q)$";
|
||||
public const string ShowNotionalRegex = "^(show|include)?(notional|notl)$";
|
||||
|
||||
public const string ShowLegVenueRegex = "^(show|include)Leg(Exch|Venue)$";
|
||||
public const string ShowLegSecurityTypeRegex = "^(show|include)Leg(Sec|Security)?(Type|Typ)$";
|
||||
public const string ShowLegAssetRegex = "^(show|include)Leg(Symbol|Sym|Asset|Product)$";
|
||||
|
||||
@@ -18,7 +18,7 @@ public class ProxyStreamFactory : IDataStreamFactory {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) {
|
||||
if (SupportedStreams.Table.IsMatch(streamId)) {
|
||||
return createTable(args);
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public class ProxyStreamFactory : IDataStreamFactory {
|
||||
yield return SupportedStreams.Table;
|
||||
}
|
||||
|
||||
ViewStream? createTable(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? createTable(IEnumerable<StreamArgument> args) {
|
||||
if (!args.TryGetFirst(out var nameArg)) {
|
||||
logger.LogError("TableStream missing required 'name' param");
|
||||
return null;
|
||||
|
||||
@@ -21,7 +21,7 @@ public class TableStreamFactory : IDataStreamFactory {
|
||||
public ViewStream Create(string tableName) =>
|
||||
new TableStream(tableName, tableAccumulatorFactory.GetTableAccumulator(tableName));
|
||||
|
||||
ViewStream? IDataStreamFactory.Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? IDataStreamFactory.Create(string streamId, IEnumerable<StreamArgument> args) {
|
||||
if (SupportedStreams.Table.IsMatch(streamId)) {
|
||||
return createTable(args);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ public class TableStreamFactory : IDataStreamFactory {
|
||||
yield return SupportedStreams.Table;
|
||||
}
|
||||
|
||||
ViewStream? createTable(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? createTable(IEnumerable<StreamArgument> args) {
|
||||
if (!args.TryGetFirst(out var nameArg)) {
|
||||
logger.LogError("TableStream missing required 'name' param");
|
||||
return null;
|
||||
|
||||
@@ -64,7 +64,7 @@ class ArgumentExtensionFunction : IDataStreamExpression {
|
||||
}
|
||||
if (TryGetExtFn(out var extObj)) {
|
||||
var extEval = ExceptionAssert.Argument.Is<IFunctionEvaluator>(extObj);
|
||||
var argArray = new (string?, int?, object?)[arguments.Count + 1];
|
||||
var argArray = new StreamArgument[arguments.Count + 1];
|
||||
argArray[0] = (null, 0, targetObj);
|
||||
int argIdx = 1;
|
||||
var fakeStreamFactory = new DataStreamFactory();
|
||||
|
||||
@@ -121,7 +121,7 @@ class ArgumentExtensionFunctionChain : IDataStreamExpression {
|
||||
}
|
||||
if (TryGetExtFn(out var extObj)) {
|
||||
var extEval = ExceptionAssert.Argument.Is<IFunctionEvaluator>(extObj);
|
||||
var argArray = new (string?, int?, object?)[arguments.Count + 1];
|
||||
var argArray = new StreamArgument[arguments.Count + 1];
|
||||
argArray[0] = (null, 0, targetObj);
|
||||
int argIdx = 1;
|
||||
var fakeStreamFactory = new DataStreamFactory();
|
||||
|
||||
@@ -107,7 +107,7 @@ public class FunctionDefinition : IFormattableCode, IDataStreamExpression {
|
||||
this.streamFactory = streamFactory;
|
||||
}
|
||||
|
||||
public object? Evaluate(string functionId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public object? Evaluate(string functionId, IEnumerable<StreamArgument> args) {
|
||||
// Add function input args to env
|
||||
var mergedEnv = AggregateDictionary.Create(parameters.Zip(args).ToDictionary(t => t.First.Id, t => t.Second.Value), env, false);
|
||||
var res = statements.Aggregate((object?)null, (vs, s) => s.Evaluate(mergedEnv, functions, streamFactory));
|
||||
|
||||
@@ -93,7 +93,7 @@ public class PrimitiveExpression : IDataStreamExpression {
|
||||
var res = fn.Statements.Aggregate((object?)null, (vs, s) => s.Evaluate(aggEnv, functions, streamFactory));
|
||||
return res;
|
||||
} else {
|
||||
var resolvedArgs = myArgs.Select((arg, i) => (arg.Name, (int?)i, arg.Evaluate(env, functions, streamFactory)));
|
||||
var resolvedArgs = myArgs.Select((arg, i) => new StreamArgument(arg.Name, i, arg.Evaluate(env, functions, streamFactory)));
|
||||
// This is a system function/ctr. For example
|
||||
// someStream(arg1, arg2, ...)
|
||||
var res = streamFactory.Create(myName, resolvedArgs);
|
||||
|
||||
@@ -17,7 +17,7 @@ public class RowAddColumnEvaluator : ExtensionFunctionEvaluator<IBlueRow> {
|
||||
return new AddColumnRow(row, outputSchema, GetValue(row), colInfos.Length);
|
||||
|
||||
object? GetValue(IBlueRow r) =>
|
||||
applyFn.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
||||
applyFn.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class StreamAddColumnEvaluator : ExtensionFunctionEvaluator<ViewStream> {
|
||||
.AsViewStream();
|
||||
|
||||
object? GetValue(IBlueRow r) =>
|
||||
applyFn.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
||||
applyFn.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public class StreamFilterEvaluator : ExtensionFunctionEvaluator<ViewStream> {
|
||||
bd.Remove(r.Id());
|
||||
}
|
||||
foreach (var r in dp.addedRows) {
|
||||
if (ExceptionAssert.of_type<bool>(filter.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) }))) {
|
||||
if (ExceptionAssert.of_type<bool>(filter.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) }))) {
|
||||
bd.AddOrUpdate(r);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class StreamGroupByEvaluator : ExtensionFunctionEvaluator<ViewStream> {
|
||||
return vs.AsObservable().Scan((IDataPacket)null!, Update).AsViewStream();
|
||||
|
||||
IBlueRow KeyWrapper(IBlueRow r) =>
|
||||
ExceptionAssert.of_type<IBlueRow>(eval.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) }));
|
||||
ExceptionAssert.of_type<IBlueRow>(eval.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) }));
|
||||
|
||||
IDataPacket Update(IDataPacket? last, IDataPacket dp) {
|
||||
// var removes = new GroupByEvaluator<IBlueRow>()
|
||||
|
||||
@@ -13,7 +13,7 @@ public class TableAddColumnEvaluator : ExtensionFunctionEvaluator<IBlueRowCollec
|
||||
return new AddColumnTable(rows, colName, colType, GetValue);
|
||||
|
||||
object? GetValue(IBlueRow r) =>
|
||||
applyFn.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
||||
applyFn.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ public class TableApplyEvaluator : ExtensionFunctionEvaluator<IBlueRowCollection
|
||||
return tableOut;
|
||||
|
||||
IBlueRow ApplyWrapper(IBlueRow inputRow) {
|
||||
var res = applyFn.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, inputRow) });
|
||||
var res = applyFn.Evaluate(string.Empty, new StreamArgument[] { (null, 0, inputRow) });
|
||||
return ExceptionAssert.of_type<IBlueRow>(res);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ public class TableColumnAppenderEvaluator : ExtensionFunctionEvaluator<IBlueRowC
|
||||
return outputTable;
|
||||
|
||||
object? GetValue(IBlueRow r) {
|
||||
var rv = eval.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
||||
var rv = eval.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) });
|
||||
return rv;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ public class TableGroupByEvaluator : ExtensionFunctionEvaluator<IBlueRowCollecti
|
||||
return new GroupByTable<IBlueRow>(rows, KeyWrapper, BlueRowEqualityComparer.Instance, BlueRowComparer.AllColumnComparer());
|
||||
|
||||
IBlueRow KeyWrapper(IBlueRow r) =>
|
||||
ExceptionAssert.of_type<IBlueRow>(eval.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) }));
|
||||
ExceptionAssert.of_type<IBlueRow>(eval.Evaluate(string.Empty, new StreamArgument[] { (null, 0, r) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ using System.Collections.Generic;
|
||||
public class FilterStreamFactory : IRecursiveDataStreamFactory {
|
||||
IDataStreamFactory? compositeFactory;
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) {
|
||||
if (SupportedStreams.Filter.IsMatch(streamId)) {
|
||||
return createFilter(args);
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public class FilterStreamFactory : IRecursiveDataStreamFactory {
|
||||
public void OnCompositeFactory(IDataStreamFactory compositeFactory) =>
|
||||
this.compositeFactory = compositeFactory;
|
||||
|
||||
ViewStream? createFilter(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? createFilter(IEnumerable<StreamArgument> args) {
|
||||
if (compositeFactory is null || !args.TryGetSingle(out var arg)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ public class GroupByApplyStreamFactory : IDataStreamFactory {
|
||||
Log.assert(group.table.state.Count > 0);
|
||||
var hash = hashIndex.GetOrAdd(group.group_key, _ => hashCounter++);
|
||||
var groupRowCollection = new TableUpdateGroupingRowCollection<EquatableKeyWrapper>(group, group.table.state.Values.First().schema);
|
||||
var applyArgs = new (string?, int?, object?)[] { ("rows", 0, groupRowCollection) };
|
||||
var applyArgs = new StreamArgument[] { ("rows", 0, groupRowCollection) };
|
||||
var res = apply.Evaluate(string.Empty, applyArgs);
|
||||
if (res is IBlueRow resSingleRow) {
|
||||
UpdateGroupTable(group.group_key, new SingleRowTable(resSingleRow));
|
||||
@@ -91,7 +91,7 @@ public class GroupByApplyStreamFactory : IDataStreamFactory {
|
||||
return inputStream.AsObservable().AsTables().GroupTable(r => r.Id(), GroupKey).Subscribe(observer);
|
||||
|
||||
EquatableKeyWrapper GroupKey(IBlueRow r) {
|
||||
var groupByArgs = new (string?, int?, object?)[] { ("row", 0, r) };
|
||||
var groupByArgs = new StreamArgument[] { ("row", 0, r) };
|
||||
var groupKey = new EquatableKeyWrapper(groupBy.Evaluate(string.Empty, groupByArgs) ?? DBNull.Value);
|
||||
return groupKey;
|
||||
}
|
||||
@@ -105,7 +105,7 @@ public class GroupByApplyStreamFactory : IDataStreamFactory {
|
||||
return CreateGroupByApplyTable(args.InputStream, groupFn, applyFn).AsDataPackets();
|
||||
}
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
public ViewStream? Create(string streamId, IEnumerable<StreamArgument> args) {
|
||||
if (SupportedStreams.GroupByApply.IsMatch(streamId)) {
|
||||
return createGroupByApply(args);
|
||||
}
|
||||
@@ -116,7 +116,7 @@ public class GroupByApplyStreamFactory : IDataStreamFactory {
|
||||
yield return SupportedStreams.GroupByApply;
|
||||
}
|
||||
|
||||
ViewStream? createGroupByApply(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
ViewStream? createGroupByApply(IEnumerable<StreamArgument> args) {
|
||||
if (!StreamFactoryArgStore.TryGetParams(args, out GroupByApplyStreamParams? gbasp, out var err)) {
|
||||
logger.LogInvalidParams("groupByApply", err);
|
||||
return null;
|
||||
|
||||
@@ -8,12 +8,12 @@ using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
class MarketDataArgStore {
|
||||
ImmutableList<(string? Name, int? Index, object? Value)> argsBacking;
|
||||
ImmutableList<StreamArgument> argsBacking;
|
||||
readonly ILogger? logger;
|
||||
readonly string streamType;
|
||||
StreamFactoryArgStore? argStoreBacking;
|
||||
|
||||
public MarketDataArgStore(IEnumerable<(string? Name, int? Index, object? Value)> args, string? streamType = null, ILogger? logger = null) {
|
||||
public MarketDataArgStore(IEnumerable<StreamArgument> args, string? streamType = null, ILogger? logger = null) {
|
||||
argsBacking = args.ToImmutableList();
|
||||
this.streamType = streamType ?? "anonStream";
|
||||
this.logger = logger;
|
||||
@@ -22,7 +22,7 @@ class MarketDataArgStore {
|
||||
public StreamFactoryArgStore ArgStore =>
|
||||
argStoreBacking ?? new(args, streamType, logger);
|
||||
|
||||
ImmutableList<(string? Name, int? Index, object? Value)> args {
|
||||
ImmutableList<StreamArgument> args {
|
||||
get => argsBacking;
|
||||
set {
|
||||
argsBacking = value;
|
||||
|
||||
@@ -10,42 +10,11 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
class SpatialArbStatsStreamFactory : IDataStreamFactory {
|
||||
readonly IMarketDataClient marketDataClient;
|
||||
readonly ViewStreamDatabase viewStreamDatabase;
|
||||
readonly ILogger logger;
|
||||
|
||||
public SpatialArbStatsStreamFactory(IMarketDataClient marketDataClient, ViewStreamDatabase viewStreamDatabase, ILogger<SpatialArbStatsStreamFactory> logger) {
|
||||
this.marketDataClient = marketDataClient;
|
||||
this.viewStreamDatabase = viewStreamDatabase;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
if (SupportedStreams.SpatialArbStats.IsMatch(streamId)) {
|
||||
return createSpatialArbStats(args);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() {
|
||||
yield return SupportedStreams.SpatialArbStats;
|
||||
}
|
||||
|
||||
ViewStream? createSpatialArbStats(IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
if (!StreamFactoryArgStore.TryGetParams(args, out SpatialArbStatsStreamParams? sassp, out var err)) {
|
||||
logger.LogInvalidParams("spatialArbStats", err);
|
||||
return null;
|
||||
}
|
||||
return new SpatialArbStatsStream(marketDataClient, sassp.WindowSize, sassp.SamplingInterval, viewStreamDatabase);
|
||||
}
|
||||
|
||||
static class SupportedStreams {
|
||||
public static readonly DataStreamMetadata SpatialArbStats = new() {
|
||||
Name = "spatialArbStats",
|
||||
AlternateNames = new() { "SpatialArbStatsStream" },
|
||||
};
|
||||
class SpatialArbStatsStreamFactory : DataStreamFactory {
|
||||
public SpatialArbStatsStreamFactory(IMarketDataClient mdClient, ViewStreamDatabase viewStreamDatabase, ILogger<SpatialArbStatsStreamFactory> logger) {
|
||||
this.Add<SpatialArbStatsStreamParams>(
|
||||
new[] { "spatialArbStats", "SpatialArbStatsStream" },
|
||||
sp => new SpatialArbStatsStream(mdClient, sp.WindowSize, sp.SamplingInterval, viewStreamDatabase),
|
||||
logger);
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,65 @@ namespace Bts.SharedStreams.StreamFactories;
|
||||
|
||||
using Bts.DataStreamCore;
|
||||
|
||||
public class SpatialArbStatsStreamParams {
|
||||
[StreamArgument(RegexNames = new[] { "^win(dow)?_?(Sz|Size)?" }, Position = 0, ParserType = typeof(TimeSpanOrSecondsParser))]
|
||||
public TimeSpan WindowSize { get; set; }
|
||||
using Spark.Core;
|
||||
|
||||
[StreamArgument(RegexNames = new[] { "^(sampling|sample|poll|polling)_?(Interval|Period|Size|Sz)" }, Position = 1, ParserType = typeof(TimeSpanOrSecondsParser))]
|
||||
public class SpatialArbStatsStreamParams {
|
||||
[StreamArgumentConstructor(false)]
|
||||
public SpatialArbStatsStreamParams() { }
|
||||
|
||||
public SpatialArbStatsStreamParams(
|
||||
[StreamArgument(RegexNames = new[] { "^win(dow)?_?(Sz|Size)?" }, Position = 0, ParserType = typeof(TimeSpanOrSecondsParser))] TimeSpan windowSize,
|
||||
[StreamArgument(RegexNames = new[] { "^(sampling|sample|poll|polling)_?(Interval|Period|Size|Sz)" }, Position = 1, ParserType = typeof(TimeSpanOrSecondsParser))] TimeSpan samplingInterval
|
||||
) {
|
||||
WindowSize = windowSize;
|
||||
SamplingInterval = samplingInterval;
|
||||
}
|
||||
|
||||
public TimeSpan WindowSize { get; set; }
|
||||
public TimeSpan SamplingInterval { get; set; }
|
||||
|
||||
class TimeSpanOrSecondsParser : IStreamArgumentParser {
|
||||
public bool TryParse(string? name, string? valueStr, out object? result) {
|
||||
if (int.TryParse(valueStr, out var secs)) {
|
||||
result = TimeSpan.FromSeconds(secs);
|
||||
return true;
|
||||
public bool CanParse(StreamArgument arg, Type outputType) {
|
||||
if (outputType == typeof(TimeSpan)) {
|
||||
return arg.Value switch {
|
||||
string or TimeSpan or int => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
if (TimeSpan.TryParse(valueStr, out var ts)) {
|
||||
result = ts;
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryParse(StreamArgument arg, Type outputType, out object? result, out string? error) {
|
||||
if (outputType != typeof(TimeSpan)) {
|
||||
error = $"Unsupported outputType {outputType} (expected {typeof(TimeSpan)})";
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
error = null;
|
||||
switch (arg.Value) {
|
||||
case string valueStr: {
|
||||
if (TimeSpan.TryParse(valueStr, out var ts)) {
|
||||
result = ts;
|
||||
return true;
|
||||
}
|
||||
if (TimeSpanUnitParser.TryParse(valueStr, out ts)) {
|
||||
result = ts;
|
||||
return true;
|
||||
}
|
||||
if (int.TryParse(valueStr, out var secs)) {
|
||||
result = TimeSpan.FromSeconds(secs);
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TimeSpan ts: {
|
||||
result = ts;
|
||||
return true;
|
||||
}
|
||||
case int i: {
|
||||
result = TimeSpan.FromSeconds(i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
result = null;
|
||||
return false;
|
||||
|
||||
+10
-26
@@ -8,32 +8,16 @@ using Bts.DataStreamCore;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System.Collections.Generic;
|
||||
class SpatialFuturePairsStreamFactory : DataStreamFactory {
|
||||
public SpatialFuturePairsStreamFactory(IMarketDataClient marketDataClient) {
|
||||
this.Add(
|
||||
new DataStreamMetadata() {
|
||||
Name = "spatialFuturePairs",
|
||||
AlternateNames = new() { "SpatialFuturePairsStream" }
|
||||
},
|
||||
Create);
|
||||
|
||||
class SpatialFuturePairsStreamFactory : IDataStreamFactory {
|
||||
readonly IMarketDataClient marketDataClient;
|
||||
|
||||
public SpatialFuturePairsStreamFactory(IMarketDataClient marketDataClient) =>
|
||||
this.marketDataClient = marketDataClient;
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) {
|
||||
if (SupportedStreams.SpatialFuturePairs.IsMatch(streamId)) {
|
||||
return createSpatialFuturePairs(args);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() {
|
||||
yield return SupportedStreams.SpatialFuturePairs;
|
||||
}
|
||||
|
||||
ViewStream createSpatialFuturePairs(IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
new SpatialFuturePairsStream(marketDataClient);
|
||||
|
||||
static class SupportedStreams {
|
||||
public static readonly DataStreamMetadata SpatialFuturePairs = new() {
|
||||
Name = "spatialFuturePairs",
|
||||
AlternateNames = new() { "SpatialFuturePairsStream" },
|
||||
};
|
||||
ViewStream? Create() =>
|
||||
new SpatialFuturePairsStream(marketDataClient);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user