feat: Add GroupByApplyStream

This commit is contained in:
John Colvin committed 2025-11-15 12:45:08 -05:00
1 parent 4bb4008ac6
commit c365330b08
18 files changed
+1127

No files matched your search

@@ -0,0 +1,93 @@
#nullable enable
namespace bts.BlueOrb;
using BCG;
using Bts.DataStream;
using Bts.DataStreamCore;
using Spark.Core.Disposables;
using System;
public class ApplyStream : ViewStream {
readonly ViewStream source;
readonly Func<IBlueRow, object?> apply;
IBlueTableSchema? outputSchema;
BlueTableImmutable? lastFired;
IDisposable? sub;
public ApplyStream(ViewStream source, IFunctionEvaluator applyEvaluator) {
this.source = source;
apply = Apply;
object? Apply(IBlueRow r) {
var res = applyEvaluator.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
return res;
}
}
public ApplyStream(ViewStream source, Func<IBlueRow, object?> apply) {
this.source = source;
this.apply = apply;
}
protected override void myOnFirstSubscriber() {
sub = source.Subscribe(OnSourceChanged);
void OnSourceChanged(IDataPacket dp) {
Lazy<BlueTableImmutable> lastFired = new(() => this.lastFired ??= new(Log.notnull(outputSchema)));
Lazy<BlueTableImmutable.DataPacketBuilder> bd = new(() => lastFired.Value.ToDataPacketBuilder());
foreach (var r in dp.deletedRows) {
var res = apply(r);
if (res is IBlueRow blueRow) {
bd.Value.Remove(blueRow.Id());
} else if (res is IBlueRowCollection blueRows) {
foreach (var br in blueRows) {
bd.Value.Remove(br.Id());
}
} else {
Log.assert(false, $"apply delegate returned obj of unexpected type '{res?.GetType()}'");
}
}
foreach (var r in dp.addedRows) {
var res = apply(r);
if (res is IBlueRow blueRow) {
outputSchema ??= blueRow.schema;
bd.Value.AddOrUpdate(blueRow);
} else if (res is IBlueRowCollection blueRows) {
outputSchema ??= blueRows.schema;
foreach (var br in blueRows) {
bd.Value.AddOrUpdate(br);
}
} else {
if (outputSchema is null) {
// We get the outputSchema from the result of the first apply, if it's null, we
// cannot determine the output data type.
// TODO: maybe support specifying return type in DSL?
Log.notnull(res);
}
var resType = res?.GetType();
if (outputSchema is null) {
Log.notnull(resType);
Log.assert(ColumnInfo.isAllowedType(resType));
outputSchema = new BlueTableSchema(new ColumnInfo[] {
new("id", 0, typeof(int)),
new("result", 1, resType),
}, dp.newRows.schema.tableName + "_Apply");
}
bd.Value.AddOrUpdate(new BlueRow(outputSchema, new object?[] { r.Id(), res }));
// Log.assert(false, $"apply delegate returned obj of unexpected type '{res?.GetType()}'");
}
}
if (bd.IsValueCreated) {
myFireEvent(bd.Value.ToDataPacket(out this.lastFired));
}
}
}
protected override void myOnLastSubscriber() {
Disposable.dispose(ref sub);
}
}
@@ -0,0 +1,23 @@
namespace bts.BlueOrb;
using BCG;
public class IndexRow : IBlueRow {
readonly IBlueRow inputRow;
readonly int id;
readonly int idIndex;
public IndexRow(IBlueRow inputRow, int id, int idIndex, IBlueTableSchema schema) {
this.inputRow = inputRow;
this.id = id;
this.idIndex = idIndex;
this.schema = schema;
}
public IBlueRow InputRow => inputRow;
public IBlueTableSchema schema { get; }
public object? this[int index] =>
index == idIndex ? id : inputRow[index];
}
@@ -0,0 +1,93 @@
namespace bts.BlueOrb;
using BCG;
using Bts.DataStreamCore;
using Spark.Core.Collections;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
public class IndexTable : IBlueRowCollection {
readonly IBlueRowCollection inputRows;
readonly IDictionary<int, int> outputToInputIdMap;
readonly IDictionary<int, int> inputToOutputIdMap;
readonly int idColIndex;
public IndexTable(IBlueRowCollection inputRows, IDictionary<int, int> outputToInputIdMap, IDictionary<int, int> inputToOutputIdMap) {
this.inputRows = inputRows;
this.outputToInputIdMap = outputToInputIdMap;
this.inputToOutputIdMap = inputToOutputIdMap;
if (!inputRows.schema.columnInfo.TryGetFirst(c => c.colName == "id", out var idColInfo)) {
throw new ArgumentException("No 'id' column", nameof(inputRows));
}
idColIndex = idColInfo.colNo;
}
public IBlueTableSchema schema => inputRows.schema;
public int Count => inputRows.Count;
public IBlueRow this[int id] =>
outputToInputIdMap.TryGetValue(id, out var inputId)
? new IndexRow(inputRows[inputId], id, idColIndex, schema)
: throw new KeyNotFoundException();
IBlueRow IList<IBlueRow>.this[int index] {
get => GetRow(index);
set => throw new NotSupportedException();
}
public static IndexTable Create(IBlueRowCollection inputRows) {
var outputToInputIdMap = new Dictionary<int, int>();
var inputToOutputIdMap = new Dictionary<int, int>();
foreach (var r in inputRows) {
int inputId = r.Id();
int outputId = outputToInputIdMap.Count + 1;
outputToInputIdMap[outputId] = inputId;
inputToOutputIdMap[inputId] = outputId;
}
return new(inputRows, outputToInputIdMap, inputToOutputIdMap);
}
public static BlueTableImmutable CreateImmutable(IBlueTableSchema schema, IEnumerable<IBlueRow> rows) {
int idIndex = schema.ResolveIndices("id");
var rowSetBd = ImmutableSortedSet.Create(KeyValuePairComparer.KeyComparer<int, IBlueRow>()).ToBuilder();
foreach (var r in rows) {
int idx = rowSetBd.Count + 1;
var inputRow = (r as IndexRow)?.InputRow ?? r;
rowSetBd.Add(new(idx, new IndexRow(inputRow, idx, idIndex, schema)));
}
return new(schema, rowSetBd.ToImmutable());
}
public bool containsID(int id) =>
inputRows.containsID(id);
public IEnumerator<IBlueRow> GetEnumerator() {
foreach (var r in inputRows) {
yield return new IndexRow(r, inputToOutputIdMap[r.Id()], idColIndex, schema);
}
}
public IBlueRow GetRow(int index) {
var r = inputRows.GetRow(index);
return new IndexRow(r, inputToOutputIdMap[r.Id()], idColIndex, schema);
}
public int IndexOf(IBlueRow item) {
int id = item.Id();
if (outputToInputIdMap.TryGetValue(id, out var inputId)) {
var inputRow = inputRows[inputId];
var r = new IndexRow(inputRow, id, idColIndex, schema);
if (BlueRowEqualityComparer.Equals(r, item)) {
var idx = inputRows.IndexOf(inputRow);
Log.assert(idx >= 0);
return idx;
}
}
return -1;
}
}
@@ -7,6 +7,7 @@ using bts.api.core;
using Bts.DataStreamCore;
using Bts.PubSub;
using Bts.SharedStreams.StreamFactories;
using mbts.utils;
@@ -137,6 +138,21 @@ public static class DataStreamExtensions {
public static ViewStream AsViewStream<T>(this IObservable<TableUpdate<T, int>> source, IBlueTableSchema schema) where T : IBlueRow =>
source.AsDataPackets(schema).AsViewStream();
public static ViewStream GroupByApply(this ViewStream viewStream, string[] columns, Func<IBlueRowCollection, IBlueRowCollection> apply) {
var groupByTables = GroupByApplyStream.CreateGroupByTable(viewStream, columns);
var applyTables = GroupByApplyStream.CreateApplyTable(groupByTables, FunctionEvaluator.Create(apply));
return applyTables.AsDataPackets().AsViewStream();
}
public static ViewStream GroupByApply(this ViewStream viewStream, string[] columns, Func<object?[], IBlueRowCollection, IBlueRowCollection?> apply) {
var groupByTables = GroupByApplyStream.CreateGroupByTable(viewStream, columns);
var applyTables = GroupByApplyStream.CreateApplyTable(groupByTables, new Func<EquatableKeyArrayWrapper, IBlueRowCollection, IBlueRowCollection?>(ApplyWrapper));
return applyTables.AsDataPackets().AsViewStream();
IBlueRowCollection? ApplyWrapper(EquatableKeyArrayWrapper groupKey, IBlueRowCollection groupRows) =>
apply(groupKey.Values, groupRows);
}
public static IDisposable Subscribe(this ViewStream viewStream, Action<IDataPacket> onChange) {
viewStream.onChange += OnChange;
return Disposable.Create(Dispose);