From 07087fd707e71f37acf1983e4149c32c73663564 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 17 Feb 2019 15:35:26 -0600 Subject: [PATCH] made TableUpdate.LeftJoin() extension --- src/client/spark_api/api/Update.cs | 26 +- .../api/Update/TableUpdateLeftJoin.cs | 225 ++++++++++++++++++ .../spark_api/utils/LazySubscription.cs | 35 +++ src/client/spark_test/Utils/TestUtils.cs | 42 ++++ src/client/spark_test/api/ApiUpdateTests.cs | 160 +++++++++++++ 5 files changed, 487 insertions(+), 1 deletion(-) create mode 100644 src/client/spark_api/api/Update/TableUpdateLeftJoin.cs create mode 100644 src/client/spark_api/utils/LazySubscription.cs create mode 100644 src/client/spark_test/Utils/TestUtils.cs diff --git a/src/client/spark_api/api/Update.cs b/src/client/spark_api/api/Update.cs index b29f0aac3..7c53aadc0 100644 --- a/src/client/spark_api/api/Update.cs +++ b/src/client/spark_api/api/Update.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; @@ -8,6 +7,7 @@ using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; +using System.Reactive.Subjects; namespace bts.api.core { @@ -288,6 +288,9 @@ namespace bts.api.core { public Builder(TableUpdate state) => _state = state; + public void add_or_update(T value) => + add_or_update(_state.key_extractor(value), value); + public void add_or_update(TKey key, T value) { if (_state.state.TryGetValue(key, out T curr)) { _removed.Remove(key); @@ -344,6 +347,9 @@ namespace bts.api.core { } public static class ObservableUpdateExtensions { + internal static bool has_changes(this TableUpdate table) where TKey : IEquatable => + table.added.Any() || table.changes.Any() || table.removed.Any(); + internal static IObservable> reconstitute(this IObservable> source, Func key_extractor) where TKey : IEquatable { var state = new Dictionary(); return source.Select(raw => { @@ -591,5 +597,23 @@ namespace bts.api.core { return new TableUpdate(cache, added, changes, removed, key); }); } + + public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + Func left_key, Func right_key, TRight right_default = default) + where TKey : IEquatable => + new TableUpdateLeftJoin( + left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => (lv, rv), (lv, lk, rk) => (lv, right_default), t => left_key(t.left)); + + public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + Func left_key, Func right_key, Func result_selector, Func absent_right_result_selector, Func result_key) + where TKey : IEquatable => + new TableUpdateLeftJoin( + left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => result_selector(lv, lk, rv), (lv, lk, rk) => absent_right_result_selector(lv, lk), result_key); + + public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + Func key, Func right_key, Func join_key, Func result_selector, Func absent_result_selector, Func result_key) + where TLeftKey : IEquatable + where TRightKey : IEquatable => + new TableUpdateLeftJoin(left_source, right_source, key, right_key, join_key, result_selector, absent_result_selector, result_key); } } \ No newline at end of file diff --git a/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs new file mode 100644 index 000000000..e1fa250d5 --- /dev/null +++ b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Reactive.Subjects; +using System.Threading; + +namespace bts.api.core { + class TableUpdateLeftJoin : IConnectableObservable> + where TLeftKey : IEquatable + where TRightKey : IEquatable { + // left + readonly Func _left_key; + readonly IObservable> _left_source; + // right + readonly Func _right_key; + readonly IObservable> _right_source; + // join + readonly Func _result_selector; + readonly Func _absent_right_result_selector; + readonly Func _join_key; + readonly Dictionary> _join_index = new Dictionary>(); + readonly Subject> _subject = new Subject>(); + // state + TableUpdate _table; + Dictionary _right_state = new Dictionary(); + IReadOnlyDictionary _left_state = new Dictionary(); + + IDisposable _subscriptions = mbts.Disposable.empty; + int _connection; // unconnected = 0, connected == 1 + Queue<_Op> _buffer = new Queue<_Op>(); + bool _is_updating, _left_completed, _right_completed; + + public TableUpdateLeftJoin(IObservable> left_source, IObservable> right_source, Func left_key, Func right_key, + Func join_key, Func result_selector, Func absent_right_result_selector, Func result_key) { + _left_source = left_source; + _left_key = left_key; + _right_source = right_source; + _right_key = right_key; + _join_key = join_key; + _result_selector = result_selector; + _absent_right_result_selector = absent_right_result_selector; + _table = TableUpdate.mk_empty(result_key); + } + + public IDisposable Connect() { + if (Interlocked.CompareExchange(ref _connection, 1, 0) == 0) { + _subscriptions = new CompositeDisposable( + _left_source.Subscribe(_on_left_update, _on_left_completed), + _right_source.Subscribe(_on_right_update, _on_right_completed)); + } + return Disposable.Create(() => { + if (Interlocked.CompareExchange(ref _connection, 0, 1) == 1) + _subscriptions.Dispose(); + }); + } + + public IDisposable Subscribe(IObserver> observer) { + lock (this) { + if (_is_updating) { + var sub = new LazySubscription>(observer); + _buffer.Enqueue(new _Op(sub)); + return sub; + } + return _subscribe_core(observer); + } + } + + IDisposable _subscribe_core(IObserver> observer) { + observer.OnNext(_table.as_snapshot()); + return _subject.Subscribe(observer); + } + + + #region Left + void _on_left_completed() { + lock (this) { + _left_completed = true; + if (_right_completed) + _subject.OnCompleted(); + } + } + void _on_left_update(TableUpdate left_update) { + lock (this) { + if (_is_updating) { + _buffer.Enqueue(new _Op(left_update)); + return; + } + _is_updating = true; + } + _process_left(left_update); + } + + void _process_left(TableUpdate left_update) { + var builder = _table.to_builder(); + foreach (var v in left_update.removed) { + var lk = _left_key(v); + builder.remove(lk); + var rk = _join_key(v); + var joined = _join_index[rk]; + if (joined.Remove(lk) && joined.Count == 0) + _join_index.Remove(rk); + } + foreach (var v in left_update.added.Concat(left_update.changed)) { + var lk = _left_key(v); + var rk = _join_key(v); + var result = _right_state.TryGetValue(rk, out TRight r) ? _result_selector(v, lk, r, rk) : _absent_right_result_selector(v, lk, rk); + builder.add_or_update(lk, result); + if (!_join_index.TryGetValue(rk, out HashSet joined)) + _join_index.Add(rk, joined = new HashSet()); + joined.Add(lk); + } + _left_state = left_update.state; + _table = builder.to_table(); + _subject.OnNext(_table); + _on_op_completed(); + } + #endregion + + #region Right + void _on_right_completed() { + lock (this) { + _right_completed = true; + if (_left_completed) + _subject.OnCompleted(); + } + } + + void _on_right_update(TableUpdate right_update) { + lock (this) { + if (_is_updating) { + _buffer.Enqueue(new _Op(right_update)); + return; + } + _is_updating = true; + } + _process_right(right_update); + } + + void _process_right(TableUpdate right_update) { + var builder = _table.to_builder(); + foreach (var v in right_update.removed) { + var rkey = _right_key(v); + if (_join_index.TryGetValue(rkey, out HashSet lkeys)) { + foreach (var k in lkeys) { + var lval = _left_state[k]; + var result = _absent_right_result_selector(lval, k, rkey); + builder.add_or_update(k, result); + } + if (lkeys.Count == 0) + _join_index.Remove(rkey); + } + _right_state.Remove(rkey); + } + foreach (var v in right_update.added.Concat(right_update.changed)) { + var rkey = _right_key(v); + if (_join_index.TryGetValue(rkey, out HashSet lkeys)) { + foreach (var k in lkeys) { + var lval = _left_state[k]; + var result = _result_selector(lval, k, v, rkey); + builder.add_or_update(k, result); + } + } else { + _join_index.Add(rkey, new HashSet()); + } + _right_state[rkey] = v; + } + _table = builder.to_table(); + if (_table.has_changes()) { + _subject.OnNext(_table); + } + _on_op_completed(); + } + #endregion + + void _on_op_completed() { + Log.assert(_is_updating); + _Op buffered_op; + lock (this) { + if (_buffer.Count == 0) { + _is_updating = false; + return; + } + buffered_op = _buffer.Dequeue(); + } + switch (buffered_op.update_case) { + case _Op.UpdateOneofCase.Left: + _process_left(buffered_op.left); + break; + case _Op.UpdateOneofCase.Right: + _process_right(buffered_op.right); + break; + case _Op.UpdateOneofCase.Subscription: + buffered_op.subscription.connect(Observable.Create(new Func>, IDisposable>(_subscribe_core))); + break; + } + _on_op_completed(); + } + + class _Op { + public readonly TableUpdate left; + public readonly TableUpdate right; + public readonly LazySubscription> subscription; + + public _Op(TableUpdate left) => this.left = left; + public _Op(TableUpdate right) => this.right = right; + public _Op(LazySubscription> subscription) => + this.subscription = subscription; + + public enum UpdateOneofCase { + Left, Right, Subscription + } + + public UpdateOneofCase update_case { + get { + if (left != null) return UpdateOneofCase.Left; + if (right != null) return UpdateOneofCase.Right; + if (subscription != null) return UpdateOneofCase.Subscription; + throw new InvalidOperationException("Unexpected state."); + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark_api/utils/LazySubscription.cs b/src/client/spark_api/utils/LazySubscription.cs new file mode 100644 index 000000000..ad9aa0959 --- /dev/null +++ b/src/client/spark_api/utils/LazySubscription.cs @@ -0,0 +1,35 @@ +using System; + +namespace bts.api { + class LazySubscription : IDisposable { + readonly IObserver _observer; + IDisposable _subscription; + bool _is_disposed; + + public LazySubscription(IObserver observer) => + _observer = observer; + + // idempotent + public void connect(IObservable source) { + lock (this) { + if (!_is_disposed && _subscription != null) + _subscription = source.Subscribe(_observer); + } + } + // idempotent + public void Dispose() { + IDisposable sub; + lock (this) { + if (_is_disposed) + return; + _is_disposed = true; + if (_subscription == null) + return; + sub = _subscription; + _subscription = null; + } + // avoid disposing inside the lock + sub.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/Utils/TestUtils.cs b/src/client/spark_test/Utils/TestUtils.cs new file mode 100644 index 000000000..f469031f3 --- /dev/null +++ b/src/client/spark_test/Utils/TestUtils.cs @@ -0,0 +1,42 @@ +using bts.collections; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace bts.tests.utils { + static class TestUtils { + public static List randomize_values(IReadOnlyList input) { + var remaining_indices = Enumerable.Range(0, input.Count).ToList(); + var rand = new Random(); + var rv = new List(); + while (remaining_indices.Count > 0) { + int ri = rand.Next(0, remaining_indices.Count); + int index = remaining_indices[ri]; + remaining_indices.RemoveAt(ri); + //if (remaining_indices.RemoveAt(index)) { + + //} else { + + //} + rv.Add(input[index]); + } + return rv; + } + + public static List randomize_values(List input, Func get_key, Func get_value, Func factory) { + // shuffle ids + var rand_keys = input.Select(get_key).ToList(); + rand_keys.Shuffle(); + // shuffle names + var rand_names = input.Select(get_value).ToList(); + rand_names.Shuffle(); + var reshuffled = new List(); + var rand = new Random(); + for (int i = 0; i < input.Count; i++) { + var k = rand_keys[i]; + reshuffled.Add(factory(rand_names[i], k)); + } + return reshuffled; + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/api/ApiUpdateTests.cs b/src/client/spark_test/api/ApiUpdateTests.cs index e1f6f08b7..a0feaa204 100644 --- a/src/client/spark_test/api/ApiUpdateTests.cs +++ b/src/client/spark_test/api/ApiUpdateTests.cs @@ -1,6 +1,10 @@ using bts.api.core; +using bts.collections; using bts.test; +using bts.tests.utils; +using bts.utils; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reactive.Concurrency; @@ -26,6 +30,9 @@ namespace mbts.api.Test { } public int id { get; } public string name { get; } + + public Item with(string name) => new Item(id, name); + public override string ToString() => $"{id}-{name}"; public override bool Equals(object obj) { if (obj is Item i) { @@ -413,6 +420,159 @@ namespace mbts.api.Test { } + TableUpdate _empty_table => + TableUpdate.mk_empty(i => i.id); + + struct LeftJoinUpdateItem { + public readonly Item add_or_update; + public readonly int? remove; + public readonly bool is_left; + + public LeftJoinUpdateItem(int id, string name, bool is_left) + : this(new Item(id, name), null, is_left) { } + + public LeftJoinUpdateItem(Item add_or_update, bool is_left) + : this(add_or_update, null, is_left) { } + + public LeftJoinUpdateItem(int remove, bool is_left) + : this(null, remove, is_left) { } + + LeftJoinUpdateItem(Item add_or_update, int? remove, bool is_left) { + this.add_or_update = add_or_update; + this.remove = remove; + this.is_left = is_left; + } + + public LeftJoinUpdateItem to_remove() { + if (remove.HasValue) + return this; + return new LeftJoinUpdateItem(null, add_or_update.id, is_left); + } + } + + class LeftJoinTest { + readonly List<(TableUpdate left, TableUpdate right)> _update_sequence = new List<(TableUpdate left, TableUpdate right)>(); + readonly List> _result_sequence = new List>(); + + + public LeftJoinTest(IEnumerable update_items) { + var left_table = TableUpdate.mk_empty(i => i.id); + var right_table = TableUpdate.mk_empty(i => i.id); + var curr_table = TableUpdate<(Item left, Item right), int>.mk_empty(i => i.left.id); + foreach (var ui in update_items) { + var builder = curr_table.to_builder(); + if (ui.is_left) { + var lbuilder = left_table.to_builder(); + if (ui.remove.HasValue) { + lbuilder.remove(ui.remove.Value); + builder.remove(ui.remove.Value); + } else { + var l = new Item(ui.add_or_update.id, ui.add_or_update.name); + var r = right_table.state.TryGetValue(ui.add_or_update.id, out Item _r) ? _r : null; + lbuilder.add_or_update(l); + builder.add_or_update((l, r)); + } + left_table = lbuilder.to_table(); + _update_sequence.Add((left_table, null)); + } else { + var rbuilder = right_table.to_builder(); + if (ui.remove.HasValue) { + rbuilder.remove(ui.remove.Value); + if (curr_table.state.TryGetValue(ui.remove.Value, out (Item l, Item r) lr)) { + builder.add_or_update((lr.l, null)); + } + } else { + var r = new Item(ui.add_or_update.id, ui.add_or_update.name); + rbuilder.add_or_update(r); + if (curr_table.state.TryGetValue(ui.add_or_update.id, out (Item l, Item r) lr)) { + builder.add_or_update((lr.l, r)); + } + } + right_table = rbuilder.to_table(); + _update_sequence.Add((null, right_table)); + } + _result_sequence.Add(curr_table = builder.to_table()); + } + } + + public IReadOnlyList<(TableUpdate left, TableUpdate right)> update_sequence => _update_sequence; + public IReadOnlyList> result_sequence => _result_sequence; + public IReadOnlyDictionary expected_state => _result_sequence.Last().state; + } + + [Test] + public void test_left_join() { + var left_items = new[] { + new LeftJoinUpdateItem(1, "a", true), + new LeftJoinUpdateItem(2, "b", true), + new LeftJoinUpdateItem(3, "c", true), + new LeftJoinUpdateItem(4, "d", true), + }; + var right_items = new[] { + new LeftJoinUpdateItem(1, "x", false), + new LeftJoinUpdateItem(2, "y", false), + new LeftJoinUpdateItem(3, "z", false), + new LeftJoinUpdateItem(4, "q", false) + }; + // pseudo random sequences that cover basic add/update/remove scenarios. + IEnumerable> sequences = new[] { + left_items.Concat(right_items), + right_items.Concat(left_items), + left_items.Take(2).Concat(right_items.Take(1)).Concat(left_items.Skip(2)).Concat(right_items.Skip(2)), + left_items.Take(2).Concat(right_items.Take(2)).Concat(left_items.Skip(2)).Concat(right_items.Skip(3)), + right_items.Take(2).Concat(left_items.Take(1)).Concat(right_items.Skip(2)).Concat(left_items.Skip(4)), + right_items.Take(2).Concat(left_items.Take(2)).Concat(right_items.Skip(2)).Concat(left_items.Skip(2)), + // with removes + new[] { left_items[0], right_items[0], left_items[0].to_remove() }, + new[] { left_items[0], right_items[0], left_items[0].to_remove(), right_items[0].to_remove() }, + new[] { left_items[0], right_items[0], right_items[1], left_items[0].to_remove(), right_items[1].to_remove() }, + new[] { left_items[0], right_items[0], right_items[1], left_items[1].to_remove(), left_items[0].to_remove() }, + new[] { left_items[1], right_items[1], right_items[0], left_items[1].to_remove(), right_items[0].to_remove() }, + new[] { left_items[0], right_items[1], right_items[0], left_items[0].to_remove(), left_items[1].to_remove() }, + // with removes, then re-adds + new[] { left_items[0], right_items[0], right_items[1], left_items[0].to_remove(), right_items[1].to_remove(), left_items[0], right_items[1] }, + new[] { left_items[0], right_items[0], right_items[1], left_items[1].to_remove(), left_items[0].to_remove(), left_items[0], left_items[1], }, + new[] { left_items[1], right_items[1], right_items[0], left_items[1].to_remove(), right_items[0].to_remove(), right_items[0] }, + new[] { left_items[1], right_items[1], right_items[0], left_items[1].to_remove(), right_items[0].to_remove(), right_items[0], left_items[1] }, + new[] { left_items[0], right_items[1], right_items[0], left_items[0].to_remove(), left_items[1].to_remove(), left_items[1], left_items[0] } + }; + + foreach (var seq in sequences) + impl(new LeftJoinTest(seq)); + + void impl(LeftJoinTest test) { + var left_source = new Subject>(); + var right_source = new Subject>(); + // join/state + var join = left_source.LeftJoin(right_source, i => i.id, i => i.id, null).RefCount(); + var update_list = new List>(); + join.Subscribe(t => { + lock (update_list) { + update_list.Add(t); + } + }, on_completed); + foreach (var (left, right) in test.update_sequence) { + if (left != null) { + left_source.OnNext(left); + } if (right != null) { + right_source.OnNext(right); + } + } + // verify + void on_completed() { + Assert.AreEqual(update_list.Count, test.result_sequence.Count); + var actual_state = update_list.Last().state; + for (int i = 0; i < update_list.Count; i++) { + var actual = update_list[i]; + var expected = test.result_sequence[i]; + Assert.IsTrue(new HashSet<(Item, Item)>(actual.removed).SetEquals(expected.changed)); + Assert.IsTrue(new HashSet<(Item, Item)>(actual.changed).SetEquals(expected.removed)); + Assert.IsTrue(new HashSet<(Item, Item)>(actual.added).SetEquals(expected.added)); + } + } + } + } + //public class Box { // public int value; // public override string ToString() {