mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: let native code own function callback handles
The SQLite facade freed every GC handle behind its scalar, aggregate, and collation registrations as soon as the connection closed, while the native side could still reach those handles through statements that had not been finalized. A freed handle slot gets reused by the next registration, which is how LocalDatabaseKeepsSqliteHelpersAndTursoHistoryRepository fails intermittently with "Unable to cast object of type 'AggregateFunctionRegistration' to type 'ScalarFunctionRegistration'". Free each handle from the context destructor that core invokes when a registration is dropped instead. The handle then lives exactly as long as native code can call it, and the per-connection handle list and its eager cleanup go away. Callbacks now check the context type and report what they received, so a future mismatch names the problem instead of surfacing as a cast failure. Tests: bindings/dotnet Turso.Tests in CI
This commit is contained in:
@@ -31,14 +31,14 @@ public partial class SqliteConnection
|
||||
if (HasNativeCallbackHandle)
|
||||
{
|
||||
using var syncOperation = _managedConnection?.EnterSyncOperation();
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterAggregateFunctions()
|
||||
{
|
||||
foreach (var registration in _aggregateFunctions.Values)
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
|
||||
private static object? InvokeNullableAggregateStep<TAccumulate>(Func<TAccumulate?, TAccumulate> function, object? accumulator, object?[] args)
|
||||
@@ -67,8 +67,7 @@ public partial class SqliteConnection
|
||||
|
||||
private static IntPtr InitializeAggregate(IntPtr context)
|
||||
{
|
||||
var registration = (AggregateFunctionRegistration?)GCHandle.FromIntPtr(context).Target
|
||||
?? throw new ObjectDisposedException(nameof(AggregateFunctionRegistration));
|
||||
var registration = ResolveCallbackContext<AggregateFunctionRegistration>(context);
|
||||
return registration.CreateInvocationHandle();
|
||||
}
|
||||
|
||||
@@ -76,8 +75,7 @@ public partial class SqliteConnection
|
||||
{
|
||||
try
|
||||
{
|
||||
var invocation = (AggregateInvocation?)GCHandle.FromIntPtr(aggregateContext).Target
|
||||
?? throw new ObjectDisposedException(nameof(AggregateInvocation));
|
||||
var invocation = ResolveCallbackContext<AggregateInvocation>(aggregateContext);
|
||||
invocation.Step(ReadArguments(argc, argv));
|
||||
return CreateResult(null);
|
||||
}
|
||||
@@ -95,8 +93,7 @@ public partial class SqliteConnection
|
||||
{
|
||||
try
|
||||
{
|
||||
var invocation = (AggregateInvocation?)GCHandle.FromIntPtr(aggregateContext).Target
|
||||
?? throw new ObjectDisposedException(nameof(AggregateInvocation));
|
||||
var invocation = ResolveCallbackContext<AggregateInvocation>(aggregateContext);
|
||||
return CreateResult(invocation.FinalizeResult());
|
||||
}
|
||||
catch (SqliteException ex)
|
||||
@@ -167,7 +164,7 @@ public partial class SqliteConnection
|
||||
}
|
||||
}
|
||||
|
||||
public GCHandle Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
public void Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
{
|
||||
var handle = GCHandle.Alloc(this);
|
||||
try
|
||||
@@ -184,7 +181,6 @@ public partial class SqliteConnection
|
||||
ContextDestructorCallback,
|
||||
AggregateDestructorCallback,
|
||||
ValueDestructorCallback);
|
||||
return handle;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -29,20 +29,19 @@ public partial class SqliteConnection
|
||||
if (HasNativeCallbackHandle)
|
||||
{
|
||||
using var syncOperation = _managedConnection?.EnterSyncOperation();
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterCollations()
|
||||
{
|
||||
foreach (var registration in _collations.Values)
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
|
||||
private static int InvokeCollation(IntPtr context, IntPtr leftPtr, UIntPtr leftLen, IntPtr rightPtr, UIntPtr rightLen)
|
||||
{
|
||||
var registration = (CollationRegistration?)GCHandle.FromIntPtr(context).Target
|
||||
?? throw new ObjectDisposedException(nameof(CollationRegistration));
|
||||
var registration = ResolveCallbackContext<CollationRegistration>(context);
|
||||
return registration.Compare(ReadUtf8(leftPtr, checked((int)leftLen)), ReadUtf8(rightPtr, checked((int)rightLen)));
|
||||
}
|
||||
|
||||
@@ -60,7 +59,7 @@ public partial class SqliteConnection
|
||||
{
|
||||
public int Compare(string left, string right) => compare(left, right);
|
||||
|
||||
public GCHandle Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
public void Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
{
|
||||
var handle = GCHandle.Alloc(this);
|
||||
try
|
||||
@@ -71,7 +70,6 @@ public partial class SqliteConnection
|
||||
GCHandle.ToIntPtr(handle),
|
||||
CollationCallback,
|
||||
ContextDestructorCallback);
|
||||
return handle;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -8,10 +8,9 @@ namespace Turso.Data.Sqlite;
|
||||
public partial class SqliteConnection
|
||||
{
|
||||
private static readonly TursoScalarFunctionCallback ScalarFunctionCallback = InvokeScalarFunction;
|
||||
private static readonly TursoContextDestructorCallback ContextDestructorCallback = NoopContextDestructor;
|
||||
private static readonly TursoContextDestructorCallback ContextDestructorCallback = FreeCallbackContext;
|
||||
private static readonly TursoValueDestructorCallback ValueDestructorCallback = DestroyFunctionValue;
|
||||
private readonly Dictionary<string, ScalarFunctionRegistration> _scalarFunctions = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<GCHandle> _nativeFunctionContexts = [];
|
||||
|
||||
private void RegisterScalarFunction(string name, int argc, bool isDeterministic, Func<object?[], object?>? function)
|
||||
{
|
||||
@@ -33,27 +32,14 @@ public partial class SqliteConnection
|
||||
if (HasNativeCallbackHandle)
|
||||
{
|
||||
using var syncOperation = _managedConnection?.EnterSyncOperation();
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterScalarFunctions()
|
||||
{
|
||||
foreach (var registration in _scalarFunctions.Values)
|
||||
_nativeFunctionContexts.Add(registration.Register(DatabaseHandle));
|
||||
}
|
||||
|
||||
private void FreeNativeFunctionContexts()
|
||||
{
|
||||
foreach (var handle in _nativeFunctionContexts)
|
||||
{
|
||||
if (handle.Target is AggregateFunctionRegistration aggregate)
|
||||
aggregate.FreeInvocations();
|
||||
if (handle.IsAllocated)
|
||||
handle.Free();
|
||||
}
|
||||
|
||||
_nativeFunctionContexts.Clear();
|
||||
registration.Register(DatabaseHandle);
|
||||
}
|
||||
|
||||
private static object? InvokeTypedFunction<T1, TResult>(string name, Func<T1, TResult> function, object?[] args)
|
||||
@@ -98,8 +84,7 @@ public partial class SqliteConnection
|
||||
{
|
||||
try
|
||||
{
|
||||
var registration = (ScalarFunctionRegistration?)GCHandle.FromIntPtr(context).Target
|
||||
?? throw new ObjectDisposedException(nameof(ScalarFunctionRegistration));
|
||||
var registration = ResolveCallbackContext<ScalarFunctionRegistration>(context);
|
||||
var args = ReadArguments(argc, argv);
|
||||
return CreateResult(registration.Invoke(args));
|
||||
}
|
||||
@@ -113,8 +98,24 @@ public partial class SqliteConnection
|
||||
}
|
||||
}
|
||||
|
||||
private static void NoopContextDestructor(IntPtr context)
|
||||
private static T ResolveCallbackContext<T>(IntPtr context) where T : class
|
||||
{
|
||||
var target = GCHandle.FromIntPtr(context).Target
|
||||
?? throw new ObjectDisposedException(typeof(T).Name);
|
||||
return target as T
|
||||
?? throw new InvalidOperationException(
|
||||
$"Native callback expected a {typeof(T).Name} context but received a {target.GetType().Name}.");
|
||||
}
|
||||
|
||||
private static void FreeCallbackContext(IntPtr context)
|
||||
{
|
||||
if (context == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
var handle = GCHandle.FromIntPtr(context);
|
||||
if (handle.Target is AggregateFunctionRegistration aggregate)
|
||||
aggregate.FreeInvocations();
|
||||
handle.Free();
|
||||
}
|
||||
|
||||
private static void DestroyFunctionValue(IntPtr result)
|
||||
@@ -295,7 +296,7 @@ public partial class SqliteConnection
|
||||
{
|
||||
public object? Invoke(object?[] args) => invoke(args);
|
||||
|
||||
public GCHandle Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
public void Register(Turso.Raw.Public.Handles.TursoDatabaseHandle database)
|
||||
{
|
||||
var handle = GCHandle.Alloc(this);
|
||||
try
|
||||
@@ -309,7 +310,6 @@ public partial class SqliteConnection
|
||||
ScalarFunctionCallback,
|
||||
ContextDestructorCallback,
|
||||
ValueDestructorCallback);
|
||||
return handle;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -224,7 +224,6 @@ public partial class SqliteConnection : DbConnection
|
||||
}
|
||||
}
|
||||
|
||||
FreeNativeFunctionContexts();
|
||||
_managedConnection.Close();
|
||||
}
|
||||
finally
|
||||
@@ -242,7 +241,6 @@ public partial class SqliteConnection : DbConnection
|
||||
var originalState = State;
|
||||
_database.Dispose();
|
||||
_database = null;
|
||||
FreeNativeFunctionContexts();
|
||||
_dataSource = null;
|
||||
_readOnly = false;
|
||||
_recursiveTriggers = false;
|
||||
@@ -544,7 +542,6 @@ public partial class SqliteConnection : DbConnection
|
||||
var originalState = State;
|
||||
try
|
||||
{
|
||||
FreeNativeFunctionContexts();
|
||||
_managedConnection.Dispose();
|
||||
}
|
||||
catch (Exception exception) when (failure is not null)
|
||||
@@ -603,7 +600,6 @@ public partial class SqliteConnection : DbConnection
|
||||
var originalState = State;
|
||||
try
|
||||
{
|
||||
FreeNativeFunctionContexts();
|
||||
await ManagedConnection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception) when (failure is not null)
|
||||
@@ -907,7 +903,6 @@ public partial class SqliteConnection : DbConnection
|
||||
{
|
||||
_database?.Dispose();
|
||||
_database = null;
|
||||
FreeNativeFunctionContexts();
|
||||
_dataSource = null;
|
||||
_readOnly = false;
|
||||
_sharedMemoryPath = null;
|
||||
|
||||
Reference in New Issue
Block a user