diff --git a/src/DataStreamSuite/DataStream/BlueOrb/FeatherReaderStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/FeatherReaderStream.cs new file mode 100644 index 000000000..c050ff5e2 --- /dev/null +++ b/src/DataStreamSuite/DataStream/BlueOrb/FeatherReaderStream.cs @@ -0,0 +1,506 @@ +namespace bts.BlueOrb; + +using Apache.Arrow; +using Apache.Arrow.Ipc; +using Apache.Arrow.Types; + +using BCG; + +using bts.collections; + +using Bts.DataStreamCore; + +using Spark.Core.Disposables; +using Spark.Core.Threading; + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +[DataStreamUserRespresentation("featherReader")] +public class FeatherReaderStream : ViewStream { + readonly string file; + FileStream fileStream; + // Let the table leak in case some dangling references linger around after + // myOnLastSubscriber is called. This should be fine since it disposes itself + // in its finalizer. + FeatherTable? table; + + public FeatherReaderStream(string file) => + this.file = file; + + protected override void myOnFirstSubscriber() { + if (!Path.Exists(file)) { + throw new InvalidOperationException("Feather file does not exist"); + } + fileStream = File.OpenRead(file); + table = new(new ArrowStreamReader(fileStream)); + myFireEvent(new DataPacket(table, table, new BlueTableImmutable(table.schema))); + } + + interface IFeatherColumn { + int Count { get; } + + object? GetValue(int i); + } + + interface IFeatherColumn : IFeatherColumn { + new T? GetValue(int i); + + object? IFeatherColumn.GetValue(int i) => + GetValue(i); + } + + class FeatherColumn : IFeatherColumn { + readonly IArrowArray array; + + public FeatherColumn(IArrowArray array) { + this.array = array; + } + + public int Count => array.Length; + + public static IFeatherColumn Create(IArrowArray array) => + array switch { + Int32Array a => new FeatherInt32Column(a), + Int64Array a => new FeatherInt64Column(a), + DoubleArray a => new FeatherFloat64Column(a), + StringArray a => new FeatherStringColumn(a), + BooleanArray a => new FeatherBooleanColumn(a), + Date64Array a => new FeatherDateTimeColumn(a), + Time64Array a => new FeatherTimeStampColumn(a), + _ => throw new NotSupportedException($"Unsupported type: {array.GetType()}") + }; + + public object? GetValue(int i) => + array switch { + Int32Array a => a.GetValue(i), + Int64Array a => a.GetValue(i), + DoubleArray a => a.GetValue(i), + StringArray a => a.GetString(i), + BooleanArray a => a.GetValue(i), + Date64Array a => a.GetValue(i), + Time64Array a => a.GetValue(i), + _ => throw new NotSupportedException($"Unsupported type: {array.GetType()}") + }; + } + + class FeatherInt32Column : IFeatherColumn { + readonly Int32Array array; + + public FeatherInt32Column(Int32Array array) => + this.array = array; + + public int Count => array.Length; + + public int? GetValue(int i) => array.GetValue(i); + } + + class FeatherInt64Column : IFeatherColumn { + readonly Int64Array array; + + public FeatherInt64Column(Int64Array array) => + this.array = array; + + public int Count => array.Length; + + public long? GetValue(int i) => array.GetValue(i); + } + + class FeatherFloat64Column : IFeatherColumn { + readonly DoubleArray array; + + public FeatherFloat64Column(DoubleArray array) => + this.array = array; + + public int Count => array.Length; + + public double? GetValue(int i) => array.GetValue(i); + } + + class FeatherFloat32Column : IFeatherColumn { + readonly FloatArray array; + + public FeatherFloat32Column(FloatArray array) => + this.array = array; + + public int Count => array.Length; + + public float? GetValue(int i) => array.GetValue(i); + } + + class FeatherStringColumn : IFeatherColumn { + readonly StringArray array; + + public FeatherStringColumn(StringArray array) => + this.array = array; + + public int Count => array.Length; + + public string? GetValue(int i) => array.GetString(i); + } + + class FeatherBooleanColumn : IFeatherColumn { + readonly BooleanArray array; + + public FeatherBooleanColumn(BooleanArray array) => + this.array = array; + + public int Count => array.Length; + + public bool? GetValue(int i) => array.GetValue(i); + } + + class FeatherDateTimeColumn : IFeatherColumn { + readonly Date64Array array; + + public FeatherDateTimeColumn(Date64Array array) => + this.array = array; + + public int Count => array.Length; + + public DateTime? GetValue(int i) { + var nanos = array.GetValue(i); + if (!nanos.HasValue) { + return null; + } + return new(nanos.Value / 100); + } + } + + class FeatherTimeStampColumn : IFeatherColumn { + readonly Time64Array array; + + public FeatherTimeStampColumn(Time64Array array) => + this.array = array; + + public int Count => array.Length; + + public DateTime? GetValue(int i) { + var nanos = array.GetValue(i); + if (!nanos.HasValue) { + return null; + } + return new(nanos.Value / 100); + } + } + + class FeatherBlueRow : IBlueRow { + readonly int id; + readonly int rowIndex; + readonly IFeatherColumn[] data; + + public FeatherBlueRow(int id, int rowIndex, IFeatherColumn[] data, IBlueTableSchema schema) { + this.id = id; + this.rowIndex = rowIndex; + this.data = data; + Schema = schema; + } + + public object? this[int index] => + index == 0 + ? id + : data[index - 1].GetValue(rowIndex); + + public IBlueTableSchema Schema { get; } + IBlueTableSchema IBlueRow.schema => Schema; + } + + class FeatherColumnDataList : IReadOnlyList { + // Represents 1 column split into batches (hence it being an array) + readonly IReadOnlyList columns; + int? count; + + public FeatherColumnDataList(IReadOnlyList columns) { + this.columns = columns; + } + + public object? this[int index] { + get { + for (int i = 0; i < columns.Count; i++) { + var col = columns[i]; + if (index < col.Count) { + return col.GetValue(index); + } + index -= col.Count; + } + throw new IndexOutOfRangeException(); + } + } + + public int Count => + count ??= columns.Sum(c => c.Count); + + public IEnumerator GetEnumerator() { + for (int i = 0; i < columns.Count; i++) { + var col = columns[i]; + for (int j = 0; j < col.Count; j++) { + yield return col.GetValue(i); + } + } + } + + IEnumerator IEnumerable.GetEnumerator() => + GetEnumerator(); + } + + class FeatherTable : IImmutableRowCollection, IDisposable { + ImmutableList<(RecordBatch Records, IFeatherColumn[] Columns)> recordBatches = ImmutableList<(RecordBatch Records, IFeatherColumn[] Columns)>.Empty; + readonly IReadOnlyDictionary fields; + readonly AtomicGate gate = new(); + int count; + ArrowStreamReader? reader; + + public FeatherTable(ArrowStreamReader reader) { + this.reader = reader; + if (reader.Schema is null) { + var batch = reader.ReadNextRecordBatch(); + Log.notnull(batch); + Log.notnull(reader.Schema); + var fcols = new IFeatherColumn[batch.ColumnCount]; + for (int i = 0; i < fcols.Length; i++) { + fcols[i] = FeatherColumn.Create(batch.Column(i)); + } + recordBatches = recordBatches.Add((batch, fcols)); + count = batch.Length; + } + fields = reader.Schema.Fields; + var columns = new ColumnInfo[fields.Count + 1]; + columns[0] = new("id", 0, typeof(int)); + for (int i = 0; i < fields.Count; i++) { + var f = reader.Schema.GetFieldByIndex(i); + Log.assert(f.Name != "id"); + columns[i + 1] = new(f.Name, i + 1, getFieldType(f)); + } + schema = new BlueTableSchema("FeatherReader", columns); + } + + ~FeatherTable() => + Disposable.DisposeThreadSafe(ref reader); + + public IBlueTableSchema schema { get; } + + public int Count { + get { + if (reader is not null) { + readBatches().Wait(); + Log.isnull(reader); + } + return count; + } + } + + public IBlueRow this[int id] => GetRow(id - 1); + + public bool containsID(int id) { + while (id > count && reader is not null) { + readBatches(1).Wait(); + } + return id <= count; + } + + public int IndexOf(IBlueRow item) { + int id = item.Id(); + while (id > count && reader is not null) { + readBatches(1).Wait(); + } + return id <= count && BlueRowEqualityComparer.Equals(GetRow(id - 1), item) + ? id - 1 + : -1; + } + + public IBlueRow GetRow(int index) { + if (index < 0) { + throw new IndexOutOfRangeException(); + } + if (count <= index) { + readRows(index + 1).Wait(); + } + int id = index + 1; + foreach (var (records, columns) in recordBatches) { + if (index < records.Length) { + return new FeatherBlueRow(id, index, columns, schema); + } + index -= records.Length; + } + throw new IndexOutOfRangeException(); + } + + public IList GetColumn(int index) => + new FeatherColumnDataList(new MyColList(this, index)).as_mutable(); + + public IEnumerator GetEnumerator() { + int i = 0; + foreach (var (records, columns) in recordBatches) { + yield return new FeatherBlueRow(i + 1, i, columns, schema); + i++; + } + while (reader is not null) { + var task = readBatches(1); + task.Wait(); + if (!task.Result) { + break; + } + yield return new FeatherBlueRow(i + 1, i, recordBatches[i].Columns, schema); + i++; + } + } + + public void Dispose() => + Disposable.DisposeThreadSafe(ref reader); + + static Type getFieldType(Field f) => + f.DataType.TypeId switch { + ArrowTypeId.Null => throw new NotImplementedException(), + ArrowTypeId.Boolean => typeof(bool), + ArrowTypeId.UInt8 => typeof(byte), + ArrowTypeId.Int8 => typeof(sbyte), + ArrowTypeId.UInt16 => typeof(ushort), + ArrowTypeId.Int16 => typeof(short), + ArrowTypeId.UInt32 => typeof(uint), + ArrowTypeId.Int32 => typeof(int), + ArrowTypeId.UInt64 => typeof(ulong), + ArrowTypeId.Int64 => typeof(long), + ArrowTypeId.HalfFloat => throw new NotImplementedException(), + ArrowTypeId.Float => typeof(float), + ArrowTypeId.Double => typeof(double), + ArrowTypeId.String => typeof(string), + ArrowTypeId.Binary => throw new NotImplementedException(), + ArrowTypeId.FixedSizedBinary => throw new NotImplementedException(), + ArrowTypeId.Date32 => throw new NotImplementedException(), + ArrowTypeId.Date64 => throw new NotImplementedException(), + ArrowTypeId.Timestamp => throw new NotImplementedException(), + ArrowTypeId.Time32 => throw new NotImplementedException(), + ArrowTypeId.Time64 => throw new NotImplementedException(), + ArrowTypeId.Interval => throw new NotImplementedException(), + ArrowTypeId.Decimal128 => throw new NotImplementedException(), + ArrowTypeId.Decimal256 => throw new NotImplementedException(), + ArrowTypeId.List => throw new NotImplementedException(), + ArrowTypeId.Struct => throw new NotImplementedException(), + ArrowTypeId.Union => throw new NotImplementedException(), + ArrowTypeId.Dictionary => throw new NotImplementedException(), + ArrowTypeId.Map => throw new NotImplementedException(), + _ => throw new ArgumentException("Unsupported field type", nameof(f)), + }; + + async Task readRows(int minCount) { + if (reader is null) { + return count >= minCount; + } + int n = 0; + using (gate.BeginTransaction()) { + if (reader is not null) { + int origCount = count; + while ((count + n) < minCount) { + Log.assert(count == origCount); + var batch = await reader.ReadNextRecordBatchAsync(); + if (batch is null) { + Disposable.dispose(ref reader); + break; + } + var columns = new IFeatherColumn[batch.ColumnCount]; + for (int i = 0; i < columns.Length; i++) { + columns[i] = FeatherColumn.Create(batch.Column(i)); + } + recordBatches.Add((batch, columns)); + n += batch.Length; + } + count += n; + } + } + return count >= minCount; + } + + async Task readBatches(int? count = null) { + if (reader is null) { + return !count.HasValue || count.Value == 0; + } + if (count.HasValue && count.Value <= recordBatches.Count) { + return true; + } + int n = 0; + using (gate.BeginTransaction()) { + if (reader is not null) { + int origCount = this.count; + var recordBatchesBd = recordBatches.ToBuilder(); + while (!count.HasValue || count-- > recordBatchesBd.Count) { + Log.assert(count == origCount); + var batch = await reader.ReadNextRecordBatchAsync(); + if (batch is null) { + Disposable.dispose(ref reader); + break; + } + var columns = new IFeatherColumn[batch.ColumnCount]; + for (int i = 0; i < columns.Length; i++) { + columns[i] = FeatherColumn.Create(batch.Column(i)); + } + recordBatchesBd.Add((batch, columns)); + n += batch.Length; + } + recordBatches = recordBatchesBd.ToImmutable(); + this.count += n; + } + } + return !count.HasValue || count.Value <= recordBatches.Count; + } + + class MyColList : IReadOnlyList { + readonly FeatherTable owner; + readonly int columnIndex; + + public MyColList(FeatherTable owner, int columnIndex) { + this.owner = owner; + this.columnIndex = columnIndex; + } + + public IFeatherColumn this[int index] { + get { + if (index < 0) { + throw new IndexOutOfRangeException(); + } + if (index >= owner.recordBatches.Count) { + var task = owner.readBatches(index + 1); + task.Wait(); + if (!task.Result) { + throw new IndexOutOfRangeException(); + } + } + return owner.recordBatches[index].Columns[columnIndex]; + } + } + + public int Count { + get { + if (owner.reader is not null) { + owner.readBatches().Wait(); + } + return owner.recordBatches.Count; + } + } + + public IEnumerator GetEnumerator() { + int i = 0; + foreach (var batch in owner.recordBatches) { + yield return batch.Columns[columnIndex]; + i++; + } + while (owner.reader is not null) { + var task = owner.readBatches(1); + task.Wait(); + if (!task.Result) { + break; + } + yield return owner.recordBatches[i].Columns[columnIndex]; + i++; + } + } + + IEnumerator IEnumerable.GetEnumerator() => + GetEnumerator(); + } + } +}