Files
spark/src/client/spark_core/config/Configuration.cs
T

192 lines
6.2 KiB
C#

#nullable enable
namespace mbts.config {
using bts;
using Google.Protobuf;
using System;
using System.Diagnostics.Contracts;
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;
enum State {
Uninitialized,
Error,
OK
}
public static T get<T>() where T : new() =>
get<T>(_default_type_key<T>());
public static T get<T>(string key) where T : new() {
var buffer = _get_buffer(key);
// Default only protobufs serialize to no bytes
if (buffer is null) {
return new();
}
using var ms = new MemoryStream(buffer);
try {
return typeof(IMessage).IsAssignableFrom(typeof(T)) ? proto3_impl() : proto2_impl();
} catch (Exception ex) {
Log.assert(false, _fmt_deserialization_error(typeof(T), key, ex));
}
return new();
T proto2_impl() =>
ProtoBuf.Serializer.Deserialize<T>(ms);
T proto3_impl() {
var rv = new T();
((IMessage)rv).MergeFrom(ms);
return rv;
}
}
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);
}
}
public static void initialize_for_test(string config = "") {
_raw_initialize_for_test(config);
// still need init_spark_lib
BTS.init();
_state = State.OK;
}
public static bool try_initialize(out string error) {
_reset();
try {
BTS.init();
} catch (ApplicationException e) {
error = e.Message;
return false;
}
error = string.Empty;
return true;
}
[DllImport("libspark")]
internal static extern int run_config_query(
string[] keysv,
int keysc,
string[] excluded_keysv,
int excluded_keysc,
bool all,
bool list_keys,
bool verbose);
[Pure]
static string _default_type_key<T>() =>
typeof(T).FullName ?? throw new InvalidOperationException();
[Pure]
static string _fmt_deserialization_error(Type type, string key, Exception error) =>
$"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) {
int length = 0;
byte[] buffer;
IntPtr pbuffer = _raw_get_buffer(key_name, ref length);
if (length > 0) {
buffer = new byte[length];
Marshal.Copy(pbuffer, buffer, 0, length);
return buffer;
}
return null;
}
}
[DllImport("libspark", EntryPoint = "get_buffer")]
static extern IntPtr _raw_get_buffer(string key_name, ref int length);
[DllImport("libspark", EntryPoint = "initialize_nothrow")]
static extern bool _initialize_nothrow(StringBuilder buffer, int length);
[DllImport("libspark", EntryPoint = "initialize_for_test")]
static extern void _raw_initialize_for_test(string buffer);
[DllImport("libspark", EntryPoint = "reset")]
static extern void _reset();
}
}