From 1e9754dcb2fbd5beaa76346382f9347d74ceea1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Moreau?= Date: Mon, 13 Jul 2026 11:05:38 -0400 Subject: [PATCH 1/2] bindings/dotnet: add HTTP client packages Add managed clients for the Turso Platform API and serverless SQL-over-HTTP workloads. Generate the Platform client during MSBuild from the pinned OpenAPI specification, keep generated artifacts out of version control, and use cross-platform generation paths. Include package metadata, NuGet publishing integration, and regression coverage for Platform extensions plus Serverless transaction and lifecycle behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/dotnet-publish.yml | 2 + bindings/dotnet/.gitignore | 6 +- bindings/dotnet/Makefile | 8 + bindings/dotnet/Turso.slnx | 2 + .../src/Turso.Platform.Client/README.md | 57 + .../Turso.Platform.Client.csproj | 56 + .../TursoPlatformClient.Supplement.cs | 53 + .../src/Turso.Platform.Client/nswag.json | 95 + .../src/Turso.Platform.Client/openapi.json | 3387 +++++++++++++++++ .../tools/OpenApiTitler/OpenApiTitler.csproj | 11 + .../tools/OpenApiTitler/Program.cs | 217 ++ .../src/Turso.Serverless.Client/HranaHttp.cs | 152 + .../Turso.Serverless.Client/HranaProtocol.cs | 370 ++ .../src/Turso.Serverless.Client/README.md | 66 + .../src/Turso.Serverless.Client/SqlArgs.cs | 24 + .../Turso.Serverless.Client.csproj | 27 + .../Turso.Serverless.Client/TursoResultSet.cs | 161 + .../TursoServerlessConnection.cs | 238 ++ .../TursoServerlessException.cs | 28 + .../Turso.Serverless.Client/TursoSession.cs | 474 +++ .../dotnet/src/Turso.Tests/Turso.Tests.csproj | 2 + .../Turso.Tests/TursoPlatformClientTests.cs | 42 + .../Turso.Tests/TursoServerlessClientTests.cs | 149 + 23 files changed, 5626 insertions(+), 1 deletion(-) create mode 100644 bindings/dotnet/src/Turso.Platform.Client/README.md create mode 100644 bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj create mode 100644 bindings/dotnet/src/Turso.Platform.Client/TursoPlatformClient.Supplement.cs create mode 100644 bindings/dotnet/src/Turso.Platform.Client/nswag.json create mode 100644 bindings/dotnet/src/Turso.Platform.Client/openapi.json create mode 100644 bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/OpenApiTitler.csproj create mode 100644 bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/Program.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/HranaHttp.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/HranaProtocol.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/README.md create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/SqlArgs.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/Turso.Serverless.Client.csproj create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/TursoResultSet.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessConnection.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessException.cs create mode 100644 bindings/dotnet/src/Turso.Serverless.Client/TursoSession.cs create mode 100644 bindings/dotnet/src/Turso.Tests/TursoPlatformClientTests.cs create mode 100644 bindings/dotnet/src/Turso.Tests/TursoServerlessClientTests.cs diff --git a/.github/workflows/dotnet-publish.yml b/.github/workflows/dotnet-publish.yml index 6b624dfe0..3367bca65 100644 --- a/.github/workflows/dotnet-publish.yml +++ b/.github/workflows/dotnet-publish.yml @@ -429,6 +429,8 @@ jobs: files=( src/Turso.Data.Sqlite/bin/Release/Turso.Data.Sqlite.*.nupkg src/Turso.Data.Sqlite.NativeAot/bin/Release/Turso.Data.Sqlite.NativeAot.*.nupkg + src/Turso.Platform.Client/bin/Release/Turso.Platform.Client.*.nupkg + src/Turso.Serverless.Client/bin/Release/Turso.Serverless.Client.*.nupkg ) if [ ${#files[@]} -eq 0 ]; then echo "No NuGet packages found to upload" diff --git a/bindings/dotnet/.gitignore b/bindings/dotnet/.gitignore index a3868f078..fbf11d8b1 100644 --- a/bindings/dotnet/.gitignore +++ b/bindings/dotnet/.gitignore @@ -484,4 +484,8 @@ $RECYCLE.BIN/ *.swp src/Turso.Native/* -rs_compiled/* \ No newline at end of file +rs_compiled/* + +# Derived from Turso.Platform.Client/openapi.json during MSBuild compilation. +src/Turso.Platform.Client/TursoPlatformClient.generated.cs +src/Turso.Platform.Client/openapi.transformed.json \ No newline at end of file diff --git a/bindings/dotnet/Makefile b/bindings/dotnet/Makefile index e5558f717..a0474b8ff 100644 --- a/bindings/dotnet/Makefile +++ b/bindings/dotnet/Makefile @@ -109,6 +109,12 @@ build-dotnet: dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Data/Turso.Data.csproj dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Data.Sqlite/Turso.Data.Sqlite.csproj dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.EntityFrameworkCore.Sqlite/Turso.EntityFrameworkCore.Sqlite.csproj + dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Platform.Client/Turso.Platform.Client.csproj + dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Serverless.Client/Turso.Serverless.Client.csproj + +# Generate the Turso Platform API client from the pinned OpenAPI spec. +generate-platform-client: + dotnet build ./src/Turso.Platform.Client/Turso.Platform.Client.csproj build: build-rust build-dotnet @@ -133,3 +139,5 @@ pack: dotnet pack -c Release ./src/Turso.Data.Sqlite/Turso.Data.Sqlite.csproj dotnet pack -c Release ./src/Turso.EntityFrameworkCore.Sqlite/Turso.EntityFrameworkCore.Sqlite.csproj $(MAKE) pack-nativeaot-static + dotnet pack -c Release ./src/Turso.Platform.Client/Turso.Platform.Client.csproj + dotnet pack -c Release ./src/Turso.Serverless.Client/Turso.Serverless.Client.csproj diff --git a/bindings/dotnet/Turso.slnx b/bindings/dotnet/Turso.slnx index f808ab114..8ac616c9a 100644 --- a/bindings/dotnet/Turso.slnx +++ b/bindings/dotnet/Turso.slnx @@ -19,5 +19,7 @@ + + diff --git a/bindings/dotnet/src/Turso.Platform.Client/README.md b/bindings/dotnet/src/Turso.Platform.Client/README.md new file mode 100644 index 000000000..ca82991ef --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/README.md @@ -0,0 +1,57 @@ +# Turso.Platform.Client + +.NET client for the [Turso Platform API](https://docs.turso.tech/api-reference/introduction) (`https://api.turso.tech`): manage databases, groups, auth tokens, organizations, members and invites. + +Unlike the `Turso` and `Turso.Data.Sqlite` packages, this is a pure managed HTTP client — it has no native component. + +## Getting started + +```C# +using Turso.Platform.Client; + +var httpClient = new HttpClient(); +httpClient.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", platformApiToken); + +var client = new TursoPlatformClient(httpClient); + +// Create a database +var created = await client.CreateDatabaseAsync(organizationSlug, new CreateDatabaseInput +{ + Name = "my-database", + Group = "default", +}); + +// Mint a database auth token +var token = await client.CreateDatabaseTokenAsync(organizationSlug, "my-database"); + +// List databases +var databases = await client.ListDatabasesAsync(organizationSlug); +``` + +The client is generated with [NSwag](https://github.com/RicoSuter/NSwag) from the official OpenAPI specification published in [tursodatabase/turso-docs](https://github.com/tursodatabase/turso-docs) (`api-reference/openapi.json`). + +## Regenerating the client + +The pinned upstream spec lives at `openapi.json` next to this file and is kept byte-identical to +the published one. Because the spec leaves its request/response schemas anonymous, NSwag would +generate counter names (`Response17`, `Body3`); the `tools/OpenApiTitler` project first derives +proper names from each `operationId` (`ListDatabasesResponse`, `CreateGroupRequest`) and collapses +the repeated `{ error: string }` payloads into one shared `ErrorResponse`. + +Every `dotnet build`, test, or pack generates the transformed document and C# client under the +project's ignored `obj` directory. The build uses the version-pinned `NSwag.MSBuild` package, so it +does not require a globally installed NSwag CLI. + +To refresh the tracked spec and regenerate during the next build: + +```bash +curl -sL https://raw.githubusercontent.com/tursodatabase/turso-docs/main/api-reference/openapi.json -o openapi.json +dotnet build +``` + +(or `make generate-platform-client` from `bindings/dotnet`). + +`TursoPlatformClient.Supplement.cs` contains the hand-written `Extensions` union NSwag cannot generate. Use `Extensions.All` to enable every extension or `Extensions.FromNames(...)` for an explicit list. + +Spec pinned from turso-docs commit `ac44bfab64a7` (2026-06-08). diff --git a/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj b/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj new file mode 100644 index 000000000..93de72e45 --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj @@ -0,0 +1,56 @@ + + + + Library + $(TursoTargetFrameworks) + enable + enable + Turso.Platform.Client + + Turso.Platform.Client + Turso Platform API Client + HTTP client for the Turso Platform API (api.turso.tech): manage databases, groups, auth tokens, organizations and members. Generated from the official OpenAPI specification. + Turso authors + turso;database;platform;api;client + MIT + https://github.com/tursodatabase/turso + https://github.com/tursodatabase/turso + git + README.md + true + $(NoWarn);1591 + + $(MSBuildProjectDirectory)/obj/$(TargetFramework)/openapi.transformed.json + $(MSBuildProjectDirectory)/obj/$(TargetFramework)/TursoPlatformClient.generated.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bindings/dotnet/src/Turso.Platform.Client/TursoPlatformClient.Supplement.cs b/bindings/dotnet/src/Turso.Platform.Client/TursoPlatformClient.Supplement.cs new file mode 100644 index 000000000..9c4f39cf0 --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/TursoPlatformClient.Supplement.cs @@ -0,0 +1,53 @@ +namespace Turso.Platform.Client; + +/// +/// The group-extension union from the Platform API. It is serialized as either the string +/// "all" or an array of extension names. +/// +[System.Text.Json.Serialization.JsonConverter(typeof(ExtensionsJsonConverter))] +public partial class Extensions +{ + private Extensions(IReadOnlyList? names) + { + Names = names; + } + + /// Enables all extensions available to the group. + public static Extensions All { get; } = new(null); + + /// Enables only the supplied extension names. + public static Extensions FromNames(IEnumerable names) + { + ArgumentNullException.ThrowIfNull(names); + return new Extensions(names.ToArray()); + } + + /// The explicitly enabled extension names, or for . + public IReadOnlyList? Names { get; } +} + +internal sealed class ExtensionsJsonConverter : System.Text.Json.Serialization.JsonConverter +{ + public override Extensions Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) + { + return reader.TokenType switch + { + System.Text.Json.JsonTokenType.String when reader.GetString() == "all" => Extensions.All, + System.Text.Json.JsonTokenType.StartArray => Extensions.FromNames( + System.Text.Json.JsonSerializer.Deserialize(ref reader, options) + ?? throw new System.Text.Json.JsonException("Extensions array cannot be null.")), + _ => throw new System.Text.Json.JsonException("Extensions must be \"all\" or an array of extension names."), + }; + } + + public override void Write(System.Text.Json.Utf8JsonWriter writer, Extensions value, System.Text.Json.JsonSerializerOptions options) + { + if (value.Names is null) + { + writer.WriteStringValue("all"); + return; + } + + System.Text.Json.JsonSerializer.Serialize(writer, value.Names, options); + } +} diff --git a/bindings/dotnet/src/Turso.Platform.Client/nswag.json b/bindings/dotnet/src/Turso.Platform.Client/nswag.json new file mode 100644 index 000000000..474f6f08c --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/nswag.json @@ -0,0 +1,95 @@ +{ + "runtime": "Net90", + "defaultVariables": null, + "documentGenerator": { + "fromDocument": { + "json": null, + "url": "$(OpenApiDocument)", + "output": null, + "newLineBehavior": "Auto" + } + }, + "codeGenerators": { + "openApiToCSharpClient": { + "clientBaseClass": null, + "configurationClass": null, + "generateClientClasses": true, + "generateClientInterfaces": true, + "clientBaseInterface": null, + "injectHttpClient": true, + "disposeHttpClient": false, + "protectedMethods": [], + "generateExceptionClasses": true, + "exceptionClass": "TursoPlatformApiException", + "wrapDtoExceptions": true, + "useHttpClientCreationMethod": false, + "httpClientType": "System.Net.Http.HttpClient", + "useHttpRequestMessageCreationMethod": false, + "useBaseUrl": true, + "generateBaseUrlProperty": true, + "generateSyncMethods": false, + "generatePrepareRequestAndProcessResponseAsAsyncMethods": false, + "exposeJsonSerializerSettings": false, + "clientClassAccessModifier": "public", + "typeAccessModifier": "public", + "generateContractsOutput": false, + "parameterDateTimeFormat": "s", + "parameterDateFormat": "yyyy-MM-dd", + "generateUpdateJsonSerializerSettingsMethod": true, + "useRequestAndResponseSerializationSettings": false, + "serializeTypeInformation": false, + "queryNullValue": "", + "className": "TursoPlatformClient", + "operationGenerationMode": "SingleClientFromOperationId", + "additionalNamespaceUsages": [], + "additionalContractNamespaceUsages": [], + "generateOptionalParameters": true, + "generateJsonMethods": false, + "enforceFlagEnums": false, + "parameterArrayType": "System.Collections.Generic.IEnumerable", + "parameterDictionaryType": "System.Collections.Generic.IDictionary", + "responseArrayType": "System.Collections.Generic.ICollection", + "responseDictionaryType": "System.Collections.Generic.IDictionary", + "wrapResponses": false, + "wrapResponseMethods": [], + "generateResponseClasses": true, + "responseClass": "SwaggerResponse", + "namespace": "Turso.Platform.Client", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTimeOffset", + "jsonConverters": null, + "anyType": "object", + "dateTimeType": "System.DateTimeOffset", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "arrayType": "System.Collections.Generic.ICollection", + "arrayInstanceType": "System.Collections.ObjectModel.Collection", + "dictionaryType": "System.Collections.Generic.IDictionary", + "dictionaryInstanceType": "System.Collections.Generic.Dictionary", + "arrayBaseType": "System.Collections.ObjectModel.Collection", + "dictionaryBaseType": "System.Collections.Generic.Dictionary", + "classStyle": "Poco", + "jsonLibrary": "SystemTextJson", + "generateDefaultValues": true, + "generateDataAnnotations": true, + "excludedTypeNames": [], + "excludedParameterNames": [], + "handleReferences": false, + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "jsonSerializerSettingsTransformationMethod": null, + "inlineNamedArrays": false, + "inlineNamedDictionaries": false, + "inlineNamedTuples": true, + "inlineNamedAny": false, + "generateDtoTypes": true, + "generateOptionalPropertiesAsNullable": true, + "generateNullableReferenceTypes": true, + "templateDirectory": null, + "serviceHost": null, + "serviceSchemes": null, + "output": "$(GeneratedClientSource)", + "newLineBehavior": "Auto" + } + } +} diff --git a/bindings/dotnet/src/Turso.Platform.Client/openapi.json b/bindings/dotnet/src/Turso.Platform.Client/openapi.json new file mode 100644 index 000000000..a240e9fd1 --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/openapi.json @@ -0,0 +1,3387 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Turso Platform API", + "description": "API description here", + "license": { + "name": "MIT" + }, + "version": "0.1.0" + }, + "servers": [ + { + "url": "https://api.turso.tech", + "description": "Turso's Platform API" + } + ], + "paths": { + "/v1/organizations/{organizationSlug}/databases": { + "get": { + "summary": "List Databases", + "description": "Returns a list of databases belonging to the organization or user.", + "operationId": "listDatabases", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "name": "group", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Filter databases by group name." + }, + { + "name": "schema", + "in": "query", + "schema": { + "type": "string" + }, + "description": "The schema database name that can be used to get databases that belong to that parent schema.", + "deprecated": true + }, + { + "name": "parent", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Filter database branches by using their parent database ID." + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "databases": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Database" + } + } + } + } + } + } + } + } + }, + "post": { + "summary": "Create Database", + "description": "Creates a new database in a group for the organization or user.", + "operationId": "createDatabase", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "requestBody": { + "description": "Database data to create a new database", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateDatabaseInput" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "database": { + "$ref": "#/components/schemas/CreateDatabaseOutput", + "description": "The newly created database" + } + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "group not found" + } + } + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "database with name [databaseName] already exists" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}": { + "get": { + "summary": "Retrieve Database", + "description": "Returns a database belonging to the organization or user.", + "operationId": "getDatabase", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "database": { + "$ref": "#/components/schemas/Database" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + }, + "delete": { + "summary": "Delete Database", + "description": "Delete a database belonging to the organization or user.", + "operationId": "deleteDatabase", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "database": { + "type": "string", + "description": "The name of the database that was deleted.", + "example": "my-db" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/configuration": { + "get": { + "summary": "Retrieve Database Configuration", + "description": "Retrieve an individual database configuration belonging to the organization or user.", + "operationId": "getDatabaseConfiguration", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DatabaseConfigurationResponse" + } + } + } + } + } + }, + "patch": { + "summary": "Update Database Configuration", + "description": "Update a database configuration belonging to the organization or user.", + "operationId": "updateDatabaseConfiguration", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "requestBody": { + "description": "The configuration to be applied to the chosen database.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DatabaseConfigurationInput" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DatabaseConfigurationResponse" + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/instances": { + "get": { + "summary": "List Database Instances", + "description": "Returns a list of instances of a database. Instances are the individual primary or replica databases in each region defined by the group.", + "operationId": "listDatabaseInstances", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "instances": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Instance" + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/instances/{instanceName}": { + "get": { + "summary": "Retrieve Database Instance", + "description": "Return the individual database instance by name.", + "operationId": "getDatabaseInstance", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + }, + { + "$ref": "#/components/parameters/instanceName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "instance": { + "$ref": "#/components/schemas/Instance" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/auth/tokens": { + "post": { + "summary": "Generate Database Auth Token", + "description": "Generates an authorization token for the specified database.", + "operationId": "createDatabaseToken", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + }, + { + "name": "expiration", + "in": "query", + "schema": { + "type": "string", + "default": "never" + }, + "description": "Expiration time for the token (e.g., 2w1d30m)." + }, + { + "name": "authorization", + "in": "query", + "schema": { + "type": "string", + "default": "full-access", + "enum": [ + "full-access", + "read-only" + ] + }, + "description": "Authorization level for the token (full-access or read-only)." + } + ], + "requestBody": { + "description": "Additional context such as claims required for the token.", + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTokenInput" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "jwt": { + "type": "string", + "description": "The generated authorization token (JWT)." + } + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "Invalid expiration format" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/usage": { + "get": { + "summary": "Retrieve Database Usage", + "description": "Fetch activity usage for a database in a given time period.", + "operationId": "getDatabaseUsage", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + }, + { + "name": "from", + "in": "query", + "schema": { + "type": "string", + "format": "date-time" + }, + "description": "The datetime to retrieve usage **from** in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Defaults to the current calendar month if not provided. Example: `2023-01-01T00:00:00Z`" + }, + { + "name": "to", + "in": "query", + "schema": { + "type": "string", + "format": "date-time" + }, + "description": "The datetime to retrieve usage **to** in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Defaults to the current calendar month if not provided. Example: `2023-02-01T00:00:00Z`" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "database": { + "type": "object", + "description": "The database usage object, containg the total and individual instance usage for rows read and written, as well as the total storage size (in bytes).", + "$ref": "#/components/schemas/DatabaseUsageOutput" + } + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "invalid from parameter: parsing time \"2023-12-12T00:00:00\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \"\" as \"Z07:00\"" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/stats": { + "get": { + "summary": "Retrieve Database Stats", + "description": "Fetch the top queries of a database, including the count of rows read and written.", + "operationId": "getDatabaseStats", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "top_queries": { + "type": "array", + "description": "The top queries performed on the given database as well as the total rows read and written.", + "nullable": true, + "items": { + "$ref": "#/components/schemas/DatabaseStatsOutput" + } + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/databases/{databaseName}/auth/rotate": { + "post": { + "summary": "Invalidate All Database Auth Tokens", + "description": "Invalidates all authorization tokens for the specified database.", + "operationId": "invalidateDatabaseTokens", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/databaseName" + } + ], + "responses": { + "200": { + "description": "Successful response (No Content)" + }, + "404": { + "$ref": "#/components/responses/DatabaseNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups": { + "get": { + "summary": "List Groups", + "description": "Returns a list of groups belonging to the organization or user.", + "operationId": "listGroups", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Group" + } + } + } + } + } + } + } + } + }, + "post": { + "summary": "Create Group", + "description": "Creates a new group for the organization or user.", + "operationId": "createGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "requestBody": { + "description": "Group data to create a new group", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewGroup" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group", + "description": "The newly created group" + } + } + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "group already exists" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}": { + "get": { + "summary": "Retrieve Group", + "description": "Returns a group belonging to the organization or user.", + "operationId": "getGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + }, + "delete": { + "summary": "Delete Group", + "description": "Delete a group belonging to the organization or user.", + "operationId": "deleteGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/configuration": { + "get": { + "summary": "Retrieve Group Configuration", + "description": "Retrieve an individual group configuration belonging to the organization or user.", + "operationId": "getGroupConfiguration", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupConfigurationResponse" + } + } + } + } + } + }, + "patch": { + "summary": "Update Group Configuration", + "description": "Update a group configuration belonging to the organization or user.", + "operationId": "updateGroupConfiguration", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "requestBody": { + "description": "The configuration to be applied to the chosen group.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupConfigurationInput" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupConfigurationResponse" + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/transfer": { + "post": { + "summary": "Transfer Group", + "description": "Transfer a group to another organization that you own or a member of.", + "operationId": "transferGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "requestBody": { + "description": "Receiving Organization details.", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The slug of the organization to transfer the group to." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Group" + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/unarchive": { + "post": { + "summary": "Unarchive Group", + "description": "Unarchive a group that has been archived due to inactivity.", + "operationId": "unarchiveGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group", + "description": "The group that was unarchived" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/locations/{location}": { + "post": { + "summary": "Add Location to Group", + "description": "Adds a location to the specified group.", + "operationId": "addLocationToGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + }, + { + "name": "location", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The location code to add to the group.", + "example": "aws-us-east-1" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group", + "description": "The group with the added location" + } + } + }, + "example": { + "group": { + "archived": false, + "locations": [ + "aws-us-east-1", + "aws-eu-west-1" + ], + "name": "default", + "primary": "aws-us-east-1", + "uuid": "f1dec998-8f7f-11ee-907d-a2a821fd08b9" + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "invalid location: amss" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + }, + "delete": { + "summary": "Remove Location from Group", + "description": "Removes a location from the specified group.", + "operationId": "removeLocationFromGroup", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + }, + { + "name": "location", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The location code to remove from the group." + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/Group", + "description": "The group with the removed location" + } + } + }, + "example": { + "group": { + "archived": false, + "locations": [ + "aws-us-east-1", + "aws-eu-west-1" + ], + "name": "default", + "primary": "aws-us-east-1", + "uuid": "f1dec998-8f7f-11ee-907d-a2a821fd08b9" + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "Invalid location code" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/update": { + "post": { + "summary": "Update Databases in a Group", + "description": "Updates all databases in the group to the latest libSQL version.", + "operationId": "updateGroupDatabases", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response (No Content)" + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/auth/tokens": { + "post": { + "summary": "Create Group Auth Token", + "description": "Generates an authorization token for the specified group.", + "operationId": "createGroupToken", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + }, + { + "name": "expiration", + "in": "query", + "schema": { + "type": "string", + "default": "never" + }, + "description": "Expiration time for the token (e.g., 2w1d30m)." + }, + { + "name": "authorization", + "in": "query", + "schema": { + "type": "string", + "default": "full-access", + "enum": [ + "full-access", + "read-only" + ] + }, + "description": "Authorization level for the token (full-access or read-only)." + } + ], + "requestBody": { + "description": "Additional context such as claims required for the token.", + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTokenInput" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "jwt": { + "type": "string", + "description": "The generated authorization token (JWT)." + } + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "Invalid expiration format" + } + } + } + } + } + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/organizations/{organizationSlug}/groups/{groupName}/auth/rotate": { + "post": { + "summary": "Invalidate All Group Auth Tokens", + "description": "Invalidates all authorization tokens for the specified group.", + "operationId": "invalidateGroupTokens", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/groupName" + } + ], + "responses": { + "200": { + "description": "Successful response (No Content)" + }, + "404": { + "$ref": "#/components/responses/GroupNotFoundResponse" + } + } + } + }, + "/v1/locations": { + "get": { + "summary": "List Locations", + "description": "Returns a list of locations where you can create or replicate databases.", + "operationId": "listLocations", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "locations": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "A mapping of location codes to location names." + } + }, + "example": { + "locations": { + "aws-ap-northeast-1": "AWS AP NorthEast (Tokyo)", + "aws-ap-south-1": "AWS AP South (Mumbai)", + "aws-eu-west-1": "AWS EU West (Ireland)", + "aws-us-east-1": "AWS US East (Virginia)", + "aws-us-east-2": "AWS US East (Ohio)", + "aws-us-west-2": "AWS US West (Oregon)" + } + } + } + } + } + } + } + } + }, + "/v1/organizations": { + "get": { + "summary": "List Organizations", + "description": "Returns a list of organizations the authenticated user owns or is a member of.", + "operationId": "listOrganizations", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Organization" + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}": { + "get": { + "summary": "Retrieve Organization", + "description": "Retrieve details of a specific organization.", + "operationId": "getOrganization", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "organization": { + "$ref": "#/components/schemas/Organization" + } + } + } + } + } + }, + "404": { + "description": "Organization not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "organization not found" + } + } + } + } + } + } + } + }, + "patch": { + "summary": "Update Organization", + "description": "Update an organization you own or are a member of.", + "operationId": "updateOrganization", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "requestBody": { + "description": "The updated organization details.", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "overages": { + "type": "boolean", + "description": "Enable or disable overages for the organization." + }, + "require_mfa": { + "type": "boolean", + "description": "Require all members of the organization to have multi-factor authentication enabled. The requesting user must have MFA enabled on their own account before enabling this requirement." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "organization": { + "description": "The updated organization.", + "$ref": "#/components/schemas/Organization" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/plans": { + "get": { + "summary": "List Plans", + "description": "Returns a list of available plans and their quotas.", + "operationId": "listOrganizationPlans", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "plans": { + "type": "array", + "description": "List of available plans.", + "items": { + "$ref": "#/components/schemas/OrganizationPlan" + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/invoices": { + "get": { + "summary": "List Invoices", + "description": "Returns a list of invoices for the organization.", + "operationId": "listOrganizationInvoices", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "name": "type", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "all", + "upcoming", + "issued" + ] + }, + "description": "The type of invoice to retrieve." + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "invoices": { + "type": "array", + "description": "The list of invoices for the organization.", + "items": { + "type": "object", + "properties": { + "invoice_number": { + "type": "string", + "description": "The unique ID for the invoice.", + "example": "LFONTK-00001" + }, + "amount_due": { + "type": "string", + "description": "The formatted price in USD for the invoice.", + "example": "10.29" + }, + "due_date": { + "type": "string", + "description": "The due date for the invoice.", + "example": "2024-01-01T05:00:00+00:00" + }, + "paid_at": { + "type": "string", + "description": "The date the invoice was paid.", + "example": "2024-01-01T05:00:00+00:00" + }, + "payment_failed_at": { + "type": "string", + "description": "The date the invoice payment last failed.", + "example": "2024-01-01T05:00:00+00:00" + }, + "invoice_pdf": { + "type": "string", + "description": "The link to the invoice PDF you can download.", + "example": "https://assets.withorb.com/invoice/..." + } + } + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/subscription": { + "get": { + "summary": "Current Subscription", + "description": "Returns the current subscription details for the organization.", + "operationId": "getOrganizationSubscription", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "subscription": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the plan for the current subscription.", + "example": "scaler" + }, + "overages": { + "type": "boolean", + "description": "Whether overages are enabled for the organization." + }, + "plan": { + "type": "string", + "description": "The name of the plan for the current subscription.", + "example": "scaler" + }, + "timeline": { + "type": "string", + "description": "Whether the plan is billed monthly or yearly.", + "example": "monthly" + } + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/usage": { + "get": { + "summary": "Organization Usage", + "description": "Fetch current billing cycle usage for an organization.", + "operationId": "getOrganizationUsage", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "organization": { + "type": "object", + "description": "The organization usage object, containing the total usage for rows read and written, as well as the total storage size (in bytes).", + "properties": { + "uuid": { + "type": "string", + "description": "The UUID of the organization.", + "example": "fa72ba58-7db3-436b-bcab-14b83eb1dd88" + }, + "usage": { + "type": "object", + "description": "The usage object for the organization.", + "properties": { + "rows_read": { + "type": "integer", + "description": "The number of rows read allowed for the specific plan.", + "example": 1000000000 + }, + "rows_written": { + "type": "integer", + "description": "The number of rows written allowed for the specific plan.", + "example": 25000000 + }, + "databases": { + "type": "integer", + "description": "The number of databases allowed for the specific plan.", + "example": 500 + }, + "locations": { + "type": "integer", + "description": "The number of locations allowed for the specific plan.", + "example": 3 + }, + "storage_bytes": { + "type": "integer", + "description": "The amount of storage allowed for the specific plan, in bytes.", + "example": 9000000000 + }, + "groups": { + "type": "integer", + "description": "The number of groups allowed for the specific plan.", + "example": 1 + }, + "bytes_synced": { + "type": "integer", + "description": "The number of bytes synced allowed for the specific plan, in bytes.", + "example": 3000000000 + } + } + }, + "databases": { + "type": "array", + "description": "The databases for the organization and their usage.", + "items": { + "$ref": "#/components/schemas/DatabaseUsageOutput" + } + } + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/members": { + "get": { + "summary": "List Members", + "description": "Returns a list of members part of the organization.", + "operationId": "listOrganizationMembers", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Member" + } + } + } + } + } + } + } + } + }, + "post": { + "summary": "Add Member", + "description": "Add an existing Turso user to an organization.", + "operationId": "addOrganizationMember", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "requestBody": { + "description": "The member you want to add.", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "username": { + "type": "string", + "description": "The username of an existing Turso user." + }, + "role": { + "type": "string", + "enum": [ + "admin", + "member", + "viewer" + ], + "description": "The role given to the user.", + "default": "member" + } + }, + "required": [ + "email" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "member": { + "$ref": "#/components/schemas/Member/properties/username" + }, + "role": { + "$ref": "#/components/schemas/Member/properties/role" + } + } + } + } + } + }, + "404": { + "description": "Member not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "could not find user [username]" + } + } + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "user [username] is already a member of organization [organizationSlug]" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/members/{username}": { + "get": { + "summary": "Retrieve Member", + "description": "Retrieve details of a specific member in the organization.", + "operationId": "getOrganizationMember", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/username" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "member": { + "$ref": "#/components/schemas/Member" + } + } + } + } + } + }, + "404": { + "description": "Member not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "could not find member" + } + } + } + } + } + } + } + }, + "patch": { + "summary": "Update Member Role", + "description": "Update the role of an organization member. Only organization admins or owners can perform this action.", + "operationId": "updateMemberRole", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/username" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "admin", + "member", + "viewer" + ], + "description": "The new role to assign to the member." + } + }, + "required": [ + "role" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "member": { + "type": "object", + "properties": { + "username": { + "type": "string", + "description": "The username of the updated member." + }, + "email": { + "type": "string", + "description": "The email of the updated member." + }, + "role": { + "type": "string", + "description": "The new role of the updated member.", + "enum": [ + "admin", + "member", + "viewer" + ] + } + } + } + } + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "invalid role" + } + } + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "updating member roles is only allowed for admin or owner" + } + } + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "could not find user [username]" + } + } + } + } + } + } + } + }, + "delete": { + "summary": "Remove Member", + "description": "Remove a user from the organization by username.", + "operationId": "removeOrganizationMember", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/username" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "member": { + "$ref": "#/components/schemas/Member/properties/username" + } + } + } + } + } + }, + "404": { + "description": "Member not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "user [username] is not a member of org [organizationSlug]" + } + } + } + } + } + } + } + } + }, + "/v1/auth/validate": { + "get": { + "summary": "Validate API Token", + "description": "Validates an API token belonging to a user.", + "operationId": "validateAPIToken", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "exp": { + "type": "integer", + "description": "The time of expiration for the provided token in unix epoch seconds, or `-1` if there is no expiration.", + "example": 999 + } + } + } + } + } + } + } + } + }, + "/v1/auth/api-tokens": { + "get": { + "summary": "List API Tokens", + "description": "Returns a list of API tokens belonging to a user.", + "operationId": "listAPITokens", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tokens": { + "type": "array", + "items": { + "$ref": "#/components/schemas/APIToken" + } + } + } + } + } + } + } + } + } + }, + "/v1/auth/api-tokens/{tokenName}": { + "post": { + "summary": "Create API Token", + "description": "Returns a new API token belonging to a user.\n\nThe token can be minted at three levels of restriction, in increasing order of narrowness:\n\n- **Organization-scoped** — pass `organization`. The token can only act on resources inside that organization.\n- **Group-scoped** — pass `organization`, `group`, and `scopes`. The token is pinned to a single group inside the organization and only the operations listed in `scopes` are allowed. The caller must be an admin or owner of the organization.\n- **Unrestricted** *(deprecated)* — no request body. The token can act on every organization the caller belongs to. **Unrestricted tokens are deprecated and will be removed in a future release.** Always pass `organization` for new tokens and rotate existing unrestricted tokens to scoped tokens.\n\nGroup-scoped tokens are designed for automations that should be able to provision and manage databases inside a single group without being able to touch the rest of the organization.", + "operationId": "createAPIToken", + "parameters": [ + { + "$ref": "#/components/parameters/tokenName" + } + ], + "requestBody": { + "description": "Optional restriction for the token. Omit the body for an unrestricted token, pass `organization` alone for an org-scoped token, or pass `organization` + `group` + `scopes` for a group-scoped token.", + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The organization slug to restrict this token to. Required when `group` is set.", + "example": "my-org" + }, + "group": { + "type": "string", + "description": "The group name (inside `organization`) to restrict this token to. Requires `organization` and a non-empty `scopes` list.", + "example": "default" + }, + "scopes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "read", + "db:create", + "db:delete", + "db:configure", + "db:mint-token", + "db:rotate-creds", + "group:configure", + "group:mint-token", + "group:rotate-creds", + "read-only", + "full-access" + ] + }, + "description": "Permissions to grant a group-scoped token. Each entry is either an individual scope or one of the presets `read-only` (expands to `read`) and `full-access` (expands to every scope). Required and must be non-empty when `group` is set. `db:mint-token` lets the token issue new SQL credentials; `db:rotate-creds` invalidates every existing SQL token for the database — they are deliberately separate because rotation is destructive.", + "example": ["db:create", "db:configure", "db:mint-token"] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "properties": { + "name": { + "$ref": "#/components/schemas/APIToken/properties/name" + }, + "id": { + "$ref": "#/components/schemas/APIToken/properties/id" + }, + "token": { + "type": "string", + "description": "The actual token contents as a JWT. This is used with the `Bearer` header, see [Authentication](/authentication) for more details. **This token is never revealed again.**", + "example": "..." + } + } + } + } + } + } + } + }, + "delete": { + "summary": "Revoke API Token", + "description": "Revokes the provided API token belonging to a user.", + "operationId": "revokeAPIToken", + "parameters": [ + { + "$ref": "#/components/parameters/tokenName" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "properties": { + "token": { + "type": "string", + "description": "The revoked token name.", + "example": "..." + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/api-tokens": { + "get": { + "summary": "List Organization API Tokens", + "description": "Returns the API tokens scoped to this organization (both organization-scoped and group-scoped). Unrestricted tokens are not returned here — manage those via [`GET /v1/auth/api-tokens`](/api-reference/tokens/list).\n\nAuthorization is symmetric with the revoke endpoint:\n\n- **Admins and owners** see every token scoped to the organization, with the minting user attached in the `owner` field.\n- **Members and viewers** see only tokens they minted themselves.\n\nThis mirrors the personal-access-token model used in GitHub organization settings: admins get the full attribution list; everyone else sees their own access.", + "operationId": "listOrganizationAPITokens", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tokens": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The token name.", + "example": "ci-bot" + }, + "id": { + "type": "string", + "description": "The token ID. Pass this to the revoke endpoint.", + "example": "clGFZ4STEe6fljpFzIum8A" + }, + "organization": { + "type": "string", + "description": "The organization slug. Always equal to the path parameter for tokens returned here.", + "example": "my-org" + }, + "group": { + "type": "string", + "description": "The group name. Present only for group-scoped tokens.", + "example": "default" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The expanded scope list. Present only for group-scoped tokens.", + "example": ["db:create", "db:configure", "db:mint-token"] + }, + "owner": { + "type": "object", + "properties": { + "username": { + "type": "string", + "example": "alice" + }, + "email": { + "type": "string", + "example": "alice@example.com" + } + }, + "description": "The user who minted the token. Returned to admins and owners so they can see who provisioned each token." + }, + "created_at": { + "type": "string", + "description": "The date the token was created.", + "example": "2026-05-21" + } + } + } + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/api-tokens/{tokenId}": { + "delete": { + "summary": "Revoke Organization API Token", + "description": "Revokes a token scoped to this organization.\n\nThe path takes a token **ID**, not a name, because names are unique per user but not across users — an admin revoking a member's token can't disambiguate by name alone.\n\nAuthorization is symmetric with the list endpoint:\n\n- **Admins and owners** can revoke any token scoped to the organization (org-scoped or group-scoped, regardless of who minted it).\n- **Members and viewers** can revoke only tokens they minted themselves.\n\nA token scoped to a different organization returns `404`, not `403`, so the endpoint does not leak the existence of cross-org token IDs. Unrestricted tokens are also unreachable here and must be revoked via [`DELETE /v1/auth/api-tokens/{tokenName}`](/api-reference/tokens/revoke).", + "operationId": "revokeOrganizationAPIToken", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "name": "tokenId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the token to revoke (from the list endpoint).", + "example": "clGFZ4STEe6fljpFzIum8A" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The ID of the revoked token.", + "example": "clGFZ4STEe6fljpFzIum8A" + } + } + } + } + } + } + } + } + }, + "/v1/organizations/{organizationSlug}/audit-logs": { + "get": { + "summary": "List Audit Logs", + "description": "Return the audit logs for the given organization, ordered by the `created_at` field in descending order.", + "operationId": "listOrganizationAuditLogs", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "$ref": "#/components/parameters/page_size" + }, + { + "$ref": "#/components/parameters/page" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "audit_logs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AuditLog" + } + }, + "pagination": { + "type": "object", + "properties": { + "page": { + "type": "integer", + "description": "The current page number.", + "example": 1 + }, + "page_size": { + "type": "integer", + "description": "The number of items per page.", + "example": 10 + }, + "total_pages": { + "type": "integer", + "description": "The total number of pages.", + "example": 1 + }, + "total_rows": { + "type": "integer", + "description": "The total number of items.", + "example": 1 + } + } + } + } + } + } + } + } + } + } + }, + "/v2/organizations/{organizationSlug}/invites": { + "get": { + "summary": "List Invites", + "description": "Returns a list of pending invites for the organization.", + "operationId": "listOrganizationInvitesV2", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "invites": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InviteV2" + } + } + } + } + } + } + } + } + }, + "post": { + "summary": "Invite Organization Member", + "description": "Invite a user to an organization. If the user isn't already registered with Turso, they will receive a signup link. If an existing pending invite exists for the same email, it will be replaced.", + "operationId": "inviteOrganizationMemberV2", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + } + ], + "requestBody": { + "description": "The user you want to invite to join Turso, and your organization. Provide exactly one of email or username.", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "The email of the user you want to invite. Exactly one of email or username must be provided." + }, + "username": { + "type": "string", + "description": "The username of an existing Turso user you want to invite. Exactly one of email or username must be provided." + }, + "role": { + "type": "string", + "enum": [ + "admin", + "member", + "viewer" + ], + "description": "The role given to the user.", + "default": "member" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "invited": { + "$ref": "#/components/schemas/InviteCreatedV2" + } + } + } + } + } + } + } + } + }, + "/v2/organizations/{organizationSlug}/invites/{email}": { + "delete": { + "summary": "Delete Invite", + "description": "Delete a pending invite for the organization by email.", + "operationId": "deleteOrganizationInviteByEmailV2", + "parameters": [ + { + "$ref": "#/components/parameters/organizationSlug" + }, + { + "in": "path", + "name": "email", + "required": true, + "schema": { + "type": "string", + "description": "The email of the user invited.", + "example": "iku@turso.tech" + } + } + ], + "responses": { + "200": { + "description": "Successful response (No Content)" + }, + "404": { + "description": "Invite not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "example": "invite not found" + } + } + } + } + } + } + } + } + }, + "/v1/user": { + "get": { + "summary": "Get Current User", + "description": "Returns information about the currently authenticated user.", + "operationId": "getCurrentUser", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "user": { + "type": "object", + "properties": { + "username": { + "type": "string", + "description": "The username of the user.", + "example": "iku" + }, + "name": { + "type": "string", + "description": "The display name of the user.", + "example": "Iku Turso" + }, + "email": { + "type": "string", + "description": "The primary email address of the user.", + "example": "iku@turso.tech" + }, + "avatarUrl": { + "type": "string", + "description": "URL to the user's avatar image.", + "example": "https://avatars.githubusercontent.com/u/12345" + }, + "plan": { + "type": "string", + "description": "The user's current plan.", + "example": "scaler" + }, + "mfa": { + "type": "boolean", + "description": "Whether the user has multi-factor authentication enabled.", + "example": false + }, + "has_pending_invites": { + "type": "boolean", + "description": "Whether the user has pending organization invites waiting to be accepted or declined.", + "example": false + } + } + } + } + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT" + } + }, + "schemas": { + "Extensions": { + "oneOf": [ + { + "type": "string", + "enum": [ + "all" + ], + "description": "Set to `all` to enable all extensions." + }, + { + "type": "array", + "items": { + "type": "string", + "enum": [ + "vector", + "crypto", + "fuzzy", + "math", + "stats", + "text", + "unicode", + "uuid", + "regexp", + "vec" + ] + }, + "description": "Array of extensions to enable." + } + ], + "description": "The extensions to enable for new databases created in this group. Users looking to enable vector extensions should instead use the native [libSQL vector datatype](/features/ai-and-embeddings)." + }, + "Organization": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization name. Every user has a `personal` organization for their own account.", + "example": "personal" + }, + "slug": { + "type": "string", + "description": "The organization slug. This will be your username for `personal` accounts.", + "example": "iku" + }, + "type": { + "type": "string", + "description": "The type of account this organization is. Will always be `personal` or `team`.", + "example": "personal", + "enum": [ + "personal", + "team" + ] + }, + "overages": { + "type": "boolean", + "description": "The name of the organization. Every user has a `personal` organization for their own account.", + "example": false + }, + "require_mfa": { + "type": "boolean", + "description": "Whether all members of the organization are required to have multi-factor authentication enabled.", + "example": false + }, + "blocked_reads": { + "type": "boolean", + "description": "Returns the current status for blocked reads.", + "example": false + }, + "blocked_writes": { + "type": "boolean", + "description": "Returns the current status for blocked writes.", + "example": false + }, + "plan_id": { + "type": "string", + "description": "The pricing plan identifier this organization is subscribed to.", + "example": "developer" + }, + "plan_timeline": { + "type": "string", + "description": "The billing cycle for the paid plan, if any.", + "example": "monthly" + }, + "platform": { + "type": "string", + "description": "The external platform this organization is managed by. Will be empty for Turso managed organizations.", + "example": "vercel" + } + } + }, + "Member": { + "type": "object", + "properties": { + "username": { + "type": "string", + "description": "The username for the member.", + "example": "iku" + }, + "role": { + "type": "string", + "description": "The role assigned to the member.", + "example": "owner", + "enum": [ + "owner", + "admin", + "member", + "viewer" + ] + }, + "email": { + "type": "string", + "description": "The email for the member.", + "example": "iku@turso.tech" + } + } + }, + "APIToken": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name given to the API Token.", + "example": "my-token" + }, + "id": { + "type": "string", + "description": "The ID generated by Turso for the API Token.", + "example": "clGFZ4STEe6fljpFzIum8A" + }, + "organization": { + "type": "string", + "description": "The organization slug this token is restricted to. Omitted if the token has access to all organizations.", + "example": "my-org" + }, + "group": { + "type": "string", + "description": "The group name this token is pinned to. Present only for group-scoped tokens.", + "example": "default" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The expanded list of scopes granted to this token. Present only for group-scoped tokens. Presets passed at creation time (`read-only`, `full-access`) are stored as the underlying individual scopes and are returned in that form.", + "example": ["db:create", "db:configure", "db:mint-token"] + }, + "created_at": { + "type": "string", + "description": "The date the token was created, in `YYYY-MM-DD` format.", + "example": "2026-05-21" + } + } + }, + "AuditLog": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The code associated to the action taken.", + "example": "db-create", + "enum": [ + "user-signup", + "db-create", + "db-delete", + "db-protect", + "db-unprotect", + "db-token-create", + "group-token-create", + "user-token-create", + "instance-create", + "instance-delete", + "org-create", + "org-delete", + "org-member-add", + "org-member-rm", + "org-member-leave", + "org-plan-update", + "org-set-overages", + "group-create", + "group-delete", + "group-unarchive", + "group-protect", + "group-unprotect", + "db-aunrchive", + "user-delete" + ] + }, + "message": { + "type": "string", + "description": "Additional context from the performed action.", + "example": "" + }, + "origin": { + "type": "string", + "description": "Where this action was performed. Will be either `cli` or `web` depending on the `User-Agent` sent to the API.", + "example": "cli" + }, + "author": { + "type": "string", + "description": "The username of the user who performed the action.", + "example": "iku" + }, + "created_at": { + "type": "string", + "description": "A formatted [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp this action was performed.", + "example": "2023-12-20T09:46:08Z" + }, + "data": { + "type": "object", + "description": "The payload of the action performed." + } + } + }, + "Database": { + "type": "object", + "properties": { + "Name": { + "type": "string", + "description": "The database name, **unique** across your organization.", + "example": "my-db" + }, + "DbId": { + "type": "string", + "description": "The database universal unique identifier (UUID).", + "example": "0eb771dd-6906-11ee-8553-eaa7715aeaf2" + }, + "Hostname": { + "type": "string", + "description": "The DNS hostname used for client libSQL and HTTP connections.", + "example": "[databaseName]-[organizationSlug].turso.io" + }, + "block_reads": { + "type": "boolean", + "description": "The current status for blocked reads.", + "example": false + }, + "block_writes": { + "type": "boolean", + "description": "The current status for blocked writes.", + "example": false + }, + "regions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A list of regions for the group the database belongs to.", + "example": [ + "aws-us-east-1" + ], + "deprecated": true + }, + "primaryRegion": { + "type": "string", + "description": "The primary region location code the group the database belongs to.", + "example": "aws-us-east-1" + }, + "group": { + "type": "string", + "description": "The name of the group the database belongs to.", + "example": "default" + }, + "delete_protection": { + "type": "boolean", + "description": "The current status for delete protection. If enabled, the database cannot be deleted.", + "example": false + }, + "parent": { + "type": "object", + "nullable": true, + "properties": { + "id": { + "type": "string", + "description": "The parent database identifier." + }, + "name": { + "type": "string", + "description": "The name of the parent database." + }, + "branched_at": { + "type": "string", + "format": "date-time", + "description": "The timestamp when the database was branched from the parent.", + "example": "2025-04-15T13:14:34.468213117Z" + } + } + } + } + }, + "Instance": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "description": "The instance universal unique identifier (UUID).", + "example": "0be90471-6906-11ee-8553-eaa7715aeaf2" + }, + "name": { + "type": "string", + "description": "The name of the instance (location code).", + "example": "aws-us-east-1" + }, + "type": { + "type": "string", + "description": "The type of database instance this, will be `primary` or `replica`.", + "enum": [ + "primary", + "replica" + ], + "example": "primary" + }, + "region": { + "type": "string", + "description": "The location code for the region this instance is located.", + "example": "aws-us-east-1" + }, + "hostname": { + "type": "string", + "description": "The DNS hostname used for client libSQL and HTTP connections (specific to this instance only).", + "example": "[databaseName]-[organizationSlug].turso.io" + } + } + }, + "CreateDatabaseInput": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 64 characters." + }, + "group": { + "type": "string", + "description": "The name of the group where the database should be created. **The group must already exist.**" + }, + "seed": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "database", + "database_upload" + ], + "description": "The type of seed to be used to create a new database. Use `database` to copy from an existing database, or `database_upload` to [upload a SQLite database file](/api-reference/databases/upload).", + "example": "database" + }, + "name": { + "type": "string", + "description": "The name of the existing database when `database` is used as a seed type.", + "example": "my-db" + }, + "timestamp": { + "type": "string", + "description": "A formatted [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) recovery point to create a database from. This must be within the last 24 hours, or 30 days on the scaler plan.", + "example": "2023-12-20T09:46:08Z" + } + } + }, + "size_limit": { + "type": "string", + "description": "The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb." + }, + "remote_encryption": { + "type": "object", + "description": "Encryption configuration for the database. Can be used when creating a new encrypted database, creating a encrypted database from upload (`seed.type = \"database_upload\"`), or forking from an encrypted database (required when the source database is encrypted).", + "properties": { + "encryption_key": { + "type": "string", + "description": "Base64-encoded encryption key. Key size depends on cipher: 32 bytes for aes256gcm, chacha20poly1305, aegis256 variants; 16 bytes for aes128gcm, aegis128l variants.", + "example": "base64-encoded-key" + }, + "encryption_cipher": { + "type": "string", + "enum": [ + "aes256gcm", + "aes128gcm", + "chacha20poly1305", + "aegis128l", + "aegis128x2", + "aegis128x4", + "aegis256", + "aegis256x2", + "aegis256x4" + ], + "description": "The encryption cipher to use.", + "example": "aes256gcm" + } + } + } + }, + "required": [ + "name", + "group" + ] + }, + "CreateDatabaseOutput": { + "type": "object", + "properties": { + "DbId": { + "$ref": "#/components/schemas/Database/properties/DbId" + }, + "Hostname": { + "$ref": "#/components/schemas/Database/properties/Hostname" + }, + "Name": { + "$ref": "#/components/schemas/Database/properties/Name" + } + } + }, + "DatabaseStatsOutput": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "A string representing the SQL query executed.", + "example": "SELECT COUNT(*), CustomerID FROM Orders GROUP BY CustomerID HAVING COUNT(*) > 5;" + }, + "rows_read": { + "type": "integer", + "description": "An integer indicating the number of rows read by the query, which reflects the volume of data the query processed from the database.", + "example": 123 + }, + "rows_written": { + "type": "integer", + "description": "An integer indicating the number of rows written (inserted, updated, or deleted) by the query, which reflects the impact of the query on the database data.", + "example": 4567 + } + } + }, + "DatabaseUsageOutput": { + "type": "object", + "properties": { + "uuid": { + "$ref": "#/components/schemas/Database/properties/DbId" + }, + "instances": { + "type": "array", + "description": "The usage objects for instances of the current database.", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "description": "The instance universal unique identifier (UUID).", + "example": "cd831986-94e5-11ee-a6fe-7a52e1f7759a" + }, + "usage": { + "description": "The usage for the current database instance.", + "$ref": "#/components/schemas/DatabaseUsageObject" + } + } + }, + "example": [ + { + "uuid": "cd831986-94e5-11ee-a6fe-7a52e1f7759a", + "usage": { + "rows_read": 0, + "rows_written": 0, + "storage_bytes": 4096, + "bytes_synced": 0 + } + }, + { + "uuid": "0be90471-6906-11ee-8553-eaa7715aeaf2", + "usage": { + "rows_read": 0, + "rows_written": 0, + "storage_bytes": 4096, + "bytes_synced": 0 + } + } + ] + }, + "total": { + "description": "The total usage for the database.", + "$ref": "#/components/schemas/DatabaseUsageObject", + "example": { + "rows_read": 0, + "rows_written": 0, + "storage_bytes": 8192, + "bytes_synced": 0 + } + } + } + }, + "DatabaseUsageObject": { + "type": "object", + "properties": { + "rows_read": { + "type": "integer", + "example": 0, + "description": "The total rows read in the time period." + }, + "rows_written": { + "type": "integer", + "example": 0, + "description": "The total rows written in the time period." + }, + "storage_bytes": { + "type": "integer", + "example": 0, + "description": "The total storage used." + }, + "bytes_synced": { + "type": "integer", + "example": 0, + "description": "The total bytes synced." + } + } + }, + "CreateTokenInput": { + "type": "object", + "properties": { + "permissions": { + "type": "object", + "description": "The permissions for the token.", + "properties": { + "read_attach": { + "type": "object", + "description": "Read `ATTACH` permission for the token.", + "properties": { + "databases": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + }, + "DatabaseConfigurationInput": { + "type": "object", + "properties": { + "size_limit": { + "type": "string", + "description": "The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb." + }, + "allow_attach": { + "type": "boolean", + "description": "Allow or disallow attaching databases to the current database.", + "deprecated": true + }, + "block_reads": { + "type": "boolean", + "description": "Block all database reads.", + "example": false + }, + "block_writes": { + "type": "boolean", + "description": "Block all database writes.", + "example": false + }, + "delete_protection": { + "type": "boolean", + "description": "Prevent the database from being deleted.", + "example": true + } + } + }, + "DatabaseConfigurationResponse": { + "type": "object", + "properties": { + "size_limit": { + "type": "string", + "description": "The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb.", + "example": "10000" + }, + "allow_attach": { + "type": "boolean", + "description": "Allow or disallow attaching databases to the current database.", + "example": true, + "deprecated": true + }, + "block_reads": { + "type": "boolean", + "description": "The current status for blocked reads.", + "example": false + }, + "block_writes": { + "type": "boolean", + "description": "The current status for blocked writes.", + "example": false + }, + "delete_protection": { + "type": "boolean", + "description": "Prevent the database from being deleted.", + "example": true + } + } + }, + "BaseGroup": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The group name, unique across your organization.", + "example": "default" + }, + "version": { + "type": "string", + "description": "The current libSQL server version the databases in that group are running.", + "example": "v0.23.7", + "deprecated": true + }, + "uuid": { + "type": "string", + "description": "The group universal unique identifier (UUID).", + "example": "0a28102d-6906-11ee-8553-eaa7715aeaf2" + }, + "locations": { + "type": "array", + "items": { + "type": "string" + }, + "description": "An array of location keys the group is located.", + "example": [ + "aws-us-east-1" + ], + "deprecated": true + }, + "primary": { + "type": "string", + "description": "The primary location key.", + "example": "us-east-1" + }, + "delete_protection": { + "type": "boolean", + "description": "The current status for delete protection. If enabled, the group and all its databases cannot be deleted.", + "example": false + } + } + }, + "GroupConfigurationInput": { + "type": "object", + "properties": { + "delete_protection": { + "type": "boolean", + "description": "Prevent the group from being deleted.", + "example": true + } + } + }, + "GroupConfigurationResponse": { + "type": "object", + "properties": { + "delete_protection": { + "type": "boolean", + "description": "Prevent the group from being deleted.", + "example": true + } + } + }, + "OrganizationPlan": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the plan.", + "example": "starter" + }, + "price": { + "type": "string", + "description": "The monthly price of the plan.", + "example": "0" + }, + "prices": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PlanPrice" + } + }, + "quotas": { + "$ref": "#/components/schemas/PlanQuotas" + } + } + }, + "PlanPrice": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "Price of the available plan.", + "example": "29" + }, + "timeline": { + "type": "string", + "description": "Payment regularity.", + "example": "monthly" + } + } + }, + "PlanQuotas": { + "type": "object", + "properties": { + "rowsRead": { + "type": "integer", + "description": "The number of rows read allowed for the specific plan.", + "example": 1000000000 + }, + "rowsWritten": { + "type": "integer", + "description": "The number of rows written allowed for the specific plan.", + "example": 25000000 + }, + "databases": { + "type": "integer", + "nullable": true, + "description": "The number of databases allowed for the specific plan.", + "example": 500 + }, + "locations": { + "type": "integer", + "description": "The number of locations allowed for the specific plan.", + "example": 3 + }, + "storage": { + "type": "integer", + "description": "The amount of storage allowed for the specific plan, in bytes.", + "example": 9000000000 + }, + "groups": { + "type": "integer", + "description": "The number of groups allowed for the specific plan.", + "example": 1 + }, + "bytesSynced": { + "type": "integer", + "description": "The number of bytes synced allowed for the specific plan, in bytes.", + "example": 3000000000 + } + } + }, + "NewGroup": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the new group." + }, + "location": { + "type": "string", + "description": "The location key for the new group." + }, + "extensions": { + "$ref": "#/components/schemas/Extensions" + } + }, + "required": [ + "name", + "location" + ], + "example": { + "name": "new-group", + "location": "aws-us-east-1" + } + }, + "Group": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseGroup" + }, + { + "type": "object" + } + ] + }, + "InviteV2": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "description": "The unique ID for the invite.", + "example": 1 + }, + "email": { + "type": "string", + "description": "The email of the person invited.", + "example": "iku@turso.tech" + }, + "role": { + "type": "string", + "enum": [ + "admin", + "member", + "viewer" + ], + "description": "The assigned role for the invited user.", + "example": "member" + }, + "created_at": { + "type": "string", + "description": "The datetime the invite was created in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.", + "example": "2023-01-01T00:00:00Z" + } + } + }, + "InviteCreatedV2": { + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "The email of the person invited.", + "example": "iku@turso.tech" + }, + "role": { + "type": "string", + "enum": [ + "admin", + "member", + "viewer" + ], + "description": "The assigned role for the invited user.", + "example": "member" + }, + "organization": { + "type": "string", + "description": "The name of the organization the user was invited to.", + "example": "mycompany" + } + } + } + }, + "responses": { + "GroupNotFoundResponse": { + "description": "Group not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "group not found" + } + } + } + } + } + }, + "DatabaseNotFoundResponse": { + "description": "Database not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The error message", + "example": "could not find database with name [databaseName]: record not found" + } + } + } + } + } + } + }, + "parameters": { + "organizationSlug": { + "in": "path", + "name": "organizationSlug", + "required": true, + "schema": { + "type": "string" + }, + "description": "The slug of the organization or user account." + }, + "groupName": { + "name": "groupName", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the group." + }, + "databaseName": { + "name": "databaseName", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the database." + }, + "instanceName": { + "name": "instanceName", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the instance (location code)." + }, + "tokenName": { + "name": "tokenName", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the api token." + }, + "username": { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The username of a Turso user or organization member." + }, + "page_size": { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "type": "integer" + }, + "description": "The limit of items to return per page. Defaults to 100." + }, + "page": { + "in": "query", + "name": "page", + "required": false, + "schema": { + "type": "integer" + }, + "description": "The page number to return. Defaults to 1." + } + } + } +} diff --git a/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/OpenApiTitler.csproj b/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/OpenApiTitler.csproj new file mode 100644 index 000000000..df37d3942 --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/OpenApiTitler.csproj @@ -0,0 +1,11 @@ + + + + Exe + net10.0 + enable + enable + Turso.Platform.Client.Tools + false + + diff --git a/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/Program.cs b/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/Program.cs new file mode 100644 index 000000000..f28046ea6 --- /dev/null +++ b/bindings/dotnet/src/Turso.Platform.Client/tools/OpenApiTitler/Program.cs @@ -0,0 +1,217 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +// Names the anonymous inline schemas of an OpenAPI document so NSwag does not fall back to +// counter names (`Response17`, `Body3`): +// - 2xx response and request-body schemas get a `title` derived from the `operationId` +// (`listDatabases` -> `ListDatabasesResponse` / `CreateGroupRequest`); NSwag uses the title +// as the generated class name. +// - error (non-2xx) response schemas are lifted into shared `components/schemas` entries and +// replaced with `$ref`s, deduplicated by structural shape — the Turso API reuses one +// `{ error: string }` shape, so they all collapse into a single `ErrorResponse` class. +// The upstream document is left untouched; the transformed copy is consumed by nswag.json. +// +// Usage: OpenApiTitler + +if (args.Length != 2) +{ + Console.Error.WriteLine("Usage: OpenApiTitler "); + return 1; +} + +var root = JsonNode.Parse(File.ReadAllText(args[0])) + ?? throw new InvalidOperationException("Failed to parse OpenAPI document."); + +string[] methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; +var titled = 0; +var lifted = 0; + +var componentSchemas = root["components"]?["schemas"] as JsonObject + ?? throw new InvalidOperationException("Document has no components/schemas section."); +var errorShapes = new Dictionary(); // structural signature -> component name +NormalizeExtensionsUnion(componentSchemas); + +if (root["paths"] is JsonObject paths) +{ + foreach (var (_, pathValue) in paths) + { + if (pathValue is not JsonObject pathItem) + { + continue; + } + + foreach (var method in methods) + { + if (pathItem[method] is not JsonObject operation) + { + continue; + } + + var operationName = ToPascalCase(operation["operationId"]?.GetValue()); + if (operationName is null) + { + continue; + } + + TitleSchema(GetJsonSchema(operation["requestBody"]), $"{operationName}Request"); + + if (operation["responses"] is not JsonObject responses) + { + continue; + } + + // Collect the response codes that carry an inline schema so the success/error + // suffixes only get a status-code disambiguator when one is actually needed. + var successCodes = new List(); + var errorCodes = new List(); + foreach (var (code, response) in responses) + { + if (GetJsonSchema(response) is not null) + { + (code.StartsWith('2') ? successCodes : errorCodes).Add(code); + } + } + + foreach (var code in successCodes) + { + var suffix = successCodes.Count > 1 ? code : ""; + TitleSchema(GetJsonSchema(responses[code]), $"{operationName}Response{suffix}"); + } + + foreach (var code in errorCodes) + { + var suffix = errorCodes.Count > 1 ? code : ""; + LiftErrorSchema(responses[code], $"{operationName}Error{suffix}"); + } + } + } +} + +// Reusable error responses (components/responses) carry the same inline shapes; lift them too. +if (root["components"]?["responses"] is JsonObject componentResponses) +{ + foreach (var (name, response) in componentResponses) + { + LiftErrorSchema(response, name); + } +} + +File.WriteAllText(args[1], root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); +Console.WriteLine($"Titled {titled} inline schemas, lifted {lifted} error schemas into {errorShapes.Count} shared component(s) -> {args[1]}"); +return 0; + +// Resolves requestBody/response -> content -> application/json -> schema. +JsonObject? GetJsonSchema(JsonNode? requestBodyOrResponse) +{ + return requestBodyOrResponse?["content"]?["application/json"]?["schema"] as JsonObject; +} + +// Replaces an inline error schema with a $ref to a shared components/schemas entry, reusing the +// same component for structurally identical shapes. `fallbackName` names a shape seen first here. +void LiftErrorSchema(JsonNode? response, string fallbackName) +{ + var schema = GetJsonSchema(response); + if (schema is null || schema.ContainsKey("$ref")) + { + return; + } + + var signature = StructuralSignature(schema); + if (!errorShapes.TryGetValue(signature, out var componentName)) + { + // The ubiquitous { error: string } payload gets the canonical name; other shapes keep + // their operation-derived fallback. + componentName = errorShapes.Count == 0 && schema["properties"] is JsonObject props + && props.Count == 1 && props.ContainsKey("error") + ? "ErrorResponse" + : fallbackName; + + if (!componentSchemas.ContainsKey(componentName)) + { + var component = schema.DeepClone().AsObject(); + component.Remove("title"); + componentSchemas[componentName] = component; + } + + errorShapes[signature] = componentName; + } + + var content = response!["content"]!["application/json"]!.AsObject(); + content["schema"] = new JsonObject { ["$ref"] = $"#/components/schemas/{componentName}" }; + lifted++; +} + +// Canonical shape of a schema, ignoring documentation-only members. +static string StructuralSignature(JsonNode? node) +{ + if (node is JsonObject obj) + { + var parts = obj + .Where(static p => p.Key is not ("description" or "example" or "title")) + .OrderBy(static p => p.Key, StringComparer.Ordinal) + .Select(static p => $"\"{p.Key}\":{StructuralSignature(p.Value)}"); + return "{" + string.Join(",", parts) + "}"; + } + + if (node is JsonArray arr) + { + return "[" + string.Join(",", arr.Select(StructuralSignature)) + "]"; + } + + return node?.ToJsonString() ?? "null"; +} + +void TitleSchema(JsonObject? schema, string title) +{ + // Only inline anonymous schemas: a $ref already has a component name, an existing title wins. + if (schema is null || schema.ContainsKey("$ref") || schema.ContainsKey("title")) + { + return; + } + + var type = schema["type"]?.GetValue(); + if (type == "array") + { + // Top-level arrays stay collections; name their inline object items instead. + if (schema["items"] is JsonObject items && !items.ContainsKey("$ref") && !items.ContainsKey("title") + && items["type"]?.GetValue() is null or "object") + { + items["title"] = $"{title}Item"; + titled++; + } + + return; + } + + if (type is null or "object") + { + schema["title"] = title; + titled++; + } +} + +static void NormalizeExtensionsUnion(JsonObject componentSchemas) +{ + var extensions = componentSchemas["Extensions"] as JsonObject + ?? throw new InvalidOperationException("Document has no Extensions schema."); + if (extensions["oneOf"] is not JsonArray) + { + throw new InvalidOperationException("Extensions schema is no longer a oneOf union."); + } + + // NSwag emits an enum for the first oneOf branch, losing the valid array form. An object + // emits an extensible partial class so the supplement can model either JSON shape. + extensions.Remove("oneOf"); + extensions["type"] = "object"; +} + +static string? ToPascalCase(string? operationId) +{ + if (string.IsNullOrWhiteSpace(operationId)) + { + return null; + } + + var parts = operationId.Split(['_', '-', ' '], StringSplitOptions.RemoveEmptyEntries); + return string.Concat(parts.Select(static p => char.ToUpperInvariant(p[0]) + p[1..])); +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/HranaHttp.cs b/bindings/dotnet/src/Turso.Serverless.Client/HranaHttp.cs new file mode 100644 index 000000000..ab2536b12 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/HranaHttp.cs @@ -0,0 +1,152 @@ +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.Json; + +namespace Turso.Serverless.Client; + +/// +/// HTTP transport for the SQL over HTTP protocol: /v3/pipeline (JSON request/response) +/// and /v3/cursor (JSON request, newline-delimited JSON streaming response). +/// +internal static class HranaHttp +{ + /// HTTP header carrying the encryption key of an encrypted Turso Cloud database. + internal const string EncryptionKeyHeader = "x-turso-encryption-key"; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + internal static async Task ExecutePipelineAsync( + HttpClient httpClient, + string baseUrl, + string? authToken, + string? remoteEncryptionKey, + HranaPipelineRequest request, + CancellationToken cancellationToken) + { + using var httpRequest = CreateRequest($"{baseUrl}/v3/pipeline", authToken, remoteEncryptionKey, request); + + using var response = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new TursoServerlessException($"HTTP error! status: {(int)response.StatusCode}"); + } + + var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + return JsonSerializer.Deserialize(body, JsonOptions) + ?? throw new TursoServerlessException("Empty pipeline response"); + } + + internal static async Task<(HranaCursorResponse Response, IAsyncEnumerable Entries)> ExecuteCursorAsync( + HttpClient httpClient, + string baseUrl, + string? authToken, + string? remoteEncryptionKey, + HranaCursorRequest request, + CancellationToken cancellationToken) + { + var httpRequest = CreateRequest($"{baseUrl}/v3/cursor", authToken, remoteEncryptionKey, request); + + HttpResponseMessage? response = null; + StreamReader? reader = null; + try + { + response = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + { + var errorMessage = $"HTTP error! status: {(int)response.StatusCode}"; + try + { + var errorBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + using var errorDoc = JsonDocument.Parse(errorBody); + if (errorDoc.RootElement.TryGetProperty("message", out var message) && message.GetString() is { } messageText) + { + errorMessage = messageText; + } + } + catch + { + // If the error body cannot be parsed, keep the default HTTP error message. + } + + throw new TursoServerlessException(errorMessage); + } + + var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + reader = new StreamReader(stream, Encoding.UTF8); + + // The first non-empty line is the cursor response; the rest are cursor entries. + HranaCursorResponse? cursorResponse = null; + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (line.Trim() is not ("" or null) and var trimmed) + { + cursorResponse = JsonSerializer.Deserialize(trimmed, JsonOptions); + break; + } + } + + if (cursorResponse is null) + { + throw new TursoServerlessException("No cursor response received"); + } + + var entries = ReadEntriesAsync(response, reader, cancellationToken); + response = null; // Ownership transferred to the entry enumerator. + reader = null; + return (cursorResponse, entries); + } + finally + { + reader?.Dispose(); + response?.Dispose(); + httpRequest.Dispose(); + } + } + + private static async IAsyncEnumerable ReadEntriesAsync( + HttpResponseMessage response, + StreamReader reader, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + using (response) + using (reader) + { + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + var trimmed = line.Trim(); + if (trimmed.Length == 0) + { + continue; + } + + var entry = JsonSerializer.Deserialize(trimmed, JsonOptions); + if (entry is not null) + { + yield return entry; + } + } + } + } + + private static HttpRequestMessage CreateRequest(string url, string? authToken, string? remoteEncryptionKey, T body) + { + var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) + { + Content = new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json"), + }; + + if (!string.IsNullOrEmpty(authToken)) + { + httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken); + } + + if (!string.IsNullOrEmpty(remoteEncryptionKey)) + { + httpRequest.Headers.Add(EncryptionKeyHeader, remoteEncryptionKey); + } + + return httpRequest; + } +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/HranaProtocol.cs b/bindings/dotnet/src/Turso.Serverless.Client/HranaProtocol.cs new file mode 100644 index 000000000..fee43cc7d --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/HranaProtocol.cs @@ -0,0 +1,370 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Turso.Serverless.Client; + +// Wire types for the SQL over HTTP protocol (Hrana 3), mirroring serverless/javascript/src/protocol.ts. +// Everything here is internal; the public surface re-exposes results through TursoResultSet/TursoRow. + +[JsonConverter(typeof(HranaValueConverter))] +internal readonly struct HranaValue +{ + public string Type { get; init; } + + /// Integer (as decimal string) or text payload. + public string? StringValue { get; init; } + + /// Float payload. + public double? DoubleValue { get; init; } + + /// Blob payload (raw bytes; base64 on the wire). + public byte[]? BlobValue { get; init; } + + public static readonly HranaValue Null = new() { Type = "null" }; + + public static HranaValue Encode(object? value) + { + switch (value) + { + case null or DBNull: + return Null; + case bool b: + return new HranaValue { Type = "integer", StringValue = b ? "1" : "0" }; + case sbyte or byte or short or ushort or int or uint or long: + return new HranaValue { Type = "integer", StringValue = Convert.ToInt64(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) }; + case ulong ul: + return new HranaValue { Type = "integer", StringValue = ul.ToString(CultureInfo.InvariantCulture) }; + case float f: + return double.IsFinite(f) + ? new HranaValue { Type = "float", DoubleValue = f } + : throw new ArgumentException("Only finite numbers (not Infinity or NaN) can be passed as arguments"); + case double d: + return double.IsFinite(d) + ? new HranaValue { Type = "float", DoubleValue = d } + : throw new ArgumentException("Only finite numbers (not Infinity or NaN) can be passed as arguments"); + case decimal m: + return new HranaValue { Type = "float", DoubleValue = (double)m }; + case string s: + return new HranaValue { Type = "text", StringValue = s }; + case char c: + return new HranaValue { Type = "text", StringValue = c.ToString() }; + case Guid g: + return new HranaValue { Type = "text", StringValue = g.ToString() }; + case DateTime dt: + return new HranaValue { Type = "text", StringValue = dt.ToString("o", CultureInfo.InvariantCulture) }; + case DateTimeOffset dto: + return new HranaValue { Type = "text", StringValue = dto.ToString("o", CultureInfo.InvariantCulture) }; + case byte[] bytes: + return new HranaValue { Type = "blob", BlobValue = bytes }; + case ReadOnlyMemory memory: + return new HranaValue { Type = "blob", BlobValue = memory.ToArray() }; + case Memory memory: + return new HranaValue { Type = "blob", BlobValue = memory.ToArray() }; + default: + throw new ArgumentException($"Unsupported argument type: {value.GetType()}"); + } + } + + public object? Decode() + { + return Type switch + { + "null" => null, + "integer" => long.Parse(StringValue!, CultureInfo.InvariantCulture), + "float" => DoubleValue ?? 0d, + "text" => StringValue, + "blob" => BlobValue ?? [], + _ => null, + }; + } +} + +internal sealed class HranaValueConverter : JsonConverter +{ + public override HranaValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using var doc = JsonDocument.ParseValue(ref reader); + var root = doc.RootElement; + var type = root.GetProperty("type").GetString() ?? "null"; + + switch (type) + { + case "integer": + // The server sends the integer as a decimal string; tolerate a raw number too. + var intValue = root.GetProperty("value"); + return new HranaValue + { + Type = type, + StringValue = intValue.ValueKind == JsonValueKind.String + ? intValue.GetString() + : intValue.GetInt64().ToString(CultureInfo.InvariantCulture), + }; + case "float": + return new HranaValue { Type = type, DoubleValue = root.GetProperty("value").GetDouble() }; + case "text": + return new HranaValue { Type = type, StringValue = root.GetProperty("value").GetString() }; + case "blob": + if (root.TryGetProperty("base64", out var b64Element) && b64Element.GetString() is { } b64) + { + // The server may omit base64 padding. + var padding = (4 - b64.Length % 4) % 4; + return new HranaValue { Type = type, BlobValue = Convert.FromBase64String(b64 + new string('=', padding)) }; + } + + return new HranaValue { Type = type, BlobValue = [] }; + default: + return HranaValue.Null; + } + } + + public override void Write(Utf8JsonWriter writer, HranaValue value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString("type", value.Type); + + switch (value.Type) + { + case "integer": + case "text": + writer.WriteString("value", value.StringValue); + break; + case "float": + writer.WriteNumber("value", value.DoubleValue ?? 0d); + break; + case "blob": + writer.WriteString("base64", Convert.ToBase64String(value.BlobValue ?? [])); + break; + } + + writer.WriteEndObject(); + } +} + +internal sealed class HranaColumn +{ + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("decltype")] + public string? Decltype { get; set; } +} + +internal sealed class HranaNamedArg +{ + [JsonPropertyName("name")] + public required string Name { get; set; } + + [JsonPropertyName("value")] + public HranaValue Value { get; set; } +} + +internal sealed class HranaStatement +{ + [JsonPropertyName("sql")] + public required string Sql { get; set; } + + [JsonPropertyName("args")] + public List Args { get; set; } = []; + + [JsonPropertyName("named_args")] + public List NamedArgs { get; set; } = []; + + [JsonPropertyName("want_rows")] + public bool WantRows { get; set; } +} + +internal sealed class HranaBatchCondition +{ + [JsonPropertyName("type")] + public required string Type { get; set; } + + [JsonPropertyName("step")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public int? Step { get; set; } + + [JsonPropertyName("cond")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public HranaBatchCondition? Cond { get; set; } + + [JsonPropertyName("conds")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Conds { get; set; } + + public static HranaBatchCondition Ok(int step) => new() { Type = "ok", Step = step }; + + public static HranaBatchCondition Not(HranaBatchCondition cond) => new() { Type = "not", Cond = cond }; + + public static HranaBatchCondition And(params HranaBatchCondition[] conds) => new() { Type = "and", Conds = conds.ToList() }; +} + +internal sealed class HranaBatchStep +{ + [JsonPropertyName("stmt")] + public required HranaStatement Statement { get; set; } + + [JsonPropertyName("condition")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public HranaBatchCondition? Condition { get; set; } +} + +internal sealed class HranaBatch +{ + [JsonPropertyName("steps")] + public required List Steps { get; set; } +} + +internal sealed class HranaPipelineRequestItem +{ + [JsonPropertyName("type")] + public required string Type { get; set; } + + [JsonPropertyName("sql")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Sql { get; set; } +} + +internal sealed class HranaPipelineRequest +{ + [JsonPropertyName("baton")] + public string? Baton { get; set; } + + [JsonPropertyName("requests")] + public required List Requests { get; set; } +} + +internal sealed class HranaError +{ + [JsonPropertyName("message")] + public string? Message { get; set; } + + [JsonPropertyName("code")] + public string? Code { get; set; } +} + +internal sealed class HranaPipelineResultResponse +{ + [JsonPropertyName("type")] + public string? Type { get; set; } + + [JsonPropertyName("result")] + public JsonElement? Result { get; set; } + + [JsonPropertyName("is_autocommit")] + public bool? IsAutocommit { get; set; } +} + +internal sealed class HranaPipelineResult +{ + [JsonPropertyName("type")] + public string? Type { get; set; } + + [JsonPropertyName("response")] + public HranaPipelineResultResponse? Response { get; set; } + + [JsonPropertyName("error")] + public HranaError? Error { get; set; } +} + +internal sealed class HranaPipelineResponse +{ + [JsonPropertyName("baton")] + public string? Baton { get; set; } + + [JsonPropertyName("base_url")] + public string? BaseUrl { get; set; } + + [JsonPropertyName("results")] + public List? Results { get; set; } +} + +internal sealed class HranaCursorRequest +{ + [JsonPropertyName("baton")] + public string? Baton { get; set; } + + [JsonPropertyName("batch")] + public required HranaBatch Batch { get; set; } +} + +internal sealed class HranaCursorResponse +{ + [JsonPropertyName("baton")] + public string? Baton { get; set; } + + [JsonPropertyName("base_url")] + public string? BaseUrl { get; set; } +} + +internal sealed class HranaCursorEntry +{ + [JsonPropertyName("type")] + public string? Type { get; set; } + + [JsonPropertyName("step")] + public int? Step { get; set; } + + [JsonPropertyName("cols")] + public List? Cols { get; set; } + + [JsonPropertyName("row")] + public List? Row { get; set; } + + [JsonPropertyName("affected_row_count")] + public long? AffectedRowCount { get; set; } + + [JsonPropertyName("last_insert_rowid")] + [JsonConverter(typeof(LongFromStringOrNumberConverter))] + public long? LastInsertRowid { get; set; } + + [JsonPropertyName("error")] + public HranaError? Error { get; set; } +} + +internal sealed class HranaDescribeParam +{ + [JsonPropertyName("name")] + public string? Name { get; set; } +} + +internal sealed class HranaDescribeResult +{ + [JsonPropertyName("params")] + public List? Params { get; set; } + + [JsonPropertyName("cols")] + public List? Cols { get; set; } + + [JsonPropertyName("is_explain")] + public bool IsExplain { get; set; } + + [JsonPropertyName("is_readonly")] + public bool IsReadonly { get; set; } +} + +/// The server sends last_insert_rowid as either a JSON string or a number. +internal sealed class LongFromStringOrNumberConverter : JsonConverter +{ + public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType switch + { + JsonTokenType.Null => null, + JsonTokenType.String => long.Parse(reader.GetString()!, CultureInfo.InvariantCulture), + JsonTokenType.Number => reader.GetInt64(), + _ => throw new JsonException($"Unexpected token for last_insert_rowid: {reader.TokenType}"), + }; + } + + public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options) + { + if (value is null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteNumberValue(value.Value); + } + } +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/README.md b/bindings/dotnet/src/Turso.Serverless.Client/README.md new file mode 100644 index 000000000..a3581f8b4 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/README.md @@ -0,0 +1,66 @@ +# Turso.Serverless.Client + +Serverless database driver for [Turso Cloud](https://docs.turso.tech) using only `HttpClient` — the .NET counterpart of [`@tursodatabase/serverless`](https://www.npmjs.com/package/@tursodatabase/serverless). Connects to a database over the SQL over HTTP protocol with streaming cursor support. + +Unlike the `Turso` and `Turso.Data.Sqlite` packages, this is a pure managed HTTP client — it has no native component. + +## Getting started + +```C# +using Turso.Serverless.Client; + +await using var connection = new TursoServerlessConnection(new TursoServerlessConnectionOptions +{ + Url = Environment.GetEnvironmentVariable("TURSO_DATABASE_URL")!, + AuthToken = Environment.GetEnvironmentVariable("TURSO_AUTH_TOKEN"), +}); + +// Query with positional arguments +var users = await connection.ExecuteAsync("SELECT id, name FROM users WHERE active = ?", [1]); +foreach (var row in users.Rows) +{ + Console.WriteLine($"{row.GetInt64("id")}: {row.GetString("name")}"); +} + +// Write with named arguments +await connection.ExecuteAsync( + "INSERT INTO users (name, email) VALUES (:name, :email)", + new Dictionary { [":name"] = "Iku", [":email"] = "iku@example.com" }); + +// Atomic batch — one round trip, BEGIN/COMMIT/ROLLBACK handled server-side +await connection.BatchAsync( + [ + new TursoBatchStatement("INSERT INTO logs (msg) VALUES (?)", ["a"]), + new TursoBatchStatement("INSERT INTO logs (msg) VALUES (?)", ["b"]), + ], + TursoBatchMode.Immediate); + +// Interactive transaction +await using (var tx = await connection.BeginTransactionAsync(TursoBatchMode.Immediate)) +{ + await tx.ExecuteAsync("UPDATE accounts SET balance = balance - 10 WHERE id = ?", [1]); + await tx.ExecuteAsync("UPDATE accounts SET balance = balance + 10 WHERE id = ?", [2]); + await tx.CommitAsync(); +} +``` + +## Concurrency model + +A `TursoServerlessConnection` is **single-stream**: it runs one statement at a time. This follows from the SQL over HTTP protocol, where each request carries a baton from the previous response to sequence operations on the server. Calls made while another is in flight automatically wait for it to finish. + +For parallelism, create multiple connections — constructing one is cheap (no HTTP request is sent until the first statement executes) and `HttpClient` pools the underlying TCP/TLS connections. A shared static `HttpClient` is used by default; pass your own via the second constructor parameter to integrate with `IHttpClientFactory`. + +## Features + +- `ExecuteAsync` — single statement with positional or named arguments, full result set +- `BatchAsync` — multiple statements in one round trip, optionally atomic (`TursoBatchMode`) +- `SequenceAsync` — semicolon-separated statement scripts (schema migrations) +- `DescribeAsync` — column/parameter metadata without executing +- `BeginTransactionAsync` — interactive transactions (`await using`, rollback on dispose) +- `InTransaction` — authoritative server-side autocommit status +- Per-call or default query timeouts (`TursoTimeoutException`), cancellation tokens throughout +- Encrypted database support via `RemoteEncryptionKey` (`x-turso-encryption-key`) + +## Protocol + +The driver speaks the same protocol as the JavaScript serverless driver (`serverless/javascript`): `POST /v3/pipeline` for request/response operations and `POST /v3/cursor` for streamed (newline-delimited JSON) results. Integers map to `long`, floats to `double`, text to `string`, blobs to `byte[]`. diff --git a/bindings/dotnet/src/Turso.Serverless.Client/SqlArgs.cs b/bindings/dotnet/src/Turso.Serverless.Client/SqlArgs.cs new file mode 100644 index 000000000..1a60e5d93 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/SqlArgs.cs @@ -0,0 +1,24 @@ +namespace Turso.Serverless.Client; + +/// Encodes statement arguments into the protocol's positional/named parameter shape. +internal static class SqlArgs +{ + internal static HranaStatement ToStatement(string sql, IReadOnlyList? args, IReadOnlyDictionary? namedArgs, bool wantRows) + { + var statement = new HranaStatement { Sql = sql, WantRows = wantRows }; + + if (args is not null) + { + statement.Args = args.Select(HranaValue.Encode).ToList(); + } + + if (namedArgs is not null) + { + statement.NamedArgs = namedArgs + .Select(static pair => new HranaNamedArg { Name = pair.Key, Value = HranaValue.Encode(pair.Value) }) + .ToList(); + } + + return statement; + } +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/Turso.Serverless.Client.csproj b/bindings/dotnet/src/Turso.Serverless.Client/Turso.Serverless.Client.csproj new file mode 100644 index 000000000..8f37cc348 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/Turso.Serverless.Client.csproj @@ -0,0 +1,27 @@ + + + + Library + $(TursoTargetFrameworks) + enable + enable + Turso.Serverless.Client + + Turso.Serverless.Client + Turso Serverless Driver for .NET + Serverless database driver for Turso Cloud using only HttpClient — SQL over HTTP with streaming cursor support and no native component. The .NET counterpart of @tursodatabase/serverless. + Turso authors + turso;sqlite;database;serverless;http;hrana + MIT + https://github.com/tursodatabase/turso + https://github.com/tursodatabase/turso + git + README.md + true + $(NoWarn);1591 + + + + + + diff --git a/bindings/dotnet/src/Turso.Serverless.Client/TursoResultSet.cs b/bindings/dotnet/src/Turso.Serverless.Client/TursoResultSet.cs new file mode 100644 index 000000000..2cb466b66 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/TursoResultSet.cs @@ -0,0 +1,161 @@ +using System.Collections; +using System.Globalization; + +namespace Turso.Serverless.Client; + +/// +/// A single result row with positional and column-name access. Values are decoded to +/// (integer), (float), (text), +/// [] (blob) or null. +/// +public sealed class TursoRow : IReadOnlyList +{ + private readonly object?[] _values; + private readonly IReadOnlyList _columns; + + internal TursoRow(object?[] values, IReadOnlyList columns) + { + _values = values; + _columns = columns; + } + + public object? this[int index] => _values[index]; + + public object? this[string column] => _values[IndexOf(column)]; + + public int Count => _values.Length; + + public IReadOnlyList Columns => _columns; + + public bool IsNull(int index) => _values[index] is null; + + public bool IsNull(string column) => this[column] is null; + + public long GetInt64(int index) => Convert.ToInt64(_values[index], CultureInfo.InvariantCulture); + + public long GetInt64(string column) => Convert.ToInt64(this[column], CultureInfo.InvariantCulture); + + public double GetDouble(int index) => Convert.ToDouble(_values[index], CultureInfo.InvariantCulture); + + public double GetDouble(string column) => Convert.ToDouble(this[column], CultureInfo.InvariantCulture); + + public string? GetString(int index) => _values[index]?.ToString(); + + public string? GetString(string column) => this[column]?.ToString(); + + public byte[]? GetBytes(int index) => (byte[]?)_values[index]; + + public byte[]? GetBytes(string column) => (byte[]?)this[column]; + + public IEnumerator GetEnumerator() => ((IEnumerable)_values).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private int IndexOf(string column) + { + for (var i = 0; i < _columns.Count; i++) + { + if (string.Equals(_columns[i], column, StringComparison.OrdinalIgnoreCase)) + { + return i; + } + } + + throw new ArgumentException($"Unknown column: {column}", nameof(column)); + } +} + +/// The fully materialized result of a SQL statement. +public sealed class TursoResultSet +{ + internal TursoResultSet(IReadOnlyList columns, IReadOnlyList columnTypes, IReadOnlyList rows, long rowsAffected, long? lastInsertRowid) + { + Columns = columns; + ColumnTypes = columnTypes; + Rows = rows; + RowsAffected = rowsAffected; + LastInsertRowid = lastInsertRowid; + } + + /// Result column names, in order. + public IReadOnlyList Columns { get; } + + /// Declared column types (decltype), in column order; empty string when undeclared. + public IReadOnlyList ColumnTypes { get; } + + public IReadOnlyList Rows { get; } + + public long RowsAffected { get; } + + public long? LastInsertRowid { get; } +} + +/// Aggregate result of a Batch execution. +public sealed class TursoBatchResult +{ + internal TursoBatchResult(long rowsAffected, long? lastInsertRowid) + { + RowsAffected = rowsAffected; + LastInsertRowid = lastInsertRowid; + } + + /// Total affected rows across the batch's user statements. + public long RowsAffected { get; } + + /// Last insert rowid produced by the batch's user statements, when any. + public long? LastInsertRowid { get; } +} + +/// Column and parameter metadata of a SQL statement (the protocol's describe answer). +public sealed class TursoStatementDescription +{ + internal TursoStatementDescription(IReadOnlyList parameterNames, IReadOnlyList columns, IReadOnlyList columnTypes, bool isExplain, bool isReadonly) + { + ParameterNames = parameterNames; + Columns = columns; + ColumnTypes = columnTypes; + IsExplain = isExplain; + IsReadonly = isReadonly; + } + + public IReadOnlyList ParameterNames { get; } + + public IReadOnlyList Columns { get; } + + public IReadOnlyList ColumnTypes { get; } + + public bool IsExplain { get; } + + public bool IsReadonly { get; } +} + +/// One statement of a batch: SQL plus optional positional or named arguments. +public sealed class TursoBatchStatement +{ + public TursoBatchStatement(string sql, IReadOnlyList? args = null, IReadOnlyDictionary? namedArgs = null) + { + Sql = sql; + Args = args; + NamedArgs = namedArgs; + } + + public string Sql { get; } + + public IReadOnlyList? Args { get; } + + public IReadOnlyDictionary? NamedArgs { get; } + + public static implicit operator TursoBatchStatement(string sql) => new(sql); +} + +/// +/// Locking mode for atomic batch execution and transactions. Mirrors the JavaScript driver's +/// BatchMode / transaction(...) variants. +/// +public enum TursoBatchMode +{ + Deferred, + Immediate, + Exclusive, + Concurrent, +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessConnection.cs b/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessConnection.cs new file mode 100644 index 000000000..f49d88367 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessConnection.cs @@ -0,0 +1,238 @@ +namespace Turso.Serverless.Client; + +/// Configuration for connecting to a Turso database over HTTP. +public sealed class TursoServerlessConnectionOptions +{ + /// Database URL (https://... or libsql://...). + public required string Url { get; init; } + + /// Authentication token (optional for local development with turso dev). + public string? AuthToken { get; init; } + + /// Encryption key (base64) for an encrypted Turso Cloud database. + public string? RemoteEncryptionKey { get; init; } + + /// Default maximum query execution time before interruption. + public TimeSpan? DefaultQueryTimeout { get; init; } +} + +/// +/// A connection to a Turso database over the SQL over HTTP protocol with streaming cursor +/// support. The .NET counterpart of the JavaScript driver's Connection. +/// +/// Concurrency model. A connection is single-stream: it runs one statement at a +/// time. This follows from the protocol — each request carries a baton from the previous +/// response to sequence operations on the server, so concurrent calls would race on that baton. +/// Calls made while another is in flight automatically wait for it to finish. For parallelism, +/// create multiple connections; constructing one is cheap and no HTTP request is sent until the +/// first statement executes. +/// +public sealed class TursoServerlessConnection : IAsyncDisposable +{ + private static readonly HttpClient SharedHttpClient = new(); + + private readonly TursoServerlessConnectionOptions _options; + private readonly TursoSession _session; + private readonly SemaphoreSlim _execLock = new(1, 1); + private bool _isOpen = true; + + public TursoServerlessConnection(TursoServerlessConnectionOptions options) + : this(options, SharedHttpClient) + { + } + + /// Creates a connection using a caller-provided (not disposed by this class). + public TursoServerlessConnection(TursoServerlessConnectionOptions options, HttpClient httpClient) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(httpClient); + if (string.IsNullOrEmpty(options.Url)) + { + throw new ArgumentException("invalid config: url is required", nameof(options)); + } + + _options = options; + _session = new TursoSession(options, httpClient); + } + + /// + /// Whether the connection is currently inside a transaction, as reported by the server or + /// established by a successful cursor transaction-control statement. + /// + public bool InTransaction => _session.InTransaction; + + /// Executes a SQL statement with optional positional arguments and returns the full result set. + public Task ExecuteAsync(string sql, IReadOnlyList? args = null, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default) + { + return LockedExecuteAsync(SqlArgs.ToStatement(sql, args, namedArgs: null, wantRows: true), queryTimeout, cancellationToken); + } + + /// Executes a SQL statement with named arguments (e.g. :name, @name, $name) and returns the full result set. + public Task ExecuteAsync(string sql, IReadOnlyDictionary namedArgs, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default) + { + return LockedExecuteAsync(SqlArgs.ToStatement(sql, args: null, namedArgs, wantRows: true), queryTimeout, cancellationToken); + } + + /// + /// Executes multiple SQL statements in one round trip. When is set, + /// the batch runs atomically: the request also carries BEGIN/COMMIT/ROLLBACK + /// steps gated on server-side conditions. When omitted, the statements run as-is under + /// autocommit (or whatever transaction is already active on this stream). + /// + public async Task BatchAsync(IReadOnlyList statements, TursoBatchMode? mode = null, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default) + { + var encoded = statements.Select(static s => SqlArgs.ToStatement(s.Sql, s.Args, s.NamedArgs, wantRows: false)).ToList(); + + await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ThrowIfClosed(); + var effectiveMode = _session.InTransaction ? null : mode; + return await _session.BatchAsync(encoded, effectiveMode, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false); + } + finally + { + _execLock.Release(); + } + } + + /// Executes a sequence of SQL statements separated by semicolons (no result rows). + public async Task SequenceAsync(string sql, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default) + { + await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ThrowIfClosed(); + await _session.SequenceAsync(sql, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false); + } + finally + { + _execLock.Release(); + } + } + + /// Describes a SQL statement: column metadata and parameter names, without executing it. + public async Task DescribeAsync(string sql, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default) + { + await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ThrowIfClosed(); + return await _session.DescribeAsync(sql, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false); + } + finally + { + _execLock.Release(); + } + } + + /// + /// Begins an interactive transaction on this connection's stream. Dispose without committing + /// to roll back. + /// + public async Task BeginTransactionAsync(TursoBatchMode mode = TursoBatchMode.Deferred, CancellationToken cancellationToken = default) + { + await ExecuteAsync($"BEGIN {mode.ToString().ToUpperInvariant()}", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false); + return new TursoServerlessTransaction(this); + } + + /// Closes the connection, releasing the server-side stream. + public async Task CloseAsync() + { + await _execLock.WaitAsync().ConfigureAwait(false); + try + { + if (!_isOpen) + { + return; + } + + _isOpen = false; + await _session.CloseAsync().ConfigureAwait(false); + } + finally + { + _execLock.Release(); + } + } + + public async ValueTask DisposeAsync() + { + await CloseAsync().ConfigureAwait(false); + } + + private async Task LockedExecuteAsync(HranaStatement statement, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ThrowIfClosed(); + return await _session.ExecuteAsync(statement.Sql, statement, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false); + } + finally + { + _execLock.Release(); + } + } + + private void ThrowIfClosed() + { + if (!_isOpen) + { + throw new InvalidOperationException("The database connection is not open"); + } + } +} + +/// +/// An interactive transaction on a . Statements executed on +/// the owning connection while the transaction is open participate in it (the protocol stream is +/// the transaction scope). Dispose without committing to roll back. +/// +public sealed class TursoServerlessTransaction : IAsyncDisposable +{ + private readonly TursoServerlessConnection _connection; + private bool _completed; + + internal TursoServerlessTransaction(TursoServerlessConnection connection) + { + _connection = connection; + } + + public Task ExecuteAsync(string sql, IReadOnlyList? args = null, CancellationToken cancellationToken = default) + { + return _connection.ExecuteAsync(sql, args, queryTimeout: null, cancellationToken); + } + + public Task ExecuteAsync(string sql, IReadOnlyDictionary namedArgs, CancellationToken cancellationToken = default) + { + return _connection.ExecuteAsync(sql, namedArgs, queryTimeout: null, cancellationToken); + } + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + await _connection.ExecuteAsync("COMMIT", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false); + _completed = true; + } + + public async Task RollbackAsync(CancellationToken cancellationToken = default) + { + await _connection.ExecuteAsync("ROLLBACK", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false); + _completed = true; + } + + public async ValueTask DisposeAsync() + { + if (!_completed && _connection.InTransaction) + { + try + { + await RollbackAsync().ConfigureAwait(false); + } + catch + { + // Best-effort rollback on dispose; the server also rolls back when the stream expires. + } + } + } +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessException.cs b/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessException.cs new file mode 100644 index 000000000..27e4a85e0 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/TursoServerlessException.cs @@ -0,0 +1,28 @@ +namespace Turso.Serverless.Client; + +/// +/// Error reported by the Turso server or the SQL over HTTP transport. +/// The .NET counterpart of the JavaScript driver's DatabaseError. +/// +public class TursoServerlessException : Exception +{ + /// Machine-readable error code (e.g. SQLITE_CONSTRAINT), when the server provided one. + public string? Code { get; } + + public TursoServerlessException(string message, string? code = null, Exception? innerException = null) + : base(message, innerException) + { + Code = code; + } +} + +/// +/// Thrown when a query exceeds the configured timeout. is TIMEOUT. +/// +public sealed class TursoTimeoutException : TursoServerlessException +{ + public TursoTimeoutException(string message = "Query timed out", Exception? innerException = null) + : base(message, "TIMEOUT", innerException) + { + } +} diff --git a/bindings/dotnet/src/Turso.Serverless.Client/TursoSession.cs b/bindings/dotnet/src/Turso.Serverless.Client/TursoSession.cs new file mode 100644 index 000000000..de2530889 --- /dev/null +++ b/bindings/dotnet/src/Turso.Serverless.Client/TursoSession.cs @@ -0,0 +1,474 @@ +using System.Text.Json; + +namespace Turso.Serverless.Client; + +/// +/// A database session managing the SQL over HTTP connection state (baton, base URL and +/// transaction status). Port of serverless/javascript/src/session.ts. +/// +internal sealed class TursoSession +{ + private readonly TursoServerlessConnectionOptions _options; + private readonly HttpClient _httpClient; + + private string? _baton; + private string _baseUrl; + + // Cached autocommit status from the server's last `get_autocommit` answer or a successful + // cursor transaction-control statement. A fresh connection is in autocommit. + private bool _autocommit = true; + + internal TursoSession(TursoServerlessConnectionOptions options, HttpClient httpClient) + { + _options = options; + _httpClient = httpClient; + _baseUrl = NormalizeUrl(options.Url); + } + + /// + /// Whether the connection is currently inside a transaction, derived from the server's + /// authoritative get_autocommit answer or the last successful cursor transaction-control + /// statement. A non-null baton does NOT imply a transaction — the server also keeps the stream + /// open for other state. + /// + internal bool InTransaction => !_autocommit; + + internal async Task DescribeAsync(string sql, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + var request = new HranaPipelineRequest + { + Baton = _baton, + Requests = + [ + new HranaPipelineRequestItem { Type = "describe", Sql = sql }, + new HranaPipelineRequestItem { Type = "get_autocommit" }, + ], + }; + + var response = await RunPipelineAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false); + + if (response.Results is [var result, ..]) + { + if (result.Type == "error") + { + throw new TursoServerlessException(result.Error?.Message ?? "Describe execution failed", result.Error?.Code); + } + + if (result.Response is { Type: "describe", Result: { } resultElement }) + { + var describe = resultElement.Deserialize(new JsonSerializerOptions(JsonSerializerDefaults.Web)); + if (describe is not null) + { + return new TursoStatementDescription( + parameterNames: describe.Params?.Select(static p => p.Name ?? "").ToArray() ?? [], + columns: describe.Cols?.Select(static c => c.Name ?? "").ToArray() ?? [], + columnTypes: describe.Cols?.Select(static c => c.Decltype ?? "").ToArray() ?? [], + isExplain: describe.IsExplain, + isReadonly: describe.IsReadonly); + } + } + } + + throw new TursoServerlessException("Unexpected describe response"); + } + + internal async Task ExecuteAsync(string sql, HranaStatement statement, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + var request = new HranaCursorRequest + { + Baton = _baton, + Batch = new HranaBatch { Steps = [new HranaBatchStep { Statement = statement }] }, + }; + + var entries = await RunCursorAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false); + + var columns = new List(); + var columnTypes = new List(); + var rows = new List(); + var rowsAffected = 0L; + long? lastInsertRowid = null; + IReadOnlyList? rowColumns = null; + + await foreach (var entry in entries.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + switch (entry.Type) + { + case "step_begin": + if (entry.Cols is not null) + { + columns = entry.Cols.Select(static c => c.Name ?? "").ToList(); + columnTypes = entry.Cols.Select(static c => c.Decltype ?? "").ToList(); + rowColumns = columns; + } + + break; + case "row": + if (entry.Row is not null) + { + var values = entry.Row.Select(static v => v.Decode()).ToArray(); + rows.Add(new TursoRow(values, rowColumns ?? [])); + } + + break; + case "step_end": + if (entry.AffectedRowCount is { } affected) + { + rowsAffected = affected; + } + + if (entry.LastInsertRowid is { } rowid) + { + lastInsertRowid = rowid; + } + + break; + case "step_error": + case "error": + throw new TursoServerlessException(entry.Error?.Message ?? "SQL execution failed", entry.Error?.Code); + } + } + + UpdateAutocommitForTransactionControlStatement(sql); + return new TursoResultSet(columns, columnTypes, rows, rowsAffected, lastInsertRowid); + } + + internal async Task BatchAsync(IReadOnlyList statements, TursoBatchMode? mode, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + var userSteps = statements.Select(static s => new HranaBatchStep { Statement = s }).ToList(); + + List steps; + var firstUserStepIdx = 0; + var lastUserStepIdx = userSteps.Count - 1; + var beginIdx = -1; + var commitIdx = -1; + var rollbackIdx = -1; + + if (mode is null) + { + steps = userSteps; + } + else + { + // Atomic batch: BEGIN , then each user step gated on its predecessor succeeding, + // then COMMIT gated on the last user step succeeding, then ROLLBACK gated on BEGIN having + // succeeded *and* COMMIT not having succeeded. The extra ok(BEGIN) guard prevents ROLLBACK + // from aborting a transaction the caller opened on this stream out of band. + beginIdx = 0; + firstUserStepIdx = 1; + lastUserStepIdx = userSteps.Count; // 1..userSteps.Count inclusive + commitIdx = lastUserStepIdx + 1; + rollbackIdx = commitIdx + 1; + + steps = [BareStep($"BEGIN {mode.Value.ToString().ToUpperInvariant()}")]; + for (var i = 0; i < userSteps.Count; i++) + { + steps.Add(new HranaBatchStep + { + Statement = userSteps[i].Statement, + Condition = HranaBatchCondition.Ok(i == 0 ? beginIdx : firstUserStepIdx + i - 1), + }); + } + + steps.Add(new HranaBatchStep + { + Statement = BareStep("COMMIT").Statement, + Condition = HranaBatchCondition.Ok(lastUserStepIdx), + }); + steps.Add(new HranaBatchStep + { + Statement = BareStep("ROLLBACK").Statement, + Condition = HranaBatchCondition.And([ + HranaBatchCondition.Ok(beginIdx), + HranaBatchCondition.Not(HranaBatchCondition.Ok(commitIdx)), + ]), + }); + } + + var request = new HranaCursorRequest + { + Baton = _baton, + Batch = new HranaBatch { Steps = steps }, + }; + + var entries = await RunCursorAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false); + + var totalRowsAffected = 0L; + long? lastInsertRowid = null; + TursoServerlessException? deferredError = null; + + // step_end entries don't carry a step index on the wire; the server only puts `step` on + // step_begin / step_error. Track the current step ourselves so we know which step_end + // belongs to a user statement when running in atomic mode. + int? currentStep = null; + bool IsUserStep(int? step) => mode is null || (step is { } s && s >= firstUserStepIdx && s <= lastUserStepIdx); + + await foreach (var entry in entries.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + switch (entry.Type) + { + case "step_begin": + currentStep = entry.Step; + break; + case "step_end": + if (mode is null && currentStep is { } step) + { + if (step < 0 || step >= statements.Count) + { + throw new TursoServerlessException("Unexpected batch step index"); + } + + UpdateAutocommitForTransactionControlStatement(statements[step].Sql); + } + + if (IsUserStep(currentStep)) + { + if (entry.AffectedRowCount is { } affected) + { + totalRowsAffected += affected; + } + + if (entry.LastInsertRowid is { } rowid) + { + lastInsertRowid = rowid; + } + } + + currentStep = null; + break; + case "step_error": + if (mode is null) + { + throw new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code); + } + + // Atomic batch: capture the first error from BEGIN, any user step, or COMMIT and + // keep draining so ROLLBACK has a chance to clean up. Errors on the synthetic + // ROLLBACK step are suppressed — they would mask the real cause already captured. + if (deferredError is null && entry.Step != rollbackIdx) + { + deferredError = new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code); + } + + currentStep = null; + break; + case "error": + throw new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code); + } + } + + if (deferredError is not null) + { + throw deferredError; + } + + return new TursoBatchResult(totalRowsAffected, lastInsertRowid); + } + + internal async Task SequenceAsync(string sql, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + var request = new HranaPipelineRequest + { + Baton = _baton, + Requests = + [ + new HranaPipelineRequestItem { Type = "sequence", Sql = sql }, + new HranaPipelineRequestItem { Type = "get_autocommit" }, + ], + }; + + var response = await RunPipelineAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false); + + if (response.Results is [var result, ..] && result.Type == "error") + { + throw new TursoServerlessException(result.Error?.Message ?? "Sequence execution failed", result.Error?.Code); + } + } + + /// + /// Close the session: sends a close request so the server cleans up the stream, then resets local state. + /// + internal async Task CloseAsync() + { + if (_baton is not null) + { + try + { + var request = new HranaPipelineRequest + { + Baton = _baton, + Requests = [new HranaPipelineRequestItem { Type = "close" }], + }; + + await HranaHttp.ExecutePipelineAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, CancellationToken.None).ConfigureAwait(false); + } + catch + { + // Ignore errors during close — the stream might already be gone or the baton stale. + } + } + + _baton = null; + _autocommit = true; + } + + private static HranaBatchStep BareStep(string sql) + { + return new HranaBatchStep { Statement = new HranaStatement { Sql = sql, WantRows = false } }; + } + + private static string NormalizeUrl(string url) + { + return url.StartsWith("libsql://", StringComparison.OrdinalIgnoreCase) + ? string.Concat("https://", url.AsSpan("libsql://".Length)) + : url; + } + + private async Task RunPipelineAsync(HranaPipelineRequest request, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + HranaPipelineResponse response; + var callerToken = cancellationToken; + using var timeout = CreateTimeoutScope(queryTimeout, ref cancellationToken); + try + { + response = await HranaHttp.ExecutePipelineAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + _baton = null; + _autocommit = true; + throw Translate(e, timeout, callerToken); + } + + _baton = response.Baton; + if (response.BaseUrl is not null) + { + _baseUrl = response.BaseUrl; + } + + UpdateAutocommit(response); + return response; + } + + private async Task> RunCursorAsync(HranaCursorRequest request, TimeSpan? queryTimeout, CancellationToken cancellationToken) + { + // The timeout scope must survive until the entries are drained; the caller's enumeration + // observes it through the cancellation token captured by the enumerator. + var callerToken = cancellationToken; + var timeout = CreateTimeoutScope(queryTimeout, ref cancellationToken); + try + { + var (response, entries) = await HranaHttp.ExecuteCursorAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, cancellationToken).ConfigureAwait(false); + + _baton = response.Baton; + if (response.BaseUrl is not null) + { + _baseUrl = response.BaseUrl; + } + + return WrapEntries(entries, timeout, callerToken); + } + catch (Exception e) + { + _baton = null; + _autocommit = true; + var translated = Translate(e, timeout, callerToken); + timeout?.Dispose(); + throw translated; + } + } + + // callerToken is deliberately not an [EnumeratorCancellation] token: the transport already observes + // the linked token captured by the inner enumerator; this one only distinguishes a caller-initiated + // cancellation from a query timeout when translating exceptions. +#pragma warning disable CS8425 + private async IAsyncEnumerable WrapEntries(IAsyncEnumerable entries, CancellationTokenSource? timeout, CancellationToken callerToken) +#pragma warning restore CS8425 + { + using (timeout) + { + var enumerator = entries.GetAsyncEnumerator(CancellationToken.None); + await using (enumerator.ConfigureAwait(false)) + { + while (true) + { + bool moved; + try + { + moved = await enumerator.MoveNextAsync().ConfigureAwait(false); + } + catch (Exception e) + { + _baton = null; + _autocommit = true; + throw Translate(e, timeout, callerToken); + } + + if (!moved) + { + yield break; + } + + yield return enumerator.Current; + } + } + } + } + + private static CancellationTokenSource? CreateTimeoutScope(TimeSpan? queryTimeout, ref CancellationToken cancellationToken) + { + var effective = queryTimeout; + if (effective is null or { Ticks: <= 0 }) + { + return null; + } + + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(effective.Value); + cancellationToken = cts.Token; + return cts; + } + + private static Exception Translate(Exception e, CancellationTokenSource? timeout, CancellationToken callerToken) + { + // A cancellation triggered by the timeout scope — not by the caller's own token — is a query timeout. + if (e is OperationCanceledException && !callerToken.IsCancellationRequested && timeout is { IsCancellationRequested: true }) + { + return new TursoTimeoutException(innerException: e); + } + + return e; + } + + private void UpdateAutocommit(HranaPipelineResponse response) + { + if (response.Results is null) + { + return; + } + + foreach (var result in response.Results) + { + if (result.Type == "ok" && result.Response is { Type: "get_autocommit", IsAutocommit: { } isAutocommit }) + { + _autocommit = isAutocommit; + return; + } + } + } + + private void UpdateAutocommitForTransactionControlStatement(string sql) + { + var command = sql.Trim().TrimEnd(';').TrimEnd(); + if (command.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase) + && (command.Length == "BEGIN".Length || char.IsWhiteSpace(command["BEGIN".Length]))) + { + _autocommit = false; + } + else if (command.Equals("COMMIT", StringComparison.OrdinalIgnoreCase) + || command.Equals("END", StringComparison.OrdinalIgnoreCase) + || command.Equals("ROLLBACK", StringComparison.OrdinalIgnoreCase)) + { + _autocommit = true; + } + } +} diff --git a/bindings/dotnet/src/Turso.Tests/Turso.Tests.csproj b/bindings/dotnet/src/Turso.Tests/Turso.Tests.csproj index 3246a0cb6..f48b44a04 100644 --- a/bindings/dotnet/src/Turso.Tests/Turso.Tests.csproj +++ b/bindings/dotnet/src/Turso.Tests/Turso.Tests.csproj @@ -28,5 +28,7 @@ + + diff --git a/bindings/dotnet/src/Turso.Tests/TursoPlatformClientTests.cs b/bindings/dotnet/src/Turso.Tests/TursoPlatformClientTests.cs new file mode 100644 index 000000000..c77b973f9 --- /dev/null +++ b/bindings/dotnet/src/Turso.Tests/TursoPlatformClientTests.cs @@ -0,0 +1,42 @@ +using System.Text.Json; +using AwesomeAssertions; +using Turso.Platform.Client; + +namespace Turso.Tests; + +public class TursoPlatformClientTests +{ + [Test] + public void GroupExtensionsSerializeAndDeserializeBothSupportedForms() + { + var named = new NewGroup + { + Name = "test", + Location = "aws-us-east-1", + Extensions = Extensions.FromNames(["fts5", "vector"]), + }; + + var namedJson = JsonSerializer.Serialize(named); + using var namedDocument = JsonDocument.Parse(namedJson); + namedDocument.RootElement.GetProperty("extensions").EnumerateArray() + .Select(static extension => extension.GetString()) + .Should().Equal("fts5", "vector"); + + var allJson = JsonSerializer.Serialize(new NewGroup + { + Name = "test", + Location = "aws-us-east-1", + Extensions = Extensions.All, + }); + using var allDocument = JsonDocument.Parse(allJson); + allDocument.RootElement.GetProperty("extensions").GetString().Should().Be("all"); + + var all = JsonSerializer.Deserialize( + """{"name":"test","location":"aws-us-east-1","extensions":"all"}"""); + all!.Extensions.Should().BeSameAs(Extensions.All); + + var deserializedNames = JsonSerializer.Deserialize( + """{"name":"test","location":"aws-us-east-1","extensions":["fts5","vector"]}"""); + deserializedNames!.Extensions!.Names.Should().Equal("fts5", "vector"); + } +} diff --git a/bindings/dotnet/src/Turso.Tests/TursoServerlessClientTests.cs b/bindings/dotnet/src/Turso.Tests/TursoServerlessClientTests.cs new file mode 100644 index 000000000..94b3bfc7d --- /dev/null +++ b/bindings/dotnet/src/Turso.Tests/TursoServerlessClientTests.cs @@ -0,0 +1,149 @@ +using System.Net; +using System.Text.Json; +using AwesomeAssertions; +using Turso.Serverless.Client; + +namespace Turso.Tests; + +public class TursoServerlessClientTests +{ + [Test] + public async Task DisposingAnUncommittedTransactionRollsBack() + { + var handler = new ServerlessHandler(); + using var httpClient = new HttpClient(handler); + await using var connection = CreateConnection(httpClient); + + await using (var transaction = await connection.BeginTransactionAsync()) + { + connection.InTransaction.Should().BeTrue(); + } + + connection.InTransaction.Should().BeFalse(); + handler.Sql.Should().Equal("BEGIN DEFERRED", "ROLLBACK"); + } + + [Test] + public async Task BatchInsideAnInteractiveTransactionDoesNotStartANestedTransaction() + { + var handler = new ServerlessHandler(); + using var httpClient = new HttpClient(handler); + await using var connection = CreateConnection(httpClient); + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await connection.BatchAsync([new TursoBatchStatement("SELECT 1")], TursoBatchMode.Immediate); + } + + var expected = new[] { "SELECT 1" }; + handler.Batches.Should().ContainSingle(batch => batch.SequenceEqual(expected)); + } + + [Test] + public async Task RawTransactionControlInABatchUpdatesTransactionState() + { + var handler = new ServerlessHandler(); + using var httpClient = new HttpClient(handler); + await using var connection = CreateConnection(httpClient); + + await connection.BatchAsync([new TursoBatchStatement("BEGIN")]); + connection.InTransaction.Should().BeTrue(); + + await connection.BatchAsync([new TursoBatchStatement("ROLLBACK")]); + connection.InTransaction.Should().BeFalse(); + } + + [Test] + public async Task DisposingWaitsForAnActiveExecution() + { + var executionStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseExecution = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new ServerlessHandler(async (request, cancellationToken) => + { + if (request.RequestUri!.AbsolutePath == "/v3/cursor") + { + executionStarted.TrySetResult(); + await releaseExecution.Task.WaitAsync(cancellationToken); + return CursorResponse(); + } + + return PipelineResponse(); + }); + + using var httpClient = new HttpClient(handler); + var connection = CreateConnection(httpClient); + var execution = connection.ExecuteAsync("SELECT 1"); + await executionStarted.Task; + + var disposal = connection.DisposeAsync().AsTask(); + disposal.IsCompleted.Should().BeFalse(); + + releaseExecution.SetResult(); + await execution; + await disposal; + } + + private static TursoServerlessConnection CreateConnection(HttpClient httpClient) + { + return new TursoServerlessConnection( + new TursoServerlessConnectionOptions { Url = "https://example.com" }, + httpClient); + } + + private sealed class ServerlessHandler : HttpMessageHandler + { + private readonly Func>? _handler; + + internal List Sql { get; } = []; + internal List> Batches { get; } = []; + + internal ServerlessHandler(Func>? handler = null) + { + _handler = handler; + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (_handler is not null) + { + return await _handler(request, cancellationToken); + } + + if (request.RequestUri!.AbsolutePath == "/v3/cursor") + { + using var document = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(cancellationToken)); + var statements = document.RootElement.GetProperty("batch").GetProperty("steps") + .EnumerateArray() + .Select(static step => step.GetProperty("stmt").GetProperty("sql").GetString()!) + .ToArray(); + Sql.AddRange(statements); + Batches.Add(statements); + return CursorResponse(); + } + + return PipelineResponse(); + } + } + + private static HttpResponseMessage CursorResponse() + { + return JsonResponse(""" + {"baton":"baton"} + {"type":"step_begin","step":0} + {"type":"step_end","affected_row_count":0} + """); + } + + private static HttpResponseMessage PipelineResponse() + { + return JsonResponse("""{"baton":null,"results":[]}"""); + } + + private static HttpResponseMessage JsonResponse(string content) + { + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(content), + }; + } +} From 2ae71fe90295c0c995f84cfeeb908c34152101aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Moreau?= Date: Tue, 14 Jul 2026 08:31:15 -0400 Subject: [PATCH 2/2] bindings/dotnet: run NSwag on .NET 10 Align the NSwag build-time runtime with the OpenAPI schema transformation helper. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/Turso.Platform.Client/Turso.Platform.Client.csproj | 2 +- bindings/dotnet/src/Turso.Platform.Client/nswag.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj b/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj index 93de72e45..7a0afc93a 100644 --- a/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj +++ b/bindings/dotnet/src/Turso.Platform.Client/Turso.Platform.Client.csproj @@ -47,7 +47,7 @@ Outputs="$(TransformedOpenApiDocument);$(GeneratedClientSource)"> - + diff --git a/bindings/dotnet/src/Turso.Platform.Client/nswag.json b/bindings/dotnet/src/Turso.Platform.Client/nswag.json index 474f6f08c..3d4d9d77f 100644 --- a/bindings/dotnet/src/Turso.Platform.Client/nswag.json +++ b/bindings/dotnet/src/Turso.Platform.Client/nswag.json @@ -1,5 +1,5 @@ { - "runtime": "Net90", + "runtime": "Net100", "defaultVariables": null, "documentGenerator": { "fromDocument": {