refactor: Load IDataStreamFactory(s) with dependency injection
So we can create ViewStreams that depend on other services, config, etc. Previously, the PrimitiveManager relied purely on static construction of types through reflection.
This commit is contained in:
1 parent
7566b2560f
commit
ea0a1fbcd3
59 files changed
+2124
-161
No files matched your search
@@ -19,6 +19,8 @@ using Newtonsoft.Json;
|
||||
using BCG;
|
||||
using System.Runtime.CompilerServices;
|
||||
using bts;
|
||||
using Spark.Core;
|
||||
using System.Numerics;
|
||||
|
||||
namespace bts {
|
||||
|
||||
@@ -91,13 +93,13 @@ namespace BCG {
|
||||
return BlueDataUtility.get_row_datetime_value(r, col_no, err_value);
|
||||
}
|
||||
|
||||
public static double? GetDouble(this IBlueRow r, int colNo) =>
|
||||
GetDouble(r[colNo]);
|
||||
public static double? GetFloat64(this IBlueRow r, int colNo) =>
|
||||
GetFloat64(r[colNo]);
|
||||
|
||||
public static double? GetDouble(this IBlueRow r, string colName) =>
|
||||
GetDouble(r[colName]);
|
||||
public static double? GetFloat64(this IBlueRow r, string colName) =>
|
||||
GetFloat64(r[colName]);
|
||||
|
||||
public static double? GetDouble(object obj) {
|
||||
public static double? GetFloat64(object obj) {
|
||||
if (obj is double d) {
|
||||
return d;
|
||||
}
|
||||
@@ -125,6 +127,127 @@ namespace BCG {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int? GetInt32(this IBlueRow r, int colNo) =>
|
||||
GetInt32(r[colNo]);
|
||||
|
||||
public static int? GetInt32(this IBlueRow r, string colName) =>
|
||||
GetInt32(r[colName]);
|
||||
|
||||
public static int? GetInt32(object obj) {
|
||||
checked {
|
||||
if (obj is double d) {
|
||||
return (int)d;
|
||||
}
|
||||
if (obj is int i32) {
|
||||
return i32;
|
||||
}
|
||||
if (obj is long i64) {
|
||||
return (int)i64;
|
||||
}
|
||||
if (obj is string s) {
|
||||
return double.TryParse(s, out d) ? (int)d : null;
|
||||
}
|
||||
if (obj is uint u32) {
|
||||
return (int)u32;
|
||||
}
|
||||
if (obj is ulong u64) {
|
||||
return (int)u64;
|
||||
}
|
||||
if (obj is short i16) {
|
||||
return i16;
|
||||
}
|
||||
if (obj is ushort u16) {
|
||||
return u16;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static long? GetInt64(this IBlueRow r, int colNo) =>
|
||||
GetInt64(r[colNo]);
|
||||
|
||||
public static long? GetInt64(this IBlueRow r, string colName) =>
|
||||
GetInt64(r[colName]);
|
||||
|
||||
public static long? GetInt64(object obj) {
|
||||
checked {
|
||||
if (obj is double d) {
|
||||
return (long)d;
|
||||
}
|
||||
if (obj is int i32) {
|
||||
return i32;
|
||||
}
|
||||
if (obj is long i64) {
|
||||
return i64;
|
||||
}
|
||||
if (obj is string s) {
|
||||
return double.TryParse(s, out d) ? (long)d : null;
|
||||
}
|
||||
if (obj is uint u32) {
|
||||
return u32;
|
||||
}
|
||||
if (obj is ulong u64) {
|
||||
return (long)u64;
|
||||
}
|
||||
if (obj is short i16) {
|
||||
return i16;
|
||||
}
|
||||
if (obj is ushort u16) {
|
||||
return u16;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static DateTime? GetUnixEpochDateTime(this IBlueRow row, string colName) =>
|
||||
GetUnixEpochDateTime(row[colName]);
|
||||
|
||||
public static DateTime? GetUnixEpochDateTime(this IBlueRow row, int colNo) =>
|
||||
GetUnixEpochDateTime(row[colNo]);
|
||||
|
||||
public static DateTime? GetUnixEpochDateTime(object obj) {
|
||||
var tsNanos = GetInt64(obj);
|
||||
return tsNanos.HasValue ? DateTime.UnixEpoch.Add(new TimeSpan(tsNanos.Value / 100)) : null;
|
||||
}
|
||||
|
||||
public static DateTime? GetDateTime(object obj) {
|
||||
var res = _get_datetime_value(obj, DateTime.MinValue);
|
||||
if (res == DateTime.MinValue) {
|
||||
return null;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static object GetEnum(Type type, object o) {
|
||||
try {
|
||||
if (o is null || o == DBNull.Value) {
|
||||
return null;
|
||||
} else if (o is string str) {
|
||||
return Enum.TryParse(type, str, true, out var res) ? res : null;
|
||||
} else if (o is int || o is uint || o is long || o is ulong || o is short || o is ushort) {
|
||||
return Convert.ChangeType(o, type);
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static T? GetEnum<T>(object o) where T : struct, Enum {
|
||||
try {
|
||||
if (o is null || o == DBNull.Value) {
|
||||
return null;
|
||||
} else if (o is string str) {
|
||||
return Enum.TryParse(str, true, out T res) ? res : null;
|
||||
} else if (o is int || o is short || o is ushort || o is uint || o is long || o is ulong)
|
||||
return (T)o;
|
||||
else if (o is T t) {
|
||||
return t;
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static T get_enum<T>(this IBlueRow r, string col_name, T err_value = default(T)) where T : struct {
|
||||
return BlueDataUtility.get_row_enum_value<T>(r, col_name, err_value);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
|
||||
public class BlueRowStore<T1, T2, T3, T4, T5, T6> : IBlueRow, IReadOnlyDictionary<string, object?> {
|
||||
readonly string? name;
|
||||
IBlueTableSchema? _schema;
|
||||
|
||||
public BlueRowStore() { }
|
||||
|
||||
public BlueRowStore(
|
||||
int id,
|
||||
(string Name, T1 Value) item1,
|
||||
(string Name, T2 Value) item2,
|
||||
(string Name, T3 Value) item3,
|
||||
(string Name, T4 Value) item4,
|
||||
(string Name, T5 Value) item5,
|
||||
(string Name, T6 Value) item6
|
||||
) {
|
||||
Id = id;
|
||||
Item1 = item1;
|
||||
Item2 = item2;
|
||||
Item3 = item3;
|
||||
Item4 = item4;
|
||||
Item5 = item5;
|
||||
Item6 = item6;
|
||||
}
|
||||
|
||||
public int Id { get; set; }
|
||||
public (string Name, T1 Value) Item1 { get; set; }
|
||||
public (string Name, T2 Value) Item2 { get; set; }
|
||||
public (string Name, T3 Value) Item3 { get; set; }
|
||||
public (string Name, T4 Value) Item4 { get; set; }
|
||||
public (string Name, T5 Value) Item5 { get; set; }
|
||||
public (string Name, T6 Value) Item6 { get; set; }
|
||||
|
||||
public int Count => 5;
|
||||
public IReadOnlyList<string> Keys => new KeyList(this);
|
||||
public IReadOnlyList<object?> Values => new ValueList(this);
|
||||
|
||||
public IBlueTableSchema schema =>
|
||||
_schema ??= new BlueTableSchema(name, new ColumnInfo[]{
|
||||
new("id", 0, typeof(int)),
|
||||
new(Item1.Name, 1, typeof(T1)),
|
||||
new(Item2.Name, 2, typeof(T2)),
|
||||
new(Item3.Name, 3, typeof(T3)),
|
||||
new(Item4.Name, 4, typeof(T4)),
|
||||
new(Item5.Name, 5, typeof(T5)),
|
||||
new(Item6.Name, 6, typeof(T6)),
|
||||
});
|
||||
|
||||
ICollection IDictionary.Keys => new KeyList(this);
|
||||
ICollection IDictionary.Values => new ValueList(this);
|
||||
|
||||
IEnumerable<string> IReadOnlyDictionary<string, object?>.Keys => Keys;
|
||||
IEnumerable<object?> IReadOnlyDictionary<string, object?>.Values => Values;
|
||||
|
||||
bool ICollection.IsSynchronized => false;
|
||||
object ICollection.SyncRoot => this;
|
||||
|
||||
public object? this[string colName] {
|
||||
get {
|
||||
if (colName == "id") {
|
||||
return Id;
|
||||
}
|
||||
if (colName == Item1.Name) {
|
||||
return Item1.Value;
|
||||
}
|
||||
if (colName == Item2.Name) {
|
||||
return Item2.Value;
|
||||
}
|
||||
if (colName == Item3.Name) {
|
||||
return Item3.Value;
|
||||
}
|
||||
if (colName == Item4.Name) {
|
||||
return Item4.Value;
|
||||
}
|
||||
if (colName == Item5.Name) {
|
||||
return Item5.Value;
|
||||
}
|
||||
if (colName == Item6.Name) {
|
||||
return Item6.Value;
|
||||
}
|
||||
throw new KeyNotFoundException();
|
||||
}
|
||||
set {
|
||||
if (colName == "id") {
|
||||
Id = ExceptionAssert.Cast(value).To<int>();
|
||||
}
|
||||
if (colName == Item1.Name) {
|
||||
Item1 = (Item1.Name, ExceptionAssert.Cast(value).To<T1>());
|
||||
}
|
||||
if (colName == Item2.Name) {
|
||||
Item2 = (Item2.Name, ExceptionAssert.Cast(value).To<T2>());
|
||||
}
|
||||
if (colName == Item3.Name) {
|
||||
Item3 = (Item3.Name, ExceptionAssert.Cast(value).To<T3>());
|
||||
}
|
||||
if (colName == Item4.Name) {
|
||||
Item4 = (Item4.Name, ExceptionAssert.Cast(value).To<T4>());
|
||||
}
|
||||
if (colName == Item5.Name) {
|
||||
Item5 = (Item5.Name, ExceptionAssert.Cast(value).To<T5>());
|
||||
}
|
||||
if (colName == Item6.Name) {
|
||||
Item6 = (Item6.Name, ExceptionAssert.Cast(value).To<T6>());
|
||||
}
|
||||
throw new KeyNotFoundException();
|
||||
}
|
||||
}
|
||||
|
||||
public object? this[int index] => index switch {
|
||||
0 => Id,
|
||||
1 => Item1.Value,
|
||||
2 => Item2.Value,
|
||||
3 => Item3.Value,
|
||||
4 => Item4.Value,
|
||||
5 => Item5.Value,
|
||||
6 => Item6.Value,
|
||||
_ => throw new IndexOutOfRangeException()
|
||||
};
|
||||
|
||||
object? IDictionary.this[object key] {
|
||||
get => this[ExceptionAssert.Cast(key).To<string>()];
|
||||
set => this[ExceptionAssert.Cast(key).To<string>()] = value;
|
||||
}
|
||||
|
||||
public void CopyTo(Array array, int index) {
|
||||
array.SetValue(Id, index++);
|
||||
array.SetValue(Item1.Value, index++);
|
||||
array.SetValue(Item2.Value, index++);
|
||||
array.SetValue(Item3.Value, index++);
|
||||
array.SetValue(Item4.Value, index++);
|
||||
array.SetValue(Item5.Value, index++);
|
||||
array.SetValue(Item6.Value, index++);
|
||||
}
|
||||
|
||||
public bool Contains(object key) =>
|
||||
key is string keystr && ContainsKey(keystr);
|
||||
|
||||
public bool ContainsKey(string key) =>
|
||||
Keys.Contains(key);
|
||||
|
||||
public void SetId(int id) =>
|
||||
Id = id;
|
||||
|
||||
public void SetValue1(T1 value) =>
|
||||
Item1 = (Item1.Name, value);
|
||||
|
||||
public void SetValue1(string colName, T1 value) =>
|
||||
Item1 = (colName, value);
|
||||
|
||||
public void SetValue2(T2 value) =>
|
||||
Item2 = (Item2.Name, value);
|
||||
|
||||
public void SetValue2(string colName, T2 value) =>
|
||||
Item2 = (colName, value);
|
||||
|
||||
public void SetValue3(T3 value) =>
|
||||
Item3 = (Item3.Name, value);
|
||||
|
||||
public void SetValue3(string colName, T3 value) =>
|
||||
Item3 = (colName, value);
|
||||
|
||||
public void SetValue4(T4 value) =>
|
||||
Item4 = (Item4.Name, value);
|
||||
|
||||
public void SetValue4(string colName, T4 value) =>
|
||||
Item4 = (colName, value);
|
||||
|
||||
public void SetValue5(T5 value) =>
|
||||
Item5 = (Item5.Name, value);
|
||||
|
||||
public void SetValue5(string colName, T5 value) =>
|
||||
Item5 = (colName, value);
|
||||
|
||||
public void SetValue6(T6 value) =>
|
||||
Item6 = (Item6.Name, value);
|
||||
|
||||
public void SetValue6(string colName, T6 value) =>
|
||||
Item6 = (colName, value);
|
||||
|
||||
public bool TryGetValue(string key, [MaybeNullWhen(false)] out object? value) {
|
||||
if (!Keys.TryFindIndex(key, out int index)) {
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
value = this[index];
|
||||
return true;
|
||||
}
|
||||
|
||||
void IDictionary.Add(object key, object? value) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
void IDictionary.Clear() =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
void IDictionary.Remove(object key) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
IDictionaryEnumerator IDictionary.GetEnumerator() =>
|
||||
throw new NotImplementedException();
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() =>
|
||||
throw new NotImplementedException();
|
||||
|
||||
public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
class KeyList : ICollection, IReadOnlyList<string> {
|
||||
readonly BlueRowStore<T1, T2, T3, T4, T5, T6> store;
|
||||
|
||||
public KeyList(BlueRowStore<T1, T2, T3, T4, T5, T6> store) =>
|
||||
this.store = store;
|
||||
|
||||
public int Count => 5;
|
||||
bool ICollection.IsSynchronized => false;
|
||||
object ICollection.SyncRoot => this;
|
||||
|
||||
public string this[int index] =>
|
||||
index switch {
|
||||
0 => "id",
|
||||
1 => store.Item1.Name,
|
||||
2 => store.Item2.Name,
|
||||
3 => store.Item3.Name,
|
||||
4 => store.Item4.Name,
|
||||
5 => store.Item5.Name,
|
||||
6 => store.Item6.Name,
|
||||
_ => throw new IndexOutOfRangeException()
|
||||
};
|
||||
|
||||
public void CopyTo(Array array, int index) {
|
||||
array.SetValue(store.Id, index++);
|
||||
array.SetValue(store.Item1.Value, index++);
|
||||
array.SetValue(store.Item2.Value, index++);
|
||||
array.SetValue(store.Item3.Value, index++);
|
||||
array.SetValue(store.Item4.Value, index++);
|
||||
array.SetValue(store.Item5.Value, index++);
|
||||
array.SetValue(store.Item6.Value, index++);
|
||||
}
|
||||
|
||||
public IEnumerator<string> GetEnumerator() {
|
||||
yield return "id";
|
||||
yield return store.Item1.Name;
|
||||
yield return store.Item2.Name;
|
||||
yield return store.Item3.Name;
|
||||
yield return store.Item4.Name;
|
||||
yield return store.Item5.Name;
|
||||
yield return store.Item6.Name;
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() =>
|
||||
GetEnumerator();
|
||||
}
|
||||
|
||||
class ValueList : ICollection, IReadOnlyList<object?> {
|
||||
readonly BlueRowStore<T1, T2, T3, T4, T5, T6> store;
|
||||
|
||||
public ValueList(BlueRowStore<T1, T2, T3, T4, T5, T6> store) =>
|
||||
this.store = store;
|
||||
|
||||
public object? this[int index] =>
|
||||
index switch {
|
||||
0 => store.Id,
|
||||
1 => store.Item1.Value,
|
||||
2 => store.Item2.Value,
|
||||
3 => store.Item3.Value,
|
||||
4 => store.Item4.Value,
|
||||
5 => store.Item5.Value,
|
||||
6 => store.Item6.Value,
|
||||
_ => throw new IndexOutOfRangeException()
|
||||
};
|
||||
|
||||
public int Count => 5;
|
||||
public bool IsSynchronized => false;
|
||||
public object SyncRoot => this;
|
||||
|
||||
public void CopyTo(Array array, int index) {
|
||||
array.SetValue(store.Id, index++);
|
||||
array.SetValue(store.Item1.Value, index++);
|
||||
array.SetValue(store.Item2.Value, index++);
|
||||
array.SetValue(store.Item3.Value, index++);
|
||||
array.SetValue(store.Item4.Value, index++);
|
||||
array.SetValue(store.Item5.Value, index++);
|
||||
array.SetValue(store.Item6.Value, index++);
|
||||
}
|
||||
|
||||
public IEnumerator<object?> GetEnumerator() {
|
||||
yield return store.Id;
|
||||
yield return store.Item1.Value;
|
||||
yield return store.Item2.Value;
|
||||
yield return store.Item3.Value;
|
||||
yield return store.Item4.Value;
|
||||
yield return store.Item5.Value;
|
||||
yield return store.Item6.Value;
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() =>
|
||||
GetEnumerator();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using System;
|
||||
|
||||
public interface ITimeSeriesRow : IBlueRow {
|
||||
int Id => ExceptionAssert.of_type<int>(this["id"]);
|
||||
DateTime Timestamp { get; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class CompositeDataStreamFactory : IDataStreamFactory {
|
||||
readonly List<IDataStreamFactory> streamFactories;
|
||||
|
||||
public CompositeDataStreamFactory(IEnumerable<IDataStreamFactory> streamFactories) {
|
||||
this.streamFactories = streamFactories.ToList();
|
||||
foreach (var rsf in this.streamFactories.OfType<IRecursiveDataStreamFactory>()) {
|
||||
rsf.OnCompositeFactory(this);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
streamFactories.SelectMany(f => f.GetSupportedStreams());
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
streamFactories.Where(f => f.CanCreate(streamId))
|
||||
.Select(f => f.Create(streamId, args))
|
||||
.ExceptNull()
|
||||
.FirstOrDefault();
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class DataStreamFactory : IDataStreamFactory {
|
||||
readonly List<IDataStreamFactory> factories = new();
|
||||
|
||||
public static IDataStreamFactory Create(IEnumerable<IDataStreamFactory> streamFactories) {
|
||||
var dsf = new DataStreamFactory();
|
||||
dsf.factories.AddRange(streamFactories);
|
||||
return dsf.factories.Count == 1 ? dsf.factories[0] : dsf;
|
||||
}
|
||||
|
||||
public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
factories.Where(sf => sf.GetSupportedStreams().Any(m => m.IsMatch(streamId)))
|
||||
.Select(sf => sf.Create(streamId, args))
|
||||
.ExceptNull()
|
||||
.FirstOrDefault();
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
factories.SelectMany(sf => sf.GetSupportedStreams());
|
||||
|
||||
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<TParams>(this DataStreamFactory streamFactory, IDataStreamMetadata metadata, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = new SingleDataStreamFactory<TParams>(metadata, singleStreamfactory, logger);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
|
||||
public static void Add<TParams>(this DataStreamFactory streamFactory, string name, Func<TParams, ViewStream?> singleStreamfactory, ILogger? logger = null) {
|
||||
var sf = new SingleDataStreamFactory<TParams>(new DataStreamMetadata() { Name = name }, singleStreamfactory, logger);
|
||||
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));
|
||||
}
|
||||
var meta = new DataStreamMetadata() { Name = names[0], AlternateNames = names.Skip(1).ToList() };
|
||||
var sf = new SingleDataStreamFactory<TParams>(meta, singleStreamfactory, logger);
|
||||
streamFactory.Add(sf);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using bts;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
public interface IDataStreamMetadata {
|
||||
public string Name { get; }
|
||||
public IEnumerable<string> AlternateNames { get; }
|
||||
}
|
||||
|
||||
public class DataStreamMetadata : IDataStreamMetadata {
|
||||
public string? Name { get; set; }
|
||||
public List<string>? AlternateNames { get; set; }
|
||||
|
||||
string IDataStreamMetadata.Name => Name ?? string.Empty;
|
||||
IEnumerable<string> IDataStreamMetadata.AlternateNames =>
|
||||
AlternateNames ?? new(0);
|
||||
|
||||
public static DataStreamMetadata FromType(Type type) {
|
||||
var friendlyName = type.GetCustomAttribute<DataStreamUserRespresentation>()?.friendlyName;
|
||||
var rv = new DataStreamMetadata() {
|
||||
Name = friendlyName ?? type.Name,
|
||||
AlternateNames = new(2) {
|
||||
Log.notnull(type.FullName)
|
||||
}
|
||||
};
|
||||
if (friendlyName is not null) {
|
||||
rv.AlternateNames.Add(type.Name);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
|
||||
public static class DataStreamMetadataExtensions {
|
||||
public static bool IsMatch(this IDataStreamMetadata dsm, string name, bool checkAlternateNames = true, bool ignoreCase = true, bool ignoreUnderscores = true) {
|
||||
var strComp = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
|
||||
var nameWithoutUnderscores = new Lazy<string>(() => RemoveUnderscores(name));
|
||||
return IsNameMatch(dsm.Name) || (checkAlternateNames && dsm.AlternateNames.Any(IsNameMatch));
|
||||
|
||||
static string RemoveUnderscores(string s) =>
|
||||
s.Replace("_", "");
|
||||
|
||||
bool IsNameMatch(string otherName) =>
|
||||
string.Equals(name, otherName, strComp)
|
||||
|| (ignoreUnderscores && string.Equals(nameWithoutUnderscores.Value, RemoveUnderscores(otherName), strComp));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public interface IDataStreamFactory {
|
||||
IEnumerable<IDataStreamMetadata> GetSupportedStreams();
|
||||
|
||||
ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
|
||||
bool CanCreate(string streamId) =>
|
||||
GetSupportedStreams().Any(s => s.IsMatch(streamId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This interface provides a way for IDataStreamFactory's that create ViewStreams
|
||||
/// that depend specifically on the composite IDataStreamFactory. This was designed
|
||||
/// specifically for the NLStreamDataFactory.
|
||||
/// </summary>
|
||||
public interface IRecursiveDataStreamFactory : IDataStreamFactory {
|
||||
void OnCompositeFactory(IDataStreamFactory compositeFactory);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
public interface ISingleStreamFactory : IDataStreamFactory {
|
||||
IDataStreamMetadata Metadata { get; }
|
||||
|
||||
ViewStream? Create(IEnumerable<(string? Name, int? Index, object? Value)> args);
|
||||
|
||||
ViewStream? IDataStreamFactory.Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
Metadata.IsMatch(streamId) ? Create(args) : null;
|
||||
|
||||
IEnumerable<IDataStreamMetadata> IDataStreamFactory.GetSupportedStreams() =>
|
||||
new[] { Metadata };
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
public interface IStreamArgumentParser {
|
||||
bool TryParse(string? name, string? valueStr, out object? result);
|
||||
}
|
||||
@@ -8,33 +8,36 @@ namespace BCG {
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using bts.collections;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Spark.Core.Collections;
|
||||
using Bts.DataStreamCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
public class PrimitiveManager {
|
||||
static MarketDataStreamFactory mdStreamFactory;
|
||||
private IDictionary myTypeLookupTable = new Hashtable();
|
||||
public class PrimitiveManager : IDataStreamFactory {
|
||||
private static PrimitiveManager mySelf;
|
||||
private ArrayList myAssemblyNames = new ArrayList();
|
||||
readonly List<string> myAssemblyNames = new();
|
||||
readonly Dictionary<string, Type> myTypeLookupTable = new();
|
||||
|
||||
private PrimitiveManager() {
|
||||
myLoadAllTypes();
|
||||
}
|
||||
public PrimitiveManager(IOptions<PrimitiveManagerConfig> config) : this(config.Value) { }
|
||||
|
||||
private void myLoadAllTypes() {
|
||||
public PrimitiveManager(PrimitiveManagerConfig config) {
|
||||
AppDomain currentDomain = AppDomain.CurrentDomain;
|
||||
currentDomain.AssemblyResolve += new ResolveEventHandler(myAssemblyResolver);
|
||||
loadAssembly(this.GetType().Assembly.FullName);
|
||||
var assemblies = new string[] { "DataStream.dll", "SharedStreams.dll" };
|
||||
var config_assemblies = Configuration.get<DataStreamConfig>().Assemblies;
|
||||
bts.Log.Gen.info($"PrimitiveManager.myLoadAllTypes config_assemblies: {config_assemblies}");
|
||||
foreach (string assemblyName in assemblies/*config_assemblies*/) {
|
||||
foreach (string assemblyName in config.Assemblies.empty_if_null()) {
|
||||
bts.Log.Gen.info($"PrimitiveManager.myLoadAllTypes assemblyName: {assemblyName}");
|
||||
string resolvedAssemblyPath = assemblyName;
|
||||
if (!System.IO.Path.IsPathRooted(assemblyName)) {
|
||||
resolvedAssemblyPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName));
|
||||
}
|
||||
loadAssembly(resolvedAssemblyPath);
|
||||
loadAssembly(resolvedAssemblyPath, IncludeType);
|
||||
}
|
||||
|
||||
bool IncludeType(Type t) =>
|
||||
!config.ExcludeTypes.empty_if_null().Any(tname => tname == t.Name);
|
||||
}
|
||||
|
||||
private static Assembly myAssemblyResolver(object sender, ResolveEventArgs args) {
|
||||
@@ -48,12 +51,7 @@ namespace BCG {
|
||||
/// Loads all the Stream types associated with the assembly
|
||||
/// </summary>
|
||||
/// <param name="assemblyName"></param>
|
||||
public void loadAssembly(string assemblyName) {
|
||||
Func<Type, bool> is_blue_orb = (t) => {
|
||||
//if (!assemblyName.Contains("SharedStreams.dll"))
|
||||
// return true;
|
||||
return t.Namespace == "bts.BlueOrb";// || t.Namespace == "BCG";
|
||||
};
|
||||
public void loadAssembly(string assemblyName, Func<Type, bool> typeFilter = null) {
|
||||
bts.Log.Gen.info($"PrimitiveManager.loadAssembly assemblyName: {assemblyName}");
|
||||
if (myAssemblyNames.Contains(assemblyName))
|
||||
return;
|
||||
@@ -62,8 +60,12 @@ namespace BCG {
|
||||
GetType().Assembly :
|
||||
Assembly.LoadFrom(assemblyName);
|
||||
|
||||
foreach (Type type in loadedAssembly.GetTypes())
|
||||
if (!type.IsInterface && is_blue_orb(type)
|
||||
IEnumerable<Type> types = loadedAssembly.GetTypes();
|
||||
if (typeFilter is not null) {
|
||||
types = types.Where(typeFilter);
|
||||
}
|
||||
foreach (Type type in types)
|
||||
if (!type.IsInterface
|
||||
&& !type.IsAbstract
|
||||
&& type.IsSubclassOf(typeof(ViewStream))
|
||||
&& type.IsPublic) {
|
||||
@@ -79,7 +81,7 @@ namespace BCG {
|
||||
break;
|
||||
}
|
||||
if (isVisible) {
|
||||
// Log.assert_d(myTypeLookupTable[userRep] == null, type.FullName);
|
||||
Log.assert_d(!myTypeLookupTable.ContainsKey(userRep));
|
||||
myTypeLookupTable[userRep] = type;
|
||||
}
|
||||
}
|
||||
@@ -95,26 +97,28 @@ namespace BCG {
|
||||
return retVal;
|
||||
}
|
||||
|
||||
public IEnumerable<Type> GetSupportedTypes() =>
|
||||
myTypeLookupTable.Values.Cast<Type>();
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
GenericDictionaryWrapper.Create<string, Type>(myTypeLookupTable).Select(kv => new DataStreamMetadata() {
|
||||
Name = kv.Key,
|
||||
AlternateNames = new() { kv.Value.Name, kv.Value.FullName }
|
||||
});
|
||||
|
||||
public static PrimitiveManager instance {
|
||||
get { return mySelf = mySelf == null ? new PrimitiveManager() : mySelf; }
|
||||
}
|
||||
public Type ResolveType(string streamId) =>
|
||||
TryResolveType(streamId, out var t) ? t
|
||||
: throw new ArgumentException($"Failed to resolve ViewStream type '{streamId}'", nameof(streamId));
|
||||
|
||||
public static void SetMarketDataClient(object value) {
|
||||
Log.isnull(mdStreamFactory);
|
||||
mdStreamFactory = new(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Type name corresponding to the primitive name
|
||||
/// </summary>
|
||||
/// <param name="friendlyName"></param>
|
||||
/// <returns></returns>
|
||||
public string find(string friendlyName) {
|
||||
if (myTypeLookupTable[friendlyName] == null)
|
||||
throw new ApplicationException(friendlyName + " is not the friendly name of any of the loaded types");
|
||||
return (myTypeLookupTable[friendlyName] as Type).Name;
|
||||
public bool TryResolveType(string streamId, [NotNullWhen(true)] out Type result) {
|
||||
result = GetSupportedStreams()
|
||||
.Where(s => s.IsMatch(streamId))
|
||||
.Select(s => s.Name)
|
||||
.Prepend(streamId)
|
||||
.Select(myTypeLookupTable.GetValueOrDefault)
|
||||
.ExceptNull()
|
||||
.FirstOrDefault();
|
||||
return result is not null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -130,19 +134,110 @@ namespace BCG {
|
||||
constructorArgs = new object[args.Count];
|
||||
args.CopyTo(constructorArgs, 0);
|
||||
}
|
||||
var type = myTypeLookupTable[friendlyName] as Type
|
||||
?? throw new ApplicationException(friendlyName + " is not the friendly name of any of the loaded types");
|
||||
if (type.HasCustomAttribute<LiveMarketDataStreamAttribute>()) {
|
||||
if (mdStreamFactory is null) {
|
||||
Log.Gen.error("Live md not available for streams");
|
||||
return null;
|
||||
}
|
||||
return mdStreamFactory.Create(type, constructorArgs);
|
||||
if (myTypeLookupTable[friendlyName] == null)
|
||||
throw new ApplicationException(friendlyName + " is not the friendly name of any of the loaded types");
|
||||
try {
|
||||
return
|
||||
constructorArgs == null ?
|
||||
Activator.CreateInstance(myTypeLookupTable[friendlyName] as Type) as ViewStream :
|
||||
Activator.CreateInstance(myTypeLookupTable[friendlyName] as Type, constructorArgs) as ViewStream;
|
||||
} catch (Exception ex) {
|
||||
Log.Gen.warn($"PrimitiveManager failed to construct ViewStream type '{friendlyName}': {ex}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ViewStream Create(string streamId, IEnumerable<(string Name, int? Index, object Value)> args) =>
|
||||
TryResolveType(streamId, out var type) ? Create(type, args) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Constructs and returns a ViewStream of type corresponding to the friendly name
|
||||
/// </summary>
|
||||
/// <param name="friendlyName">friendly primitive name </param>
|
||||
/// <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) {
|
||||
var ctrs = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
|
||||
var argList = args.ToList();
|
||||
const int MAX_ALLOWED_ARGS = 64;
|
||||
if (argList.Count > MAX_ALLOWED_ARGS) {
|
||||
throw new ArgumentException(
|
||||
$"ViewStream arg count ({argList.Count}) exceeds max allowed ({MAX_ALLOWED_ARGS})", nameof(args));
|
||||
}
|
||||
if (argList.Any(a => !(a.Name?.Length > 0) && !a.Index.HasValue)) {
|
||||
throw new ArgumentException(
|
||||
"One or more ViewStream args lack both Name and Index (unable to assign a constructor param)", nameof(args));
|
||||
}
|
||||
var indexedArgs = argList.Where(a => a.Index.HasValue).ToList();
|
||||
var namedArgs = argList.Where(a => a.Name?.Length > 0).ToList();
|
||||
if (!namedArgs.Select(a => a.Name).IsDistinct()) {
|
||||
throw new ArgumentException("ViewStream arg names are not unique");
|
||||
}
|
||||
if (!indexedArgs.Select(a => a.Index.Value).IsDistinct()) {
|
||||
throw new ArgumentException("ViewStream arg indices are not unique");
|
||||
}
|
||||
// Constructor params with default values may be omitted from the input 'args'. Therefore,
|
||||
// 'minArgCount' >= 'argList.Count'.
|
||||
var minArgCount = Math.Max(indexedArgs.Select(a => a.Index.Value).MaxOrDefault(), argList.Count);
|
||||
foreach (var ctr in ctrs) {
|
||||
if (TryAssignConstructorArgs(ctr, minArgCount, argList, indexedArgs, namedArgs, out var ctrArgs)) {
|
||||
return ctr.Invoke(ctrArgs) as ViewStream;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
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,
|
||||
[NotNullWhen(true)] out object[] ctrArgs
|
||||
) {
|
||||
ctrArgs = null;
|
||||
var ctrParams = ctr.GetParameters();
|
||||
if (ctrParams.Length < minArgCount) {
|
||||
return false;
|
||||
}
|
||||
var ctrArgList = new List<object>();
|
||||
int remInputArgs = argList.Count;
|
||||
for (int i = 0; i < ctrParams.Length; i++) {
|
||||
var ctrParam = ctrParams[i];
|
||||
var paramType = ctrParams[i].ParameterType;
|
||||
if (indexedArgs.TryGetFirst(a => CanAssignInputArg(ctrParam, a), out var a)) {
|
||||
remInputArgs--;
|
||||
ctrArgList.Add(a.Value);
|
||||
} else if (ctrParam.HasDefaultValue) {
|
||||
ctrArgList.Add(ctrParam.DefaultValue);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (remInputArgs > 0) {
|
||||
return false;
|
||||
}
|
||||
Log.assert(ctrArgList.Count == ctrParams.Length);
|
||||
ctrArgs = ctrArgList.ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool CanAssignInputArg(ParameterInfo pi, (string Name, int? Index, object Value) arg) {
|
||||
if (!string.IsNullOrEmpty(arg.Name) && arg.Name != pi.Name) {
|
||||
return false;
|
||||
}
|
||||
if (arg.Index.HasValue && arg.Index.Value != pi.Position) {
|
||||
return false;
|
||||
}
|
||||
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;
|
||||
}
|
||||
return
|
||||
constructorArgs == null ?
|
||||
Activator.CreateInstance(type) as ViewStream :
|
||||
Activator.CreateInstance(type, constructorArgs) as ViewStream;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class PrimitiveManagerConfig {
|
||||
public List<string>? Assemblies { get; set; }
|
||||
public List<string>? ExcludeTypes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
class SingleDataStreamFactory : ISingleStreamFactory {
|
||||
readonly Func<IEnumerable<(string?, int?, object?)>, ViewStream?> factory;
|
||||
|
||||
public SingleDataStreamFactory(IDataStreamMetadata metadata, Func<IEnumerable<(string?, int?, object?)>, ViewStream?> factory) {
|
||||
Metadata = metadata;
|
||||
this.factory = factory;
|
||||
}
|
||||
|
||||
public IDataStreamMetadata Metadata { get; }
|
||||
|
||||
public ViewStream? Create(IEnumerable<(string? Name, int? Index, object? Value)> args) =>
|
||||
factory(args);
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
new[] { Metadata };
|
||||
}
|
||||
|
||||
class SingleDataStreamFactory<TParams> : ISingleStreamFactory {
|
||||
readonly Func<TParams, ViewStream?> factory;
|
||||
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) {
|
||||
Metadata = metadata;
|
||||
this.factory = factory;
|
||||
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)) {
|
||||
logger?.LogInvalidParams(Metadata.Name, err);
|
||||
return null;
|
||||
}
|
||||
return Create(streamParams);
|
||||
}
|
||||
|
||||
public ViewStream? Create(TParams streamParams) {
|
||||
return factory(streamParams);
|
||||
}
|
||||
|
||||
public IEnumerable<IDataStreamMetadata> GetSupportedStreams() =>
|
||||
new[] { Metadata };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using System;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
public class StreamArgumentAttribute : Attribute {
|
||||
public StreamArgumentAttribute(params string[] names) {
|
||||
Names = names;
|
||||
RegexNames = Array.Empty<string>();
|
||||
}
|
||||
|
||||
public string[] Names { get; }
|
||||
public string[] RegexNames { get; set; }
|
||||
public int Position { get; set; } = -1;
|
||||
public bool IsRequired { get; set; }
|
||||
public bool AllowCommaSeparatedAliases { get; set; } = true;
|
||||
public Type? ParserType { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using BCG;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Spark.Core;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
public class StreamFactoryArgStore {
|
||||
readonly ILogger? logger;
|
||||
readonly string streamType;
|
||||
ImmutableList<(string? Name, int? Index, object? Value)> args;
|
||||
|
||||
public StreamFactoryArgStore(IEnumerable<(string? Name, int? Index, object? Value)> 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 static bool TryGetParams<T>(
|
||||
IEnumerable<(string? Name, int? Index, object? Value)> args,
|
||||
[NotNullWhen(true)] out T? result,
|
||||
[NotNullWhen(false)] out string? errorMessage
|
||||
) =>
|
||||
new StreamFactoryArgStore(args).TryGetParams(out result, out errorMessage);
|
||||
|
||||
public bool TryGetParams<T>([MaybeNull][NotNullWhen(true)] out T result, [NotNullWhen(false)] out string? errorMessage) {
|
||||
var props = typeof(T).GetProperties();
|
||||
var res = Activator.CreateInstance<T>();
|
||||
if (res is null) {
|
||||
errorMessage = $"Failed to instantiate {typeof(T)}";
|
||||
result = default;
|
||||
return false;
|
||||
}
|
||||
foreach (var p in props) {
|
||||
var att = p.GetCustomAttribute<StreamArgumentAttribute>();
|
||||
IEnumerable<string> names = att?.Names ?? new[] { p.Name };
|
||||
if (att?.AllowCommaSeparatedAliases ?? false) {
|
||||
names = names.SelectMany(n => n.Split(','));
|
||||
}
|
||||
IEnumerable<string> regexNames = att?.RegexNames ?? Enumerable.Empty<string>();
|
||||
if (TryGet(names, out var arg) || TryGetRegex(regexNames, out arg)) {
|
||||
SetValue(arg);
|
||||
} else if (att is not null && att.Position >= 0 && args.Skip(att.Position).TryGetFirst(out arg)) {
|
||||
SetValue(arg);
|
||||
} else if (att?.IsRequired ?? false) {
|
||||
errorMessage = $"Missing required param '{p.Name}'";
|
||||
result = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
void SetValue((string? Name, int? Index, object? Value) 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)) {
|
||||
throw new InvalidOperationException($"Failed to parse arg with custom parser of type {parserType}");
|
||||
}
|
||||
}
|
||||
var pType = p.PropertyType;
|
||||
bool isNullable = pType.IsNullable();
|
||||
if (isNullable) {
|
||||
pType = pType.GetGenericArguments().Single();
|
||||
}
|
||||
var vType = val?.GetType() ?? typeof(object);
|
||||
if (pType == typeof(DateTime)) {
|
||||
SetValueType(BlueDataUtility.GetDateTime(val));
|
||||
} else if (pType == typeof(TimeSpan)) {
|
||||
SetValueType(BlueDataUtility.GetTimeSpan(val));
|
||||
} else if (pType == typeof(string)) {
|
||||
p.SetValue(res, val as string ?? val?.ToString());
|
||||
} else if (pType.IsEnum) {
|
||||
p.SetValue(res, BlueDataUtility.GetEnum(pType, val));
|
||||
} else if (vType.IsAssignableTo(pType) || (val is null && (!pType.IsValueType || isNullable))) {
|
||||
p.SetValue(res, val);
|
||||
} else {
|
||||
p.SetValue(res, Convert.ChangeType(val, pType));
|
||||
}
|
||||
|
||||
void SetValueType<TProp>(TProp? pVal) where TProp : struct {
|
||||
if (isNullable) {
|
||||
p.SetValue(res, pVal);
|
||||
} else {
|
||||
p.SetValue(res, pVal.assert_value());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
errorMessage = null;
|
||||
result = res;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool GetInt32(string name, [NotNullWhen(true)] out int? result) =>
|
||||
GetInt32(out result, true, name);
|
||||
|
||||
public bool GetInt32([NotNullWhen(true)] out int? result, bool required, params string[] names) {
|
||||
result = GetInt32(names);
|
||||
if (required && !result.HasValue) {
|
||||
logger.LogMissingParam(streamType, names.Length switch {
|
||||
0 => "Int32",
|
||||
_ => names[0],
|
||||
});
|
||||
}
|
||||
return result.HasValue;
|
||||
}
|
||||
|
||||
public int? GetInt32(params string[] names) =>
|
||||
GetInt32(true, names);
|
||||
|
||||
public int? GetInt32(bool required, params string[] names) {
|
||||
if (names.Length == 0) {
|
||||
return null;
|
||||
}
|
||||
var obj = Get(names);
|
||||
if (obj is int i) {
|
||||
return i;
|
||||
}
|
||||
var s = obj as string ?? obj?.ToString();
|
||||
if (int.TryParse(s, out i)) {
|
||||
return i;
|
||||
}
|
||||
if (required && logger is not null) {
|
||||
logger.LogMissingParam(streamType, names[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool GetTimeSpan(string name, out TimeSpan? result) {
|
||||
result = GetTimeSpan(true, new[] { name });
|
||||
return result.HasValue;
|
||||
}
|
||||
|
||||
public TimeSpan? GetTimeSpan(string name) =>
|
||||
GetTimeSpan(true, new[] { name });
|
||||
|
||||
public TimeSpan? GetTimeSpan(bool required, string[] preferredNames) =>
|
||||
preferredNames
|
||||
.Select(n => BlueDataUtility.GetTimeSpan(Get(n)))
|
||||
.Where(ts => ts.HasValue)
|
||||
.FirstOrDefault();
|
||||
|
||||
public IEnumerable<string> GetStrings() =>
|
||||
args.Select(a => a.Value).OfType<string>();
|
||||
|
||||
// First, parses the args associated with preferredNames and returns the first successful
|
||||
// parse result. If none were successful, tries to parse every arg.
|
||||
public T? GetEnum<T>(params string[] preferredNames) where T : struct {
|
||||
var candidateObjs = preferredNames.Select(n => Get(n)).Concat(args.Select(a => a.Value));
|
||||
foreach (var obj in candidateObjs) {
|
||||
if (obj is T res) {
|
||||
return res;
|
||||
}
|
||||
if (obj is string s && Enum.TryParse(s, true, out res)) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<DateTime> GetDateTimes() =>
|
||||
args.Select(a => convertToDateTime(a.Value)).SelectWhereValues();
|
||||
|
||||
public bool GetDateTime(string name, [NotNullWhen(true)] out DateTime? result) {
|
||||
result = GetDateTime(true, name);
|
||||
return result.HasValue;
|
||||
}
|
||||
|
||||
public bool GetDateTime([NotNullWhen(true)] out DateTime? result, params string[] names) {
|
||||
result = GetDateTime(names);
|
||||
return result.HasValue;
|
||||
}
|
||||
|
||||
public bool GetDateTime([NotNullWhen(true)] out DateTime? result, out int index, bool removeArg) {
|
||||
int i = 0;
|
||||
foreach (var arg in args) {
|
||||
var dt = convertToDateTime(arg.Value);
|
||||
if (dt.HasValue) {
|
||||
result = dt.Value;
|
||||
index = i;
|
||||
if (removeArg) {
|
||||
args = args.RemoveAt(i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
result = null;
|
||||
index = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
public DateTime? GetDateTime(params string[] names) =>
|
||||
GetDateTime(true, names);
|
||||
|
||||
public DateTime? GetDateTime(bool required, params string[] names) =>
|
||||
names.Select(n => Get(n)).Select(convertToDateTime).Where(dt => dt.HasValue).FirstOrDefault();
|
||||
|
||||
public object? Get(params string[] names) =>
|
||||
Get(true, names);
|
||||
|
||||
public object? Get(out int index, params string[] names) =>
|
||||
Get(true, out index, names);
|
||||
|
||||
public object? Get(bool required, params string[] names) =>
|
||||
Get(required, out _, names);
|
||||
|
||||
public object? Get(bool required, out int index, params string[] names) {
|
||||
if (names.Length == 0) {
|
||||
index = -1;
|
||||
return null;
|
||||
}
|
||||
if (!TryGet(names, out var result, out index) && required && logger is not null) {
|
||||
logger.LogMissingParam(streamType, names[0]);
|
||||
}
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
public bool TryGetRegex(string name, out (string? Name, int? Index, object? Value) result) =>
|
||||
TryGet(new[] { name }, out result, checkDefaultMatch: false, checkRegexMatch: true);
|
||||
|
||||
public bool TryGetRegex(IEnumerable<string> names, out (string? Name, int? Index, object? Value) 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) =>
|
||||
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) {
|
||||
if (checkDefaultMatch) {
|
||||
foreach (var name in names.SelectMany(Variants)) {
|
||||
if (args.TryGetFirst(a => a.Name == name, out var a, out index)) {
|
||||
result = a;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (checkRegexMatch) {
|
||||
foreach (var name in names) {
|
||||
if (args.TryGetFirst(a => Regex.IsMatch(a.Name ?? string.Empty, name, RegexOptions.IgnoreCase), out var a, out index)) {
|
||||
result = a;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
index = -1;
|
||||
result = default;
|
||||
return false;
|
||||
|
||||
IEnumerable<string> Variants(string s) {
|
||||
if (string.IsNullOrEmpty(s)) {
|
||||
yield break;
|
||||
}
|
||||
yield return s;
|
||||
// Convert to snake_case
|
||||
var bd = new StringBuilder(char.ToLower(s[0]));
|
||||
for (int i = 1; i < s.Length; i++) {
|
||||
if (i > 1 && char.IsUpper(s[i]) && char.IsLower(s[i - 1])) {
|
||||
bd.Append('_');
|
||||
}
|
||||
bd.Append(char.ToLower(s[i]));
|
||||
}
|
||||
yield return bd.ToString();
|
||||
// Convert to camelCase
|
||||
bd.Clear();
|
||||
for (int i = 0; i < s.Length; i++) {
|
||||
int numUnderscores = 0;
|
||||
while (s[i + numUnderscores] == '_' & (i + numUnderscores < s.Length)) {
|
||||
numUnderscores++;
|
||||
}
|
||||
if (numUnderscores > 0) {
|
||||
i += numUnderscores;
|
||||
if (i >= s.Length) {
|
||||
break;
|
||||
}
|
||||
bd.Append(char.ToUpper(s[i]));
|
||||
} else {
|
||||
bd.Append(s[i]);
|
||||
}
|
||||
}
|
||||
yield return bd.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
static DateTime? convertToDateTime(object? obj) =>
|
||||
tryConvert(obj, out DateTime dt) ? dt : null;
|
||||
|
||||
static bool tryConvert(object? obj, out DateTime res) {
|
||||
if (obj is DateTime dt) {
|
||||
res = dt;
|
||||
return true;
|
||||
}
|
||||
if (obj is string s) {
|
||||
// if (OffsetDateTimePattern)
|
||||
if (DateTimeOffset.TryParseExact(s, "yyyy-MM-ddTHH:mm:ssK", null, System.Globalization.DateTimeStyles.None, out var dto)) {
|
||||
res = dto.ToUniversalTime().DateTime;
|
||||
return true;
|
||||
}
|
||||
if (DateTimeOffset.TryParseExact(s, "yyyy-MM-ddTHH:mm:ss.fffffffffK", null, System.Globalization.DateTimeStyles.None, out dto)) {
|
||||
res = dto.ToUniversalTime().DateTime;
|
||||
return true;
|
||||
}
|
||||
if (DateTime.TryParse(s, null, System.Globalization.DateTimeStyles.RoundtripKind, out res)) {
|
||||
return true;
|
||||
}
|
||||
if (DateTimeOffset.TryParse(s, out var resOff)) {
|
||||
res = resOff.ToUniversalTime().DateTime;
|
||||
return true;
|
||||
}
|
||||
return DateTime.TryParse(s, out res);
|
||||
}
|
||||
res = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public static partial class StreamFactoryLogs {
|
||||
[LoggerMessage(EventId = 1, Level = LogLevel.Warning, Message = "Unable to create '{StreamType}' stream. Missing required parameter '{Parameter}'.")]
|
||||
public static partial void LogMissingParam(this ILogger logger, string streamType, string parameter);
|
||||
|
||||
[LoggerMessage(EventId = 2, Level = LogLevel.Warning, Message = "Unable to create '{StreamType}' stream. {error}.")]
|
||||
public static partial void LogInvalidParams(this ILogger logger, string streamType, string error);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#nullable enable
|
||||
namespace Bts.DataStreamCore;
|
||||
|
||||
public static class WellKnownStreamArgumentAliases {
|
||||
/// <summary>
|
||||
/// Aliases for a Venue argument.
|
||||
/// </summary>
|
||||
public const string Venue = "venue,exchange,exch";
|
||||
|
||||
/// <summary>
|
||||
/// Aliases for a Type argument.
|
||||
/// </summary>
|
||||
public const string Asset = "symbol,sym,product,asset";
|
||||
|
||||
/// <summary>
|
||||
/// Aliases for a Type argument.
|
||||
/// </summary>
|
||||
public const string Type = "type,typ";
|
||||
|
||||
/// <summary>
|
||||
/// Aliases for a SecurityType argument. Some are potentially ambiguous, like 'type' and 'typ'.
|
||||
/// If this conflicts with other arguments, consider using <see cref="QualifiedSecurityType"/>.
|
||||
/// </summary>
|
||||
public const string SecurityType = "secType,secTyp,securityType,securityTyp,type,typ";
|
||||
|
||||
/// <summary>
|
||||
/// Aliases for a SecurityName argument. Some are potentially ambiguous, like 'name'. If this
|
||||
/// conflicts with other arguments, consider using <see cref="QualifiedSecurityType"/>.
|
||||
/// </summary>
|
||||
public const string SecurityName = "name,sec,secName,security";
|
||||
|
||||
public const string QualifiedSecurityType = "secType,secTyp,securityType,securityTyp";
|
||||
public const string QualifiedSecurityName = "sec,secName,security";
|
||||
|
||||
public const string VenueRegex = "^(venue|exchange|exch)$";
|
||||
public const string AssetRegex = "^(symbol|sym|asset|product)$";
|
||||
public const string TypeRegex = "^(type|typ)$";
|
||||
public const string SecurityTypeRegex = "^(secType|secTyp|type|typ)$";
|
||||
public const string SecurityNameRegex = "^(sec|security|name|secName|securityName)$";
|
||||
|
||||
public const string ShowVenueRegex = "^(show|include)(Exch|Venue)$";
|
||||
public const string ShowAssetRegex = "^(show|include)(Symbol|Sym|Asset|Product)$";
|
||||
public const string ShowSecurityTypeRegex = "^(show|include)(Sec|Security)?(Type|Typ)$";
|
||||
public const string ShowSecurityNameRegex = "^(show|include)(Sec|Security|Name|SecName|SecurityName)$";
|
||||
public const string ShowExpirationRegex = "^(show|include)(Exp(iration|Date)?)$";
|
||||
public const string ShowCashPerPointRegex = "^(show|include)(CashPerPoint|Cpp)$";
|
||||
|
||||
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)$";
|
||||
public const string ShowLegExpirationRegex = "^(show|include)Leg(Exp(iration|Date)?)$";
|
||||
public const string ShowLegNameRegex = "^(show|include)Leg(Name|Desc)$";
|
||||
public const string ShowLegCashPerPointRegex = "^(show|include)Leg(CashPerPoint|Cpp)$";
|
||||
|
||||
public const string ReplaySpeedRegex = $"^(replay|replaySpeed|speed|rate|velocity)$";
|
||||
public const string BeginDateRegex = "(begin|start)(date(Time)?|time)?";
|
||||
public const string EndDateRegex = "(end|stop)(date(Time)?|time)?";
|
||||
}
|
||||
@@ -3,6 +3,7 @@ namespace Bts.DataStreamCore.Services;
|
||||
using BCG;
|
||||
using BCG.Utilities.General;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static class DataStreamCoreServices {
|
||||
@@ -14,4 +15,11 @@ public static class DataStreamCoreServices {
|
||||
ViewStreamDatabase.SetGlobalInstance(new ViewStreamDatabase(sp.GetRequiredService<ISubscriberCore>()));
|
||||
return ViewStreamDatabase.instance;
|
||||
});
|
||||
|
||||
public static IServiceCollection AddPrimitiveStreams(this IServiceCollection services, IConfiguration configurationSection) =>
|
||||
services.Configure<PrimitiveManagerConfig>(configurationSection)
|
||||
.AddSingleton<IDataStreamFactory, PrimitiveManager>();
|
||||
|
||||
public static IServiceCollection AddCompositeDataStreamFactory(this IServiceCollection services) =>
|
||||
services.AddSingleton<CompositeDataStreamFactory>();
|
||||
}
|
||||
Reference in new issue
Block a user