refactor: Change Configuration.initialize to be async
This commit is contained in:
1 parent
d9e804b4e1
commit
f922215cae
4 files changed
+165
-28
No files matched your search
@@ -0,0 +1,35 @@
|
||||
#nullable enable
|
||||
namespace Spark.Core;
|
||||
|
||||
using bts.api.core;
|
||||
|
||||
using System;
|
||||
|
||||
sealed class ManagedQuickbusWrapper : IDisposable {
|
||||
readonly object lockObj = new();
|
||||
IntPtr handle;
|
||||
|
||||
public ManagedQuickbusWrapper()
|
||||
: this(ApiNativeMethods.api_create_quickbus(null, 0)) {}
|
||||
|
||||
internal ManagedQuickbusWrapper(IntPtr handle) =>
|
||||
this.handle = handle;
|
||||
|
||||
public static ManagedQuickbusWrapper None => new(IntPtr.Zero);
|
||||
|
||||
public IntPtr Handle => handle;
|
||||
|
||||
public bool IsDisposed => handle == IntPtr.Zero;
|
||||
|
||||
public void Dispose() {
|
||||
if (IsDisposed) {
|
||||
return;
|
||||
}
|
||||
lock (lockObj) {
|
||||
if (handle != IntPtr.Zero) {
|
||||
ApiNativeMethods.api_destroy_quickbus(handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,24 +2,48 @@
|
||||
namespace bts.api.core {
|
||||
using bts.api.user;
|
||||
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using Spark.Core.Services;
|
||||
using Spark.Core;
|
||||
using System.Threading;
|
||||
|
||||
public sealed class ServiceContext : Spark.Api.IServiceProvider, IDisposable {
|
||||
IntPtr _qbus;
|
||||
readonly object lockObj = new();
|
||||
LazyOnce<ManagedQuickbusWrapper>? quickbusBacking;
|
||||
bool isDisposed;
|
||||
IntPtr _qbus => quickbusBacking?.Value?.Handle ?? throw new ObjectDisposedException(nameof(ServiceContext));
|
||||
|
||||
AuthToken? _token;
|
||||
|
||||
public ServiceContext() {
|
||||
_qbus = ApiNativeMethods.api_create_quickbus(null, 0);
|
||||
public ServiceContext(ISparkConfigLoader configLoader) {
|
||||
quickbusBacking = new(QuickbusFactory, lockObj);
|
||||
|
||||
ManagedQuickbusWrapper QuickbusFactory() {
|
||||
if (isDisposed) {
|
||||
return ManagedQuickbusWrapper.None;
|
||||
}
|
||||
configLoader.InitializeAsync(CancellationToken.None).Wait();
|
||||
return new();
|
||||
}
|
||||
}
|
||||
|
||||
internal ServiceContext(IntPtr qbus) =>
|
||||
_qbus = qbus;
|
||||
internal ServiceContext(IntPtr qbus) {
|
||||
quickbusBacking = new(QuickbusFactory, lockObj);
|
||||
|
||||
ManagedQuickbusWrapper QuickbusFactory() {
|
||||
// This code is executed in a lock (since we passed 'lockObj' in to the constructor), so
|
||||
// no need to worry about concurrency when reading 'isDisposed'.
|
||||
Log.assert(!isDisposed);
|
||||
if (isDisposed) {
|
||||
|
||||
}
|
||||
return new(qbus);
|
||||
}
|
||||
}
|
||||
|
||||
public AuthTokenImmutable? token => _token?.immutable();
|
||||
public UserTuple? user { get; private set; }
|
||||
@@ -87,9 +111,25 @@ namespace bts.api.core {
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
if (_qbus != IntPtr.Zero) {
|
||||
ApiNativeMethods.api_destroy_quickbus(_qbus);
|
||||
_qbus = IntPtr.Zero;
|
||||
if (isDisposed) {
|
||||
return;
|
||||
}
|
||||
ManagedQuickbusWrapper? oldQuickbus;
|
||||
lock (lockObj) {
|
||||
if (isDisposed) {
|
||||
return;
|
||||
}
|
||||
isDisposed = true;
|
||||
if (quickbusBacking?.IsValueCreated ?? false) {
|
||||
// IMPORTANT: Don't access quickbusBacking.Value unless you are SURE that the value
|
||||
// has already been created (otherwise the factory function will deadlock, since it
|
||||
// also locks 'lockObj').
|
||||
oldQuickbus = quickbusBacking.Value;
|
||||
quickbusBacking.Value.Dispose();
|
||||
}
|
||||
// Set quickbusBacking to null to prevent the quickbus from being created after dispose
|
||||
// has been called (if it hasn't been created already).
|
||||
quickbusBacking = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,17 @@ namespace Spark.Core {
|
||||
/// </summary>
|
||||
public class LazyOnce<T> {
|
||||
readonly Func<T> _create;
|
||||
readonly object syncRoot;
|
||||
Optional<T> _value;
|
||||
|
||||
public LazyOnce(Func<T> create) =>
|
||||
public LazyOnce(Func<T> create)
|
||||
: this(create, new()) { }
|
||||
|
||||
public LazyOnce(Func<T> create, object syncRoot) {
|
||||
_create = create;
|
||||
ArgumentNullException.ThrowIfNull(syncRoot);
|
||||
this.syncRoot = syncRoot;
|
||||
}
|
||||
|
||||
public bool IsValueCreated => _value.has_value;
|
||||
|
||||
@@ -19,7 +26,7 @@ namespace Spark.Core {
|
||||
get {
|
||||
// check has_value outside of lock since, once set to true, it doesn't change
|
||||
if (!_value.has_value) {
|
||||
lock (_create) {
|
||||
lock (syncRoot) {
|
||||
// check has_value again (may have become true since first check)
|
||||
if (!_value.has_value) {
|
||||
_value = _create();
|
||||
|
||||
@@ -9,9 +9,12 @@ namespace mbts.config {
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public static class Configuration {
|
||||
static object _config_lock = new();
|
||||
static TaskCompletionSource<bool>? initTcs;
|
||||
|
||||
static State _state = State.Uninitialized;
|
||||
|
||||
@@ -50,19 +53,61 @@ namespace mbts.config {
|
||||
}
|
||||
}
|
||||
|
||||
public static void initialize(string? config_source = null) {
|
||||
if (_state == State.OK) {
|
||||
return;
|
||||
public static ValueTask<bool> InitializeAsync(string? configSource = null) =>
|
||||
InitializeAsync(configSource, CancellationToken.None);
|
||||
|
||||
public static ValueTask<bool> InitializeAsync(CancellationToken cancellationToken) =>
|
||||
InitializeAsync(null, cancellationToken);
|
||||
|
||||
public static ValueTask<bool> InitializeAsync(string? config_source, CancellationToken cancellationToken) {
|
||||
return _state switch {
|
||||
State.OK => ValueTask.FromResult(true),
|
||||
State.Error => ValueTask.FromResult(false),
|
||||
State.Uninitialized => Initialize(),
|
||||
_ => throw new InvalidOperationException(),
|
||||
};
|
||||
|
||||
ValueTask<bool> Initialize() {
|
||||
lock (_config_lock) {
|
||||
switch (_state) {
|
||||
case State.OK:
|
||||
return ValueTask.FromResult(true);
|
||||
case State.Error:
|
||||
return ValueTask.FromResult(false);
|
||||
case State.Uninitialized:
|
||||
if (initTcs is not null) {
|
||||
return new(initTcs.Task);
|
||||
}
|
||||
initTcs = new(cancellationToken);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
}
|
||||
// Set 'initTcs' to null at the end so subsequent calls to InitializeAsync re-run BTS.init,
|
||||
// rather than simply return the same completed task.
|
||||
// Note: if BTS.init is successful, it won't rerun (see the switch case above).
|
||||
var task = initTcs.Task;
|
||||
try {
|
||||
BTS.init(config_source);
|
||||
// Guarentee BTS.init runs BEFORE we signal initialization is complete (this code won't
|
||||
// run concurrently, so a full lock isn't necessary).
|
||||
Thread.MemoryBarrier();
|
||||
_state = State.OK;
|
||||
initTcs.SetResult(true);
|
||||
} catch (Exception ex) {
|
||||
if (ex is ApplicationException) {
|
||||
lock (_config_lock) {
|
||||
_state = State.Error;
|
||||
initTcs.SetException(ex);
|
||||
initTcs = null;
|
||||
}
|
||||
}
|
||||
return new(false);
|
||||
}
|
||||
initTcs = null;
|
||||
return new(task);
|
||||
}
|
||||
// Considered doing this async on a background thread but it wouldn't do any good. The next
|
||||
// guy down the line to ask for config will just block until this completes.
|
||||
try {
|
||||
BTS.init(config_source);
|
||||
} catch (ApplicationException) {
|
||||
_state = State.Error;
|
||||
throw;
|
||||
}
|
||||
_state = State.OK;
|
||||
}
|
||||
|
||||
public static void initialize_for_test(string config = "") {
|
||||
@@ -72,7 +117,7 @@ namespace mbts.config {
|
||||
_state = State.OK;
|
||||
}
|
||||
|
||||
public static unsafe bool try_initialize(out string error) {
|
||||
public static bool try_initialize(out string error) {
|
||||
_reset();
|
||||
try {
|
||||
BTS.init();
|
||||
@@ -103,12 +148,22 @@ namespace mbts.config {
|
||||
$"Failed to deserialize config '{key}' as {type}: {error}";
|
||||
|
||||
static byte[]? _get_buffer(string key_name) {
|
||||
switch (_state) {
|
||||
case State.Uninitialized:
|
||||
if (!InitializeAsync().GetAwaiter().GetResult()) {
|
||||
return null;
|
||||
}
|
||||
break;
|
||||
case State.Error:
|
||||
return null;
|
||||
case State.OK:
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException($"Unexpected state: {_state}");
|
||||
}
|
||||
/// The native get_buffer (<see cref="_raw_get_buffer(string, ref int)"/>) is not thread
|
||||
/// safe, so this call must be protected from re-entrancy.
|
||||
lock (_config_lock) {
|
||||
if (_state == State.Uninitialized) { initialize(); }
|
||||
if (_state == State.Error) { return null; }
|
||||
|
||||
int length = 0;
|
||||
byte[] buffer;
|
||||
IntPtr pbuffer = _raw_get_buffer(key_name, ref length);
|
||||
|
||||
Reference in new issue
Block a user