using Google.Protobuf.WellKnownTypes; using Google.Protobuf; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reactive.Linq; using System.IO; using System.Reactive.Disposables; using mbts; using System.Threading; namespace bts.api.core { internal class QuickbusClientChannel : ClientChannel { IntPtr _client; public QuickbusClientChannel(ServiceContext context, string type_name, string qualifier) : base(context) { _client = ApiNativeMethods.api_client_create(context.native_context, type_name, qualifier); System.Diagnostics.Trace.Assert(_client != IntPtr.Zero); } public override void Dispose() { ApiNativeMethods.api_client_destroy(_client); _client = IntPtr.Zero; } int _req_id = 0; Dictionary _keepalive_cache = new Dictionary(); unsafe public override Task> send(int method_id, Request request) { var id = Interlocked.Increment(ref _req_id); var header = new RequestHeader() { Method = method_id, RequestId = id, }; var buffer = header.serialize(request); var tcs = new TaskCompletionSource>(); //ApiNativeMethods.api_client_log_error($"Call {id}"); ApiNativeMethods.raw_pb_callback callback = (rbuffer, rlength, _) => { //ApiNativeMethods.api_client_log_error($"Reply {id}"); var res = ApiUtils.deserialize(rbuffer, (long)rlength); if (res.header.Code == ApiError.Success) { tcs.TrySetResult(new Result(res.body)); } else { tcs.TrySetResult(new Result(res.header.Code)); } lock (_keepalive_cache) { _keepalive_cache.Remove(id); } }; System.Diagnostics.Trace.Assert(_client != IntPtr.Zero, "Channel may have been disposed"); lock (_keepalive_cache) { _keepalive_cache.Add(id, callback); } ApiNativeMethods.api_client_send(_client, buffer, buffer.Length, callback, IntPtr.Zero); return tcs.Task; } public unsafe override IObservable> subscribe(string method_and_qualifier, MessageParser parser, Func converter) { var result = Observable.Create>(observer => { bool first_update = true; // Memory optimization. There is only one update per subscription. RawUpdate the_update = new RawUpdate(); ApiNativeMethods.raw_subscription_callback cb = (event_type, changes, change_count, unused) => { the_update.Clear(); try { if (event_type == ApiNativeMethods.EventType.TABLE_UPDATED) { foreach (var change in changes) { switch (change.type) { case ApiNativeMethods.ChangeType.REMOVE: the_update.removed_keys.Add(change.key); break; case ApiNativeMethods.ChangeType.REPLACE: the_update.changed_items.Add(converter(parser.ParseFrom(new UnmanagedMemoryStream(change.buffer, change.buffer_len)))); the_update.changed_keys.Add(change.key); break; case ApiNativeMethods.ChangeType.CREATE: the_update.added_items.Add(converter(parser.ParseFrom(new UnmanagedMemoryStream(change.buffer, change.buffer_len)))); the_update.added_keys.Add(change.key); break; } } observer.OnNext(the_update); } else if (event_type == ApiNativeMethods.EventType.TABLE_CREATED) { if (!first_update) { observer.OnNext(the_update.MarkAsReset()); } first_update = false; } } catch (Exception e) { ApiNativeMethods.api_client_log_error($"Exception in subscription callback for sub: '{method_and_qualifier}' \n--\n '{e}'"); // Sleep to let the log message get asyncronously written to disk Thread.Sleep(100); Environment.Exit(-1); } }; var subscription = ApiNativeMethods.api_client_subscribe(_client, method_and_qualifier, cb, IntPtr.Zero); return FinalizeableAnonymousDisposable.Create((disposing) => { ApiNativeMethods.api_client_unsubscribe(_client, subscription); subscription = IntPtr.Zero; GC.KeepAlive(cb); cb = null; // Cannot (ever) call logging from the finalizer thread // if (!disposing) { // ApiNativeMethods.api_client_log_error($"Subscription has been terminated because the returned IDisposable has been finalized. Subscription: {method_and_qualifier}"); // } }); }); return result; } private class FinalizeableAnonymousDisposable : IDisposable { private Action _action; public FinalizeableAnonymousDisposable(Action dispose) { _action = dispose; } public static FinalizeableAnonymousDisposable Create(Action dispose) { return new FinalizeableAnonymousDisposable(dispose); } ~FinalizeableAnonymousDisposable() { Dispose(false); } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } protected virtual void Dispose(bool disposing) { var temp = _action; _action = null; temp?.Invoke(disposing); } } public override bool is_sync_call_ok() { return !ApiNativeMethods.api_client_is_on_qb_thread(_client); } } }