diff --git a/CODEOWNERS b/CODEOWNERS
index e7fd3064a..84ceeb2ba 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -58,12 +58,15 @@
# CommunityToolkit.Aspire.RavenDB.Client
# CommunityToolkit.Aspire.Hosting.RavenDB
-
-/examples/ravendb/ @shiranshalom @aviv86 @karmeli87 @ppekrol
-/src/CommunityToolkit.Aspire.RavenDB.Client/ @shiranshalom @aviv86 @karmeli87 @ppekrol
-/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/ @shiranshalom @aviv86 @karmeli87 @ppekrol
-/src/CommunityToolkit.Aspire.Hosting.RavenDB/ @shiranshalom @aviv86 @karmeli87 @ppekrol
-/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Tests/ @shiranshalom @aviv86 @karmeli87 @ppekrol
+# CommunityToolkit.Aspire.Hosting.RavenDB.Cloud
+
+/examples/ravendb/ @ppekrol @poissoncorp @karmeli87
+/src/CommunityToolkit.Aspire.RavenDB.Client/ @ppekrol @poissoncorp @karmeli87
+/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/ @ppekrol @poissoncorp @karmeli87
+/src/CommunityToolkit.Aspire.Hosting.RavenDB/ @ppekrol @poissoncorp @karmeli87
+/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Tests/ @ppekrol @poissoncorp @karmeli87
+/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/ @ppekrol @poissoncorp @karmeli87
+/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/ @ppekrol @poissoncorp @karmeli87
# CommunityToolkit.Aspire.Hosting.PostgreSQL.Extensions
diff --git a/CommunityToolkit.Aspire.slnx b/CommunityToolkit.Aspire.slnx
index 13922544a..df2e7d5d1 100644
--- a/CommunityToolkit.Aspire.slnx
+++ b/CommunityToolkit.Aspire.slnx
@@ -188,6 +188,7 @@
+
@@ -311,6 +312,7 @@
+
@@ -396,6 +398,7 @@
+
diff --git a/README.md b/README.md
index de14bf876..50deda875 100644
--- a/README.md
+++ b/README.md
@@ -67,6 +67,7 @@ For Aspire 17, migrate Toolkit Go, Java, and Cargo-based Rust applications to th
| - **Learn More**: [`Hosting.PowerShell`](src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.PowerShell/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.PowerShell/absoluteLatest) | Run powershell scripts in-process with your Aspire AppHost, injecting aspire resources and/or object instances as variables, using the command lines tools of your choice like azure cli, azd, or any other terminal tools. |
| - **Learn More**: [`Hosting.Python.Extensions`](src/CommunityToolkit.Aspire.Hosting.Python.Extensions/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Python.Extensions/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Python.Extensions/absoluteLatest) | ⚠️ **Deprecated** — An Aspire integration for hosting Uvicorn apps. |
| - **Learn More**: [`Hosting.RavenDB`](src/CommunityToolkit.Aspire.Hosting.RavenDB/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB/absoluteLatest) | An Aspire integration leveraging the RavenDB container. |
+| - **Learn More**: [`Hosting.RavenDB.Cloud`](src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/absoluteLatest) | Publishes the Aspire RavenDB integration to RavenDB Cloud: aspire deploy creates or finds a RavenDB Cloud product and hands the applications its URL and a client certificate of their own. |
| - **Learn More**: [`Hosting.Redis.Extensions`](src/CommunityToolkit.Aspire.Hosting.Redis.Extensions/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Redis.Extensions/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Redis.Extensions/absoluteLatest) | An Aspire hosting integration for extending Redis resources with additional management tooling. |
| - **Learn More**: [`Hosting.RedPanda`](src/CommunityToolkit.Aspire.Hosting.RedPanda/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RedPanda/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.RedPanda/absoluteLatest) | An Aspire hosting package for the Redpanda Kafka-compatible streaming platform. |
| - **Learn More**: [`Hosting.Rust.Extensions`](src/CommunityToolkit.Aspire.Hosting.Rust.Extensions/README.md)
- Stable 📦: [](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Rust.Extensions/)
- Preview 📦: [)](https://nuget.org/packages/CommunityToolkit.Aspire.Hosting.Rust.Extensions/absoluteLatest) | An Aspire integration for running Rust applications with Bacon. |
diff --git a/docs/diagnostics.md b/docs/diagnostics.md
index 3ed300b3f..af865290d 100644
--- a/docs/diagnostics.md
+++ b/docs/diagnostics.md
@@ -45,3 +45,15 @@ Suppress this diagnostic only when you intentionally opt into the experimental A
Retired. This diagnostic applied only to internal Perl Dockerfile helpers and did not gate a
consumer API. The ID is reserved and must not be reused. Generated Perl Dockerfile publishing
remains preview; see the Perl integration README for its validation status.
+
+## CTASPIRERAVENDB001
+
+The RavenDB hosting integration's API for deployment packages, such as `CommunityToolkit.Aspire.Hosting.RavenDB.Cloud`, which publish a RavenDB server somewhere else than its container. It may change while those packages are previews.
+
+Current usage:
+
+- `WithPublishStrategy(...)` and `RavenDBPublishStrategy` - publish the server with a deployment package's URL instead of its container
+- `RavenDBServerResource.PublishStrategy` - the strategy in use, if any
+- `RavenDBServerResource.DatabasesToCreate` - the databases declared with `ensureCreated`, which a deployment package creates
+
+AppHosts do not call these: they call the deployment package's own method, such as `PublishAsRavenDBCloud(...)`.
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/apphost.mts b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/apphost.mts
new file mode 100644
index 000000000..29ffd2275
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/apphost.mts
@@ -0,0 +1,42 @@
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { createBuilder, RavenDBCloudDiskLayout, RavenDBCloudProvider, RavenDBCloudStorageType } from "./.aspire/modules/aspire.mjs";
+
+const builder = await createBuilder();
+const appHostDirectory = path.dirname(fileURLToPath(import.meta.url));
+const apiServiceProjectPath = path.join(
+ appHostDirectory,
+ "..",
+ "CommunityToolkit.Aspire.Hosting.RavenDB.ApiService",
+ "CommunityToolkit.Aspire.Hosting.RavenDB.ApiService.csproj",
+);
+
+// The applications run in Docker Compose; RavenDB Cloud gets them the product URL and a certificate of their own.
+await builder.addDockerComposeEnvironment("compose");
+
+const apiKey = await builder.addParameter("ravendb-cloud-api-key", { secret: true });
+
+// aspire run starts a local RavenDB container; aspire deploy finds or creates the RavenDB Cloud product.
+const ravendb = await builder.addRavenDB("ravendb")
+ .publishAsRavenDBCloud(
+ apiKey,
+ "aspire-ravendb-example",
+ async spec => {
+ await spec.development(
+ RavenDBCloudProvider.Aws,
+ "eu-central-1", // region
+ "Dev10", // instance type
+ 10, // disk size in GB
+ RavenDBCloudStorageType.SsdStandard,
+ RavenDBCloudDiskLayout.SingleDataDisk,
+ "Stable72"); // release channel
+ },
+ { configure: async cloud => { await cloud.withAllowedIps(["203.0.113.0/24"]); } });
+
+await ravendb.addDatabase("ravenDatabase", { ensureCreated: true });
+
+const apiService = await builder.addDotnetProject("apiservice", apiServiceProjectPath);
+await apiService.withReference(ravendb);
+await apiService.waitFor(ravendb);
+
+await builder.build().run();
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/aspire.config.json b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/aspire.config.json
new file mode 100644
index 000000000..8bc4d6152
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/aspire.config.json
@@ -0,0 +1,24 @@
+{
+ "appHost": {
+ "path": "apphost.mts",
+ "language": "typescript/nodejs"
+ },
+ "sdk": {
+ "version": "17.0.0"
+ },
+ "profiles": {
+ "https": {
+ "applicationUrl": "https://localhost:29751;http://localhost:28932",
+ "environmentVariables": {
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:10976",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:13320"
+ }
+ }
+ },
+ "packages": {
+ "Aspire.Hosting.Docker": "17.0.0",
+ "Aspire.Hosting.Dotnet": "17.0.0",
+ "CommunityToolkit.Aspire.Hosting.RavenDB": "../../../src/CommunityToolkit.Aspire.Hosting.RavenDB/CommunityToolkit.Aspire.Hosting.RavenDB.csproj",
+ "CommunityToolkit.Aspire.Hosting.RavenDB.Cloud": "../../../src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.csproj"
+ }
+}
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/eslint.config.mjs b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/eslint.config.mjs
new file mode 100644
index 000000000..001a84a17
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/eslint.config.mjs
@@ -0,0 +1,17 @@
+// @ts-check
+
+import { defineConfig } from 'eslint/config';
+import tseslint from 'typescript-eslint';
+
+export default defineConfig({
+ files: ['apphost.mts'],
+ extends: [tseslint.configs.base],
+ languageOptions: {
+ parserOptions: {
+ projectService: true,
+ },
+ },
+ rules: {
+ '@typescript-eslint/no-floating-promises': ['error', { checkThenables: true }],
+ },
+});
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package-lock.json b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package-lock.json
new file mode 100644
index 000000000..ebc21eea4
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package-lock.json
@@ -0,0 +1,2157 @@
+{
+ "name": "validationapphost",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "validationapphost",
+ "version": "1.0.0",
+ "dependencies": {
+ "vscode-jsonrpc": "^8.2.0"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.6",
+ "eslint": "^10.11.0",
+ "nodemon": "^3.1.14",
+ "tsx": "^4.23.15",
+ "typescript": "^5.9.3",
+ "typescript-eslint": "^8.73.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@cacheable/memory": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz",
+ "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cacheable/utils": "^2.5.0",
+ "@keyv/bigmap": "^1.3.1",
+ "hookified": "^1.15.1",
+ "keyv": "^5.6.0"
+ }
+ },
+ "node_modules/@cacheable/utils": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz",
+ "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hashery": "^1.5.1",
+ "keyv": "^5.6.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@eslint-community/eslint-utils": {
+ "version": "4.9.1",
+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
+ "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eslint-visitor-keys": "^3.4.3"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
+ }
+ },
+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/@eslint-community/regexpp": {
+ "version": "4.12.2",
+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",
+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
+ }
+ },
+ "node_modules/@eslint/config-array": {
+ "version": "0.23.5",
+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
+ "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@eslint/object-schema": "^3.0.5",
+ "debug": "^4.3.1",
+ "minimatch": "^10.2.4"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@eslint/config-helpers": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
+ "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@eslint/core": "^1.2.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@eslint/core": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz",
+ "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/json-schema": "^7.0.15"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@eslint/object-schema": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz",
+ "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@eslint/plugin-kit": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz",
+ "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@eslint/core": "^1.2.1",
+ "levn": "^0.4.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ }
+ },
+ "node_modules/@humanfs/core": {
+ "version": "0.19.2",
+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
+ "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@humanfs/types": "^0.15.0"
+ },
+ "engines": {
+ "node": ">=18.18.0"
+ }
+ },
+ "node_modules/@humanfs/node": {
+ "version": "0.16.8",
+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",
+ "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@humanfs/core": "^0.19.2",
+ "@humanfs/types": "^0.15.0",
+ "@humanwhocodes/retry": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18.18.0"
+ }
+ },
+ "node_modules/@humanfs/types": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
+ "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.18.0"
+ }
+ },
+ "node_modules/@humanwhocodes/module-importer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.22"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/nzakas"
+ }
+ },
+ "node_modules/@humanwhocodes/retry": {
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.18"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/nzakas"
+ }
+ },
+ "node_modules/@isaacs/nonrecursive-glob-match": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
+ "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0"
+ },
+ "node_modules/@keyv/bigmap": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz",
+ "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hashery": "^1.4.0",
+ "hookified": "^1.15.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "peerDependencies": {
+ "keyv": "^5.6.0"
+ }
+ },
+ "node_modules/@keyv/serialize": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz",
+ "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/esrecurse": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
+ "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/json-schema": {
+ "version": "7.0.15",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@typescript-eslint/eslint-plugin": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.73.0.tgz",
+ "integrity": "sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@eslint-community/regexpp": "^4.12.2",
+ "@typescript-eslint/scope-manager": "8.73.0",
+ "@typescript-eslint/type-utils": "8.73.0",
+ "@typescript-eslint/utils": "8.73.0",
+ "@typescript-eslint/visitor-keys": "8.73.0",
+ "ignore": "^7.0.5",
+ "natural-compare": "^1.4.0",
+ "ts-api-utils": "^2.5.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "@typescript-eslint/parser": "^8.73.0",
+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
+ "version": "7.0.14",
+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz",
+ "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/@typescript-eslint/parser": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz",
+ "integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/scope-manager": "8.73.0",
+ "@typescript-eslint/types": "8.73.0",
+ "@typescript-eslint/typescript-estree": "8.73.0",
+ "@typescript-eslint/visitor-keys": "8.73.0",
+ "debug": "^4.4.3"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/project-service": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz",
+ "integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/tsconfig-utils": "^8.73.0",
+ "@typescript-eslint/types": "^8.73.0",
+ "debug": "^4.4.3"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/scope-manager": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz",
+ "integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.73.0",
+ "@typescript-eslint/visitor-keys": "8.73.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/tsconfig-utils": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz",
+ "integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/type-utils": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.73.0.tgz",
+ "integrity": "sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.73.0",
+ "@typescript-eslint/typescript-estree": "8.73.0",
+ "@typescript-eslint/utils": "8.73.0",
+ "debug": "^4.4.3",
+ "ts-api-utils": "^2.5.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/types": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz",
+ "integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz",
+ "integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/project-service": "8.73.0",
+ "@typescript-eslint/tsconfig-utils": "8.73.0",
+ "@typescript-eslint/types": "8.73.0",
+ "@typescript-eslint/visitor-keys": "8.73.0",
+ "debug": "^4.4.3",
+ "minimatch": "^11.0.1",
+ "semver": "^7.7.3",
+ "tinyglobby": "^0.2.15",
+ "ts-api-utils": "^2.5.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev",
+ "typescript": ">=4.8.4 <6.1.0"
+ },
+ "peerDependenciesMeta": {
+ "@typescript/native": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
+ "version": "11.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+ "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/@typescript-eslint/utils": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.73.0.tgz",
+ "integrity": "sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@eslint-community/eslint-utils": "^4.9.1",
+ "@typescript-eslint/scope-manager": "8.73.0",
+ "@typescript-eslint/types": "8.73.0",
+ "@typescript-eslint/typescript-estree": "8.73.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/@typescript-eslint/visitor-keys": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz",
+ "integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.73.0",
+ "eslint-visitor-keys": "^5.0.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.16.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-jsx": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ }
+ },
+ "node_modules/ajv": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/anymatch": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/binary-extensions": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
+ "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/brace-expansion": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz",
+ "integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fill-range": "^7.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cacheable": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz",
+ "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cacheable/memory": "^2.2.0",
+ "@cacheable/utils": "^2.5.0",
+ "hookified": "^1.15.0",
+ "keyv": "^5.6.0",
+ "qified": "^0.10.1"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
+ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "anymatch": "~3.1.2",
+ "braces": "~3.0.2",
+ "glob-parent": "~5.1.2",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.6.0"
+ },
+ "engines": {
+ "node": ">= 8.10.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz",
+ "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/deep-is": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
+ }
+ },
+ "node_modules/escape-string-regexp": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/eslint": {
+ "version": "10.11.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.11.0.tgz",
+ "integrity": "sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ==",
+ "dev": true,
+ "license": "MIT",
+ "workspaces": [
+ "packages/*"
+ ],
+ "dependencies": {
+ "@eslint-community/eslint-utils": "^4.8.0",
+ "@eslint-community/regexpp": "^4.12.2",
+ "@eslint/config-array": "^0.23.5",
+ "@eslint/config-helpers": "^0.7.0",
+ "@eslint/core": "^1.2.1",
+ "@eslint/plugin-kit": "^0.7.3",
+ "@humanfs/node": "^0.16.6",
+ "@humanwhocodes/module-importer": "^1.0.1",
+ "@humanwhocodes/retry": "^0.4.2",
+ "@types/estree": "^1.0.6",
+ "ajv": "^6.14.0",
+ "cross-spawn": "^7.0.6",
+ "debug": "^4.3.2",
+ "escape-string-regexp": "^4.0.0",
+ "eslint-scope": "^9.1.2",
+ "eslint-visitor-keys": "^5.0.1",
+ "espree": "^11.2.0",
+ "esquery": "^1.7.0",
+ "esutils": "^2.0.2",
+ "fast-deep-equal": "^3.1.3",
+ "file-entry-cache": "11.1.5 || >11.1.6 <12",
+ "find-up": "^5.0.0",
+ "glob-parent": "^6.0.2",
+ "ignore": "^5.2.0",
+ "imurmurhash": "^0.1.4",
+ "is-glob": "^4.0.0",
+ "json-stable-stringify-without-jsonify": "^1.0.1",
+ "minimatch": "^10.2.5",
+ "natural-compare": "^1.4.0",
+ "optionator": "^0.9.3"
+ },
+ "bin": {
+ "eslint": "bin/eslint.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "funding": {
+ "url": "https://eslint.org/donate"
+ },
+ "peerDependencies": {
+ "jiti": "*"
+ },
+ "peerDependenciesMeta": {
+ "jiti": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/eslint-scope": {
+ "version": "9.1.2",
+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz",
+ "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@types/esrecurse": "^4.3.1",
+ "@types/estree": "^1.0.8",
+ "esrecurse": "^4.3.0",
+ "estraverse": "^5.2.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/eslint-visitor-keys": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
+ "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/eslint/node_modules/glob-parent": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/espree": {
+ "version": "11.2.0",
+ "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",
+ "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "acorn": "^8.16.0",
+ "acorn-jsx": "^5.3.2",
+ "eslint-visitor-keys": "^5.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/esquery": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",
+ "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "estraverse": "^5.1.0"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/esrecurse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "estraverse": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/esutils": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-levenshtein": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/file-entry-cache": {
+ "version": "11.1.5",
+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz",
+ "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "flat-cache": "^6.1.23"
+ }
+ },
+ "node_modules/fill-range": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/find-up": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^6.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/flat-cache": {
+ "version": "6.1.23",
+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz",
+ "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cacheable": "^2.5.0",
+ "flatted": "^3.4.2",
+ "hookified": "^1.15.0"
+ }
+ },
+ "node_modules/flatted": {
+ "version": "3.4.4",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
+ "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/glob-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hashery": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz",
+ "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hookified": "^1.15.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/hookified": {
+ "version": "1.15.1",
+ "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",
+ "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/ignore": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/ignore-by-default": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
+ "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/imurmurhash": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.19"
+ }
+ },
+ "node_modules/is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "binary-extensions": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-glob": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-extglob": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/json-stable-stringify-without-jsonify": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/keyv": {
+ "version": "5.6.0",
+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
+ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@keyv/serialize": "^1.1.1"
+ }
+ },
+ "node_modules/levn": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prelude-ls": "^1.2.1",
+ "type-check": "~0.4.0"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/locate-path": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "10.2.6",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.8"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/natural-compare": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nodemon": {
+ "version": "3.1.14",
+ "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz",
+ "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "chokidar": "^3.5.2",
+ "debug": "^4",
+ "ignore-by-default": "^1.0.1",
+ "minimatch": "^10.2.1",
+ "pstree.remy": "^1.1.8",
+ "semver": "^7.5.3",
+ "simple-update-notifier": "^2.0.0",
+ "supports-color": "^5.5.0",
+ "touch": "^3.1.0",
+ "undefsafe": "^2.0.5"
+ },
+ "bin": {
+ "nodemon": "bin/nodemon.js"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/nodemon"
+ }
+ },
+ "node_modules/normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/optionator": {
+ "version": "0.9.4",
+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "deep-is": "^0.1.3",
+ "fast-levenshtein": "^2.0.6",
+ "levn": "^0.4.1",
+ "prelude-ls": "^1.2.1",
+ "type-check": "^0.4.0",
+ "word-wrap": "^1.2.5"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/p-limit": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "yocto-queue": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/prelude-ls": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/pstree.remy": {
+ "version": "1.1.8",
+ "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
+ "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/qified": {
+ "version": "0.10.1",
+ "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz",
+ "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hookified": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/qified/node_modules/hookified": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz",
+ "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/readdirp": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "picomatch": "^2.2.1"
+ },
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/simple-update-notifier": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
+ "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.5.3"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyglobby/node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/tinyglobby/node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/touch": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz",
+ "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "nodetouch": "bin/nodetouch.js"
+ }
+ },
+ "node_modules/ts-api-utils": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
+ "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.12"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4"
+ }
+ },
+ "node_modules/tsx": {
+ "version": "4.23.15",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
+ "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.28.0"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/type-check": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prelude-ls": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/typescript-eslint": {
+ "version": "8.73.0",
+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.73.0.tgz",
+ "integrity": "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/eslint-plugin": "8.73.0",
+ "@typescript-eslint/parser": "8.73.0",
+ "@typescript-eslint/typescript-estree": "8.73.0",
+ "@typescript-eslint/utils": "8.73.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+ "typescript": ">=4.8.4 <6.1.0"
+ }
+ },
+ "node_modules/undefsafe": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
+ "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "node_modules/vscode-jsonrpc": {
+ "version": "8.2.1",
+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.1.tgz",
+ "integrity": "sha512-kdjOSJ2lLIn7r1rtrMbbNCHjyMPfRnowdKjBQ+mGq6NAW5QY2bEZC/khaC5OR8svbbjvLEaIXkOq45e2X9BIbQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/word-wrap": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/yocto-queue": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ }
+ }
+}
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package.json b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package.json
new file mode 100644
index 000000000..07d62c171
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "validationapphost",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "lint": "eslint apphost.mts",
+ "predev": "npm run lint",
+ "dev": "aspire run",
+ "prebuild": "npm run lint",
+ "build": "tsc",
+ "watch": "tsc --watch"
+ },
+ "dependencies": {
+ "vscode-jsonrpc": "^8.2.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.6",
+ "eslint": "^10.11.0",
+ "nodemon": "^3.1.14",
+ "tsx": "^4.23.15",
+ "typescript": "^5.9.3",
+ "typescript-eslint": "^8.73.0"
+ }
+}
diff --git a/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/tsconfig.json b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/tsconfig.json
new file mode 100644
index 000000000..c34e4c0b3
--- /dev/null
+++ b/examples/ravendb/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "skipLibCheck": true,
+ "outDir": "./dist",
+ "rootDir": "."
+ },
+ "include": [
+ "apphost.mts",
+ ".aspire/modules/**/*.ts"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
\ No newline at end of file
diff --git a/examples/ravendb/RavenDB.Cloud.AppHost/AppHost.cs b/examples/ravendb/RavenDB.Cloud.AppHost/AppHost.cs
new file mode 100644
index 000000000..2ccbbf85b
--- /dev/null
+++ b/examples/ravendb/RavenDB.Cloud.AppHost/AppHost.cs
@@ -0,0 +1,34 @@
+using CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+using Projects;
+
+var builder = DistributedApplication.CreateBuilder(args);
+
+// The applications run in Docker Compose; RavenDB Cloud gets them the product URL and a certificate of their own.
+builder.AddDockerComposeEnvironment("compose");
+
+var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+
+// aspire run starts a local RavenDB container; aspire deploy finds or creates the RavenDB Cloud product.
+var ravendb = builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(
+ apiKey,
+ productName: "aspire-ravendb-example",
+ RavenDBCloudSpec.Development(
+ RavenDBCloudProvider.Aws,
+ region: "eu-central-1",
+ instanceType: "Dev10",
+ diskSizeInGb: 10,
+ RavenDBCloudStorageType.SsdStandard,
+ RavenDBCloudDiskLayout.SingleDataDisk,
+ releaseChannel: "Stable72"),
+ cloud => cloud.WithAllowedIps("203.0.113.0/24"));
+
+ravendb.AddDatabase("ravenDatabase", ensureCreated: true);
+
+#pragma warning disable ASPIREDOTNETPROJECT001
+builder.AddDotnetProject("apiservice", new CommunityToolkit_Aspire_Hosting_RavenDB_ApiService().ProjectPath)
+#pragma warning restore ASPIREDOTNETPROJECT001
+ .WithReference(ravendb)
+ .WaitFor(ravendb);
+
+builder.Build().Run();
diff --git a/examples/ravendb/RavenDB.Cloud.AppHost/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.csproj b/examples/ravendb/RavenDB.Cloud.AppHost/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.csproj
new file mode 100644
index 000000000..df53598e1
--- /dev/null
+++ b/examples/ravendb/RavenDB.Cloud.AppHost/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.csproj
@@ -0,0 +1,22 @@
+
+
+
+ Exe
+ enable
+ enable
+ 4fcd02ee-860a-4d4d-9219-7e37faa3c05a
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/ravendb/RavenDB.Cloud.AppHost/Properties/launchSettings.json b/examples/ravendb/RavenDB.Cloud.AppHost/Properties/launchSettings.json
new file mode 100644
index 000000000..cce889646
--- /dev/null
+++ b/examples/ravendb/RavenDB.Cloud.AppHost/Properties/launchSettings.json
@@ -0,0 +1,13 @@
+{
+ "profiles": {
+ "RavenDB.Cloud.AppHost": {
+ "commandName": "Project",
+ "environmentVariables": {
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "\"\"",
+ "DISABLE_OTLP": "true",
+ "ASPNETCORE_URLS": "http://localhost:5000",
+ "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.csproj b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.csproj
new file mode 100644
index 000000000..3c43e5062
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.csproj
@@ -0,0 +1,32 @@
+
+
+
+ Publishes the Aspire RavenDB integration to RavenDB Cloud: aspire deploy creates or finds a RavenDB Cloud product and hands the applications its URL and a client certificate of their own.
+ hosting ravendb cloud deployment
+
+ true
+
+ true
+
+ $(NoWarn);CTASPIRERAVENDB001
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/README.md b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/README.md
new file mode 100644
index 000000000..ae5403f2a
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/README.md
@@ -0,0 +1,272 @@
+# RavenDB Cloud hosting integration
+
+Use this integration to model, configure, and orchestrate the deployment of an Aspire AppHost's RavenDB server to [RavenDB Cloud](https://cloud.ravendb.net). `aspire run` keeps starting the local RavenDB container; `aspire deploy` creates or finds a RavenDB Cloud product and hands every application that references the server the product URL and a client certificate of its own.
+
+> [!IMPORTANT]
+> This package is a preview, so its API may still change. It supports applications deployed with Docker Compose only (see [Known limitations](#known-limitations)). Follow the RavenDB Aspire announcements in [GitHub Discussions of ravendb/ravendb](https://github.com/ravendb/ravendb/discussions) to hear about changes before they land.
+
+## Getting started
+
+Install the package in your AppHost project:
+
+```shell
+aspire add CommunityToolkit.Aspire.Hosting.RavenDB.Cloud
+```
+
+### Prerequisites
+
+- **A RavenDB Cloud API key.** Create it in the RavenDB Cloud portal (see [Cloud API](https://docs.ravendb.net/cloud/cloud-api)). The key acts with the account owner's authority on every product of the account, so keep it in a secret parameter, never in source control. Keys expire after at most 12 months and RavenDB Cloud sends no reminder: note the date. `aspire deploy` asks for the key when the parameter has no value; in CI, pass it as the `Parameters__ravendb-cloud-api-key` environment variable. Aspire saves parameter values, the key included, in plain text in its deployment state on the machine that deploys (`~/.aspire/deployments`), and a saved value wins over a new one from the environment: after replacing the key, deploy once with `aspire deploy --clear-cache`.
+- **Docker Compose.** The AppHost needs a Docker Compose environment for the applications, and `aspire deploy` must run where Docker can start them.
+- **Allowed IPs.** RavenDB Cloud accepts connections only from a product's allowed IP ranges. For a product the deployment creates, list the addresses in `WithAllowedIps(...)`. For an existing product, the machine that runs `aspire deploy` (or the CI runner) and the applications' host must already be in its allowed IPs, set in the RavenDB Cloud portal. See [Network access](#network-access).
+
+## Usage example
+
+```csharp
+using CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+var builder = DistributedApplication.CreateBuilder(args);
+
+builder.AddDockerComposeEnvironment("compose");
+
+var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+
+var ravendb = builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(
+ apiKey,
+ productName: "shop-production",
+ RavenDBCloudSpec.Production(
+ RavenDBCloudProvider.Azure,
+ region: "westeurope",
+ instanceType: "P20",
+ diskSizeInGb: 128,
+ RavenDBCloudStorageType.SsdStandard,
+ RavenDBCloudDiskLayout.SingleDataDisk,
+ releaseChannel: "Stable72"),
+ cloud => cloud.WithAllowedIps("203.0.113.0/24"));
+
+var orders = ravendb.AddDatabase("orders", ensureCreated: true);
+
+builder.AddProject("api")
+ .WithReference(orders)
+ .WaitFor(orders);
+
+builder.Build().Run();
+```
+
+In a TypeScript AppHost the spec is chosen in a callback:
+
+```typescript
+const apiKey = await builder.addParameter("ravendb-cloud-api-key", { secret: true });
+
+const ravendb = await builder.addRavenDB("ravendb")
+ .publishAsRavenDBCloud(
+ apiKey,
+ "shop-production",
+ async spec => {
+ await spec.production(
+ RavenDBCloudProvider.Azure,
+ "westeurope", // region
+ "P20", // instance type
+ 128, // disk size in GB
+ RavenDBCloudStorageType.SsdStandard,
+ RavenDBCloudDiskLayout.SingleDataDisk,
+ "Stable72"); // release channel
+ },
+ { configure: async cloud => { await cloud.withAllowedIps(["203.0.113.0/24"]); } });
+```
+
+The application uses the RavenDB client integration as it does locally (`builder.AddRavenDBClient("orders")`); nothing changes in its code.
+
+To use a product that already exists, possibly shared with other AppHosts, attach to it instead. The deployment never creates, changes or terminates it:
+
+```csharp
+builder.AddRavenDB("ravendb")
+ .PublishAsExistingRavenDBCloud(apiKey, productName: "shared-production", clientName: "shop");
+```
+
+## Choosing a spec
+
+Everything that decides the cost of the product and where its data lives is explicit:
+
+- `RavenDBCloudSpec.Development(provider, region, instanceType, diskSizeInGb, storageType, diskLayout, releaseChannel, iops?, throughput?)`: one node, no automatic backups.
+- `RavenDBCloudSpec.Production(...)`, with the same parameters: three nodes and automatic backups.
+
+The region is the provider's own code, such as `eu-central-1` on AWS, `westeurope` on Azure or `europe-west3` on Google Cloud. The instance types (such as `Dev10` or `P20`) and the release channels (such as `Stable72`, which follows RavenDB 7.2) are RavenDB Cloud's; the same instance type is a different machine on each provider.
+
+The disk layout says where the data lives: `SingleDataDisk` on a data disk of its own, `RootOnly` on the instance's system disk. RavenDB Cloud decides which layouts a tier and instance type allow and refuses the others when the product is created; a product keeps its layout for life.
+
+To see what you can choose, run the plan. It checks the spec against what RavenDB Cloud offers your account in that region, and for every value that is not offered it lists the valid ones: the regions, the instance types with their vCPUs, RAM, nodes and disk sizes, and the release channels with their RavenDB versions. The list comes from RavenDB Cloud itself, so it is never out of date:
+
+```bash
+aspire do ravendb-cloud-plan-ravendb
+```
+
+```text
+release channel 'Stable99' does not exist. Available: Stable62 (RavenDB 6.2...), Stable72 (RavenDB 7.2...), ...
+instance type 'Dev99' is not offered for the Development tier in Aws eu-central-1. Offered: Dev10 (2 vCPU, ...), Dev20 (...), ...
+```
+
+## Publish, deploy and destroy
+
+| Command | What happens |
+|---|---|
+| `aspire run` | The local RavenDB container starts, as without this package. RavenDB Cloud is not contacted. |
+| `aspire do ravendb-cloud-plan-` | Shows the [plan](#the-plan-and-approving-changes) and changes nothing. |
+| `aspire publish` | Writes `docker-compose.yaml` and `.env` to `aspire-output`. They reference the product URL and the certificates through placeholders (`${RAVENDB_URL}` and one variable per application). The Cloud API is never called. |
+| `aspire deploy` | The plan runs first. Then the product is created or changed as approved, the databases declared with `ensureCreated` are created, every application gets a new certificate, the values are written to `aspire-output/.env.` (`.env.Production` by default), Docker Compose starts the applications, and the previous certificates are revoked. |
+| `aspire destroy` | Revokes this AppHost's certificates. Terminates the product only if the AppHost manages it and `TerminateOnDestroy` is set. |
+
+Locally and deployed, the same AppHost gives:
+
+| | `aspire run` | `aspire deploy` |
+|---|---|---|
+| Server | local container, unsecured | RavenDB Cloud product, TLS |
+| Application's access | everything | admin on its referenced databases only |
+| Databases with `ensureCreated` | created by the AppHost | created by the deployment |
+
+The databases declared with `ensureCreated: true` are created with as many replicas as the product has nodes. The deployment never deletes a database, also not one removed from the AppHost.
+
+### Pipeline steps
+
+For a server named `ravendb`, the integration adds these steps to Aspire's deployment pipeline; `aspire do ` runs one with the steps it needs:
+
+| Step | Runs | What it does |
+|---|---|---|
+| `ravendb-cloud-plan-ravendb` | after `process-parameters`, before `deploy-prereq` | shows the plan, and stops the deployment on a blocking line |
+| `ravendb-cloud-provision-ravendb` | after the plan | creates or changes the product, and waits until it is active |
+| `ravendb-cloud-databases-ravendb` | after provision | creates the databases declared with `ensureCreated` |
+| `ravendb-cloud-certificates-ravendb` | after the databases | issues every application its certificate |
+| `ravendb-cloud-cleanup-ravendb` | after every other deploy step, `docker compose up` included | revokes the certificates the applications no longer use |
+| `ravendb-cloud-destroy-ravendb` | in `aspire destroy` | revokes this AppHost's certificates, and terminates the product with `TerminateOnDestroy` |
+
+The URL and the certificates are deploy-time values. `aspire publish` writes them into `docker-compose.yaml` as variables named after the server and the application, such as `${RAVENDB_URL}` and `${RAVENDB_API_CERTIFICATE}`. On `aspire deploy`, Docker Compose's `prepare-` step runs after the provision and certificates steps and writes their values into `aspire-output/.env.`. The integration relies on these Aspire conventions, the step names and Docker Compose resolving deploy-time values, and its tests check both.
+
+### Destroy
+
+Terminating a product deletes its data, so `aspire destroy` terminates it only when you ask for it with `TerminateOnDestroy` in the options of `PublishAsRavenDBCloud`; it is off by default. The product is found by its name, like on every deployment, so this also applies to a product made in the portal that the AppHost took over. Before terminating it, `aspire destroy` names the product it terminates, and refuses when the tier, provider, region, release channel or instance type differ from the AppHost: the name may then belong to another environment's product. The terminated product is also hidden in the portal, which frees its name for a later deployment once RavenDB Cloud has finished terminating it. A product the AppHost attaches to with `PublishAsExistingRavenDBCloud` is never terminated. In CI, `aspire destroy` needs `--yes`.
+
+## The product
+
+### The name is the identity
+
+The product is found by its name on every deployment, from any machine, CI included: RavenDB Cloud keeps no metadata of ours, so the name is all a deployment has. The name is used exactly as given and must be unique in the account (two live products with the same name stop the deployment). RavenDB Cloud keeps the name of a terminated product taken until the product is hidden in the portal; the plan stops with `name` when that blocks creating the product.
+
+Give every environment a product name of its own, for example from the environment's name:
+
+```csharp
+builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(apiKey, $"shop-{builder.Environment.EnvironmentName.ToLowerInvariant()}", spec);
+```
+
+Two environments that use one name share one product: a deployment of one changes the product the other uses.
+
+Renaming the product in the AppHost creates a new product; the old one keeps running and keeps costing until you terminate it in the portal. To move to another tier, provider or region, which RavenDB Cloud cannot change, create a product under a new name and move the data (see [Cloud: Migration](https://docs.ravendb.net/cloud/cloud-migration)).
+
+A new product's URL is `https://a..`. The subdomain comes from the product name (up to 13 letters, digits and dashes; a longer name is shortened and given a short hash) unless you choose it with `Subdomain` in the options.
+
+### Managed or attached
+
+- `PublishAsRavenDBCloud(apiKey, productName, spec)`: the AppHost owns the product. A deployment creates it from the spec when there is none, and keeps it to the spec.
+- `PublishAsExistingRavenDBCloud(apiKey, productName, clientName)`: the product exists and other AppHosts may use it too. A missing product stops the deployment. `clientName` keeps this AppHost's certificates apart from the other clients' ones; two environments of one AppHost on one product need different client names.
+
+Attaching is what the AppHost declares, not a permission: the API key can manage every product of the account, whatever the AppHost says. Give the key only to people and pipelines that may manage all products of the account.
+
+## The plan and approving changes
+
+Every deployment starts with a plan, before anything is built or changed. The plan shows one line per decision:
+
+- `create`: there is no product with the name; it is created from the spec.
+- `name`: a terminated product, or one still being terminated, holds the name.
+- `no changes`: the product matches the spec.
+- `change`: the product differs in something the Cloud API can change (instance type, disk size, storage type, IOPS, throughput). The deployment stops unless the change is approved.
+- `impossible`: the tier, the provider, the region, the release channel or the disk layout differ, the product's disk is larger than the AppHost's, which happens when RavenDB Cloud grows a disk that fills up, or the AppHost asks for a disk size RavenDB Cloud does not grow this disk to. RavenDB Cloud cannot change these, so the deployment always stops.
+
+The disk sizes the plan lists for an instance type are the ones a new product chooses from. An existing disk keeps its size, also one RavenDB Cloud grew past that list, and grows only to the sizes RavenDB Cloud lists for that disk.
+- `other certificates`: certificates on the product that this AppHost does not issue, such as other AppHosts' ones, which the deployment leaves alone.
+- `allowed IPs`, `wide allowed IPs`, `unreachable`: see [Network access](#network-access).
+- `missing`: the attached product does not exist.
+- `error`, `awaiting payment`: RavenDB Cloud could not set the product up, or waits for a payment. See the portal.
+- `no target`: an application is not deployed with Docker Compose, or has more than one compute environment (see [Known limitations](#known-limitations)).
+
+Approve changes with the `RavenDB__Cloud__ApproveChanges` environment variable:
+
+```bash
+RavenDB__Cloud__ApproveChanges=true aspire deploy
+```
+
+The deployment reads it only from the environment of the process that runs it, never from `appsettings.json`, user secrets or the AppHost, so no committed file can approve future changes. In CI, set it only in a manually approved job, so that a change of the AppHost never resizes a paid product without a person looking at the plan.
+
+## Network access
+
+RavenDB Cloud accepts connections only from the product's allowed IP ranges, and the Cloud API cannot change them once the product exists. Declare them with `WithAllowedIps(...)`:
+
+- the machine that runs `aspire deploy`, or your CI runner's outbound addresses: the deployment creates databases and certificates on the product;
+- the outbound addresses of the host that runs the applications.
+
+Keep the ranges narrow: an address outside them cannot reach the product at all, while one inside them is stopped only by the certificates. The plan warns with `wide allowed IPs` about an IPv4 range wider than /16 or an IPv6 range wider than /48.
+
+A product the deployment creates gets these ranges. On every deployment the plan checks that each declared range is allowed on the product and stops with `allowed IPs: ... not allowed`, naming the missing ones, which you then add in the RavenDB Cloud portal. For an attached product, the product's owner allows them. When the machine that deploys cannot connect to an existing product, the plan stops with `unreachable`.
+
+Right after the product is created or changed, RavenDB Cloud reports it active a little before it accepts connections: the deployment waits for it, five minutes at most. RavenDB Cloud drops traffic from addresses it does not allow instead of refusing it, so a missing address looks the same as a node that is still starting: check the list before the first deployment, because a new product is created before anything can connect to it.
+
+## What the applications get
+
+Every resource that references the server or one of its databases gets:
+
+- `ConnectionStrings__`: the URLs of the product's nodes, separated by commas, so that the application reaches the cluster while one node is down (and the database);
+- `Aspire__RavenDB__Client____CertificateBase64`: its own client certificate, as base64-encoded .pfx content, which the RavenDB client integration reads, under the same name as the connection string, also one renamed with `WithReference(db, connectionName: ...)`. When the application uses no other RavenDB server, the certificate also goes to `Aspire__RavenDB__Client__CertificateBase64`. Applications in other languages can read the same variables.
+
+The certificate grants admin access to the databases the application references, and nothing else. The databases themselves are created by the deployment, from `AddDatabase(..., ensureCreated: true)` in the AppHost; an application that sets `CreateDatabase` in the client settings still starts, since its database already exists. An application that creates other databases while it runs needs a certificate with wider access: create one in the Studio with access to just what it needs, and set it in the application with `AddRavenDBClient(..., settings => settings.Certificate = ...)`, which takes precedence over the certificate the deployment delivers.
+
+Admin access to a database includes its ongoing tasks: an application can create an ETL or a periodic backup that sends the database's data elsewhere, and such a task keeps running after the application's certificate is revoked. Check the database's ongoing tasks in the Studio when an application's certificate may have leaked.
+
+Every deployment issues new certificates; the previous ones are revoked once the applications run with the new ones. RavenDB issues them valid for five years, but a certificate lives only until the next deployment, and nothing on disk has to be kept between deployments. To revoke a certificate that may have leaked, deploy again. The certificates are named `aspire.` for a managed product and `aspire..` for an attached one.
+
+With Docker Compose the values are written to `aspire-output/.env.` on the machine that runs `aspire deploy`, in plain text like any other parameter: protect that machine, keep `aspire-output/` in `.gitignore`, and do not upload it as a CI artifact.
+
+## Continuous deployment
+
+```yaml
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ concurrency: deploy-production
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ - run: dotnet tool install -g Aspire.Cli
+ - run: aspire deploy --non-interactive
+ env:
+ Parameters__ravendb-cloud-api-key: ${{ secrets.RAVENDB_CLOUD_API_KEY }}
+```
+
+`aspire deploy` starts the applications with `docker compose up` on the Docker the runner talks to, so the runner needs Docker, and its outbound addresses must be in the product's allowed IP ranges. GitHub-hosted runners have no fixed addresses: use a runner with a static outbound address (self-hosted, or a larger GitHub runner with a static IP). `concurrency` keeps two runs from deploying at once, so one does not revoke the certificates the other just issued. Run a deployment that approves changes in a separate job with a manual approval.
+
+## Known limitations
+
+- The applications that use the server are deployed with Docker Compose for now, as their only compute environment. Elsewhere the plan stops with `no target`, because the certificate would not travel as a secret: Azure Container Apps and App Service would carry it as a plain template parameter, visible in the deployment history. Support for Azure Container Apps through Azure Key Vault is planned.
+- RavenDB Cloud creates free products only in the portal. To use one, attach to it with `PublishAsExistingRavenDBCloud`.
+
+## Troubleshooting
+
+| What you see | Why | What to do |
+|---|---|---|
+| `allowed IPs: ... not allowed` | A declared range is not allowed on the product | Add it in the RavenDB Cloud portal and deploy again |
+| `unreachable`, or "did not answer for 00:05:00" | This machine's address is not allowed on the product | Add the machine's or CI runner's outbound address in the portal |
+| `change ...` stops the deployment | The AppHost's spec differs from the product | Review the plan, then deploy with `RavenDB__Cloud__ApproveChanges=true` |
+| `impossible ...` | Tier, provider, region, release channel or disk layout differ | Change the AppHost back, or create a product under a new name and migrate |
+| `impossible: disk ...` | RavenDB Cloud grew the disk when it filled up, and a disk cannot shrink; or this disk does not grow to the size in the AppHost | Set the disk size in the AppHost to the size shown, or to one of the sizes listed |
+| `name ...` | A terminated product still holds the name | Wait until it is terminated, or hide it in the portal |
+| `aspire destroy` says the product does not match the AppHost | The product with that name is not the one the AppHost describes, for example another environment's | Give each environment a product name of its own, or make the AppHost describe the product |
+| The Cloud API answers 401 | The API key expired (keys last at most 12 months) or was revoked, or Aspire still uses an old key from its deployment state | Create a new key, update the secret, and deploy once with `aspire deploy --clear-cache` |
+| "The SSL connection could not be established" | Something between this machine and RavenDB Cloud replaces its certificate, such as a TLS-inspecting proxy | Let the machine reach RavenDB Cloud directly, or trust that proxy's CA |
+| The application gets 403 from RavenDB | The operation needs more than admin access to its own databases | Give the application a certificate of its own for that (see [What the applications get](#what-the-applications-get)) |
+
+## Additional documentation
+
+- https://docs.ravendb.net/cloud/cloud-overview
+- https://learn.microsoft.com/dotnet/aspire/community-toolkit/ravendb
+
+## Feedback & contributing
+
+https://github.com/CommunityToolkit/Aspire
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudApiClient.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudApiClient.cs
new file mode 100644
index 000000000..294b10af3
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudApiClient.cs
@@ -0,0 +1,366 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+/// Creates instances; replaced in tests.
+internal interface IRavenDBCloudApiClientFactory
+{
+ RavenDBCloudApiClient Create(string endpoint, string apiKey);
+}
+
+/// Creates the clients of the real Cloud API: no redirects, and a two-minute timeout per request.
+internal sealed class RavenDBCloudApiClientFactory : IRavenDBCloudApiClientFactory
+{
+ // No redirects: HttpClient would send the X-Api-Key header, which has account-owner rights, to wherever they point.
+ ///
+ public RavenDBCloudApiClient Create(string endpoint, string apiKey) =>
+ new(new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromMinutes(2) }, endpoint, apiKey, ownsHttpClient: true);
+}
+
+///
+/// Client for the RavenDB Cloud API v1 (https://api.cloud.ravendb.net/api/v1/swagger.json). Authentication is
+/// an account-level API key sent in the X-Api-Key header.
+///
+internal sealed class RavenDBCloudApiClient : IDisposable
+{
+ private static readonly JsonSerializerOptions s_json = new(JsonSerializerDefaults.Web)
+ {
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ };
+
+ private readonly HttpClient _http;
+ private readonly bool _ownsHttpClient;
+
+ public RavenDBCloudApiClient(HttpClient http, string endpoint, string apiKey, bool ownsHttpClient = false)
+ {
+ _http = http;
+ _ownsHttpClient = ownsHttpClient;
+
+ _http.BaseAddress = new Uri(endpoint.TrimEnd('/') + "/");
+ _http.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
+ _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // The Cloud API's gateway answers requests without a User-Agent, which HttpClient does not send, with 403.
+ _http.DefaultRequestHeaders.UserAgent.Add(UserAgent);
+ }
+
+ /// Delay before the first retry, doubled for each further one; shortened in tests.
+ internal TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(1);
+
+ private const int MaxAttempts = 5;
+
+ /// The User-Agent of every request, with the package version; the API's gateway refuses requests without one.
+ internal static ProductInfoHeaderValue UserAgent { get; } = new(
+ "CommunityToolkit.Aspire.Hosting.RavenDB.Cloud",
+ typeof(RavenDBCloudApiClient).Assembly.GetName().Version?.ToString(3) ?? "1.0.0");
+
+ /// GET /api/v1/products/list.
+ public async Task> ListProductsAsync(CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync("api/v1/products/list", cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "list products", cancellationToken).ConfigureAwait(false);
+
+ var list = await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false);
+
+ return list?.Items ?? [];
+ }
+
+ /// GET /api/v1/products/details/{id}; when the product is gone.
+ public async Task GetProductAsync(string productId, CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync($"api/v1/products/details/{Uri.EscapeDataString(productId)}", cancellationToken).ConfigureAwait(false);
+
+ if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Gone)
+ {
+ return null;
+ }
+
+ await EnsureSuccessAsync(response, "get product details", cancellationToken).ConfigureAwait(false);
+
+ return await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// POST /api/v1/products/create; returns the new product id.
+ public async Task CreateProductAsync(ProductCreateRequest request, CancellationToken cancellationToken)
+ {
+ // Not retried on a server error: the product may have been created, and the next deployment finds it by name.
+ using var response = await SendAsync(() => Post("api/v1/products/create", request), idempotent: false, cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "create the product", cancellationToken).ConfigureAwait(false);
+
+ var created = await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false);
+
+ return created?.ProductId ?? throw new InvalidOperationException("RavenDB Cloud did not return a product id.");
+ }
+
+ /// POST /api/v1/products/instance-type.
+ public async Task ChangeInstanceTypeAsync(string productId, string instanceType, CancellationToken cancellationToken)
+ {
+ using var response = await SendAsync(
+ () => Post("api/v1/products/instance-type", new ChangeInstanceTypeRequest(productId, instanceType)),
+ idempotent: false,
+ cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "change the instance type", cancellationToken).ConfigureAwait(false);
+ }
+
+ /// POST /api/v1/products/storage.
+ public async Task ChangeStorageAsync(ChangeStorageRequest request, CancellationToken cancellationToken)
+ {
+ using var response = await SendAsync(() => Post("api/v1/products/storage", request), idempotent: false, cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "change the storage", cancellationToken).ConfigureAwait(false);
+ }
+
+ /// GET /api/v1/products/security/certificate/{id}: the bundle with the client admin certificate.
+ public async Task GetAdminCertificateAsync(string productId, CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync($"api/v1/products/security/certificate/{Uri.EscapeDataString(productId)}", cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "download the client admin certificate", cancellationToken).ConfigureAwait(false);
+
+ return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// POST /api/v1/products/terminate/{id}, hiding the product in the portal: RavenDB Cloud keeps a product's name taken
+ /// until it is hidden, and the next deployment may want the name back. A product that is already gone is not an error.
+ ///
+ public async Task TerminateProductAsync(string productId, CancellationToken cancellationToken)
+ {
+ // Terminating twice changes nothing: a product already gone answers 404.
+ using var response = await SendAsync(
+ () => Post($"api/v1/products/terminate/{Uri.EscapeDataString(productId)}", new TerminateProductRequest(HideInPortal: true)),
+ idempotent: true,
+ cancellationToken).ConfigureAwait(false);
+
+ if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Gone)
+ {
+ return;
+ }
+
+ await EnsureSuccessAsync(response, "terminate the product", cancellationToken).ConfigureAwait(false);
+ }
+
+ /// GET /api/v1/metadata/regions/{provider}.
+ public async Task> GetRegionsAsync(string provider, CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync($"api/v1/metadata/regions/{Uri.EscapeDataString(provider)}", cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "list regions", cancellationToken).ConfigureAwait(false);
+
+ var regions = await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false);
+
+ return regions?.Names ?? [];
+ }
+
+ /// GET /api/v1/metadata/instance-types/{provider}/{region}.
+ public async Task> GetInstanceTypesAsync(string provider, string region, CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync(
+ $"api/v1/metadata/instance-types/{Uri.EscapeDataString(provider)}/{Uri.EscapeDataString(region)}",
+ cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "list instance types", cancellationToken).ConfigureAwait(false);
+
+ var types = await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false);
+
+ return types?.InstanceTypes ?? [];
+ }
+
+ /// GET /api/v1/metadata/release-channels.
+ public async Task GetReleaseChannelsAsync(CancellationToken cancellationToken)
+ {
+ using var response = await GetAsync("api/v1/metadata/release-channels", cancellationToken).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, "list release channels", cancellationToken).ConfigureAwait(false);
+
+ return await response.Content.ReadFromJsonAsync(s_json, cancellationToken).ConfigureAwait(false)
+ ?? new ReleaseChannelsResponse(null, null);
+ }
+
+ private Task GetAsync(string path, CancellationToken cancellationToken) =>
+ SendAsync(() => new HttpRequestMessage(HttpMethod.Get, path), idempotent: true, cancellationToken);
+
+ private static HttpRequestMessage Post(string path, T body) =>
+ new(HttpMethod.Post, path) { Content = JsonContent.Create(body, options: s_json) };
+
+ ///
+ /// The API accepts about one request per second and answers 429 beyond that. A 429 was not processed, so any
+ /// request is sent again; a server error or a lost connection only when sending it again changes nothing.
+ ///
+ private async Task SendAsync(Func request, bool idempotent, CancellationToken cancellationToken)
+ {
+ for (var attempt = 1; ; attempt++)
+ {
+ HttpResponseMessage response;
+
+ try
+ {
+ using var message = request();
+ response = await _http.SendAsync(message, cancellationToken).ConfigureAwait(false);
+ }
+ catch (HttpRequestException) when (idempotent && attempt < MaxAttempts)
+ {
+ await Task.Delay(RetryDelay * Math.Pow(2, attempt - 1), cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ var retry = response.StatusCode == HttpStatusCode.TooManyRequests || (idempotent && (int)response.StatusCode >= 500);
+
+ if (!retry || attempt == MaxAttempts)
+ {
+ return response;
+ }
+
+ var delay = response.Headers.RetryAfter?.Delta ?? RetryDelay * Math.Pow(2, attempt - 1);
+ response.Dispose();
+ await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private static async Task EnsureSuccessAsync(HttpResponseMessage response, string operation, CancellationToken cancellationToken)
+ {
+ if (response.IsSuccessStatusCode)
+ {
+ return;
+ }
+
+ var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+
+ var hint = response.StatusCode switch
+ {
+ HttpStatusCode.Unauthorized => " Check the RavenDB Cloud API key.",
+
+ // The API's answer when the account already holds its quota of paid products.
+ HttpStatusCode.PreconditionFailed =>
+ " The account has reached its quota of products: terminate one in the RavenDB Cloud portal, or ask support to raise the quota.",
+ _ => string.Empty,
+ };
+
+ throw new InvalidOperationException(
+ $"RavenDB Cloud API failed to {operation}: {(int)response.StatusCode} {response.ReasonPhrase}.{hint} {body}".TrimEnd());
+ }
+
+ /// Disposes the HTTP client when this client created it.
+ public void Dispose()
+ {
+ if (_ownsHttpClient)
+ {
+ _http.Dispose();
+ }
+ }
+}
+
+/// The answer of GET /api/v1/products/list.
+internal sealed record ProductListResponse(IReadOnlyList? Items);
+
+/// A product in .
+internal sealed record ProductListItem(string? Id, string? Name);
+
+/// The body of POST /api/v1/products/create.
+internal sealed record ProductCreateRequest(
+ string CloudProvider,
+ string InstanceTypeName,
+ string DisplayName,
+ string? ReleaseChannel,
+ string? SubdomainName,
+ string Tier,
+ string Region,
+ int DiskSize,
+ int? Iops,
+ double? Throughput,
+ string StorageTypeName,
+ IReadOnlyList AllowedIps,
+ string DiskLayout);
+
+/// The answer of POST /api/v1/products/create.
+internal sealed record ProductCreatedResponse(string? ProductId);
+
+/// The body of the request that changes a product's instance type.
+internal sealed record ChangeInstanceTypeRequest(string ProductId, string InstanceType);
+
+/// The body of the request that changes a product's data disk.
+internal sealed record ChangeStorageRequest(string ProductId, string StorageType, int Size, int? Iops, double? Throughput);
+
+/// The answer of GET /api/v1/products/details/{id}, the parts the deployment reads.
+internal sealed record ProductDetails(
+ string? Id,
+ string? DisplayName,
+ string? Status,
+ string? Tier,
+ string? CloudProvider,
+ string? Region,
+ string? InstanceType,
+ string? ReleaseChannel,
+ IReadOnlyList? Dns,
+ IReadOnlyList? NodeTags,
+ HardwareInfo? HardwareInfo,
+ ProductSecurity? Security);
+
+///
+/// A product's disks. One with a separate data disk, set up in the portal, reports its system disk as
+/// and the data disk as .
+///
+internal sealed record HardwareInfo(StorageInfo? Storage, StorageInfo? AdditionalStorage)
+{
+ /// The disk the data is on, which the spec describes.
+ public StorageInfo? DataDisk => AdditionalStorage ?? Storage;
+}
+
+///
+/// A disk of a product: size in GB, IOPS, throughput in MB/s, storage type, and the sizes it can grow to, which are
+/// narrower than the sizes a new product chooses from.
+///
+internal sealed record StorageInfo(int Size, int? Iops, double? Throughput, string? Type, IReadOnlyList? AvailableDiskSizes = null);
+
+/// The network settings of a product.
+internal sealed record ProductSecurity(IReadOnlyList? AllowedIps);
+
+/// The body of the request that terminates a product.
+internal sealed record TerminateProductRequest(bool HideInPortal);
+
+/// The regions a provider offers the account.
+internal sealed record RegionsResponse(IReadOnlyList? Names);
+
+/// The instance types a region offers the account.
+internal sealed record InstanceTypesResponse(IReadOnlyList? InstanceTypes);
+
+/// An instance type in .
+internal sealed record InstanceTypeItem(string? Name, string? Tier, InstanceTypeParameters? Parameters);
+
+/// What an instance type is: vCPUs, RAM in GB, nodes, and the disk sizes and storage types it offers.
+internal sealed record InstanceTypeParameters(
+ int? VirtualCpus,
+ double? Ram,
+ int? NumberOfNodes,
+ IReadOnlyList? AvailableDiskSizes,
+ IReadOnlyList? AvailableStorageTypes);
+
+/// A storage type an instance type offers.
+internal sealed record StorageTypeInfo(string? Name, IopsRange? IopsRange);
+
+/// The IOPS a storage type can be provisioned with.
+internal sealed record IopsRange(int Min, int Max);
+
+/// The release channels the account can use.
+internal sealed record ReleaseChannelsResponse(string? DefaultReleaseChannel, IReadOnlyList? ReleaseChannels);
+
+/// A release channel and the RavenDB version it is on.
+internal sealed record ReleaseChannelItem(string? Name, string? RavenVersion);
+
+/// Values of ProductStatus.
+internal static class ProductStatus
+{
+ /// Being created; it has no URL yet.
+ public const string Creating = "Creating";
+ /// Running; changes can be requested.
+ public const string Active = "Active";
+ /// Applying a change.
+ public const string DeployingChanges = "DeployingChanges";
+ /// Being terminated.
+ public const string Terminating = "Terminating";
+ /// Terminated; its name stays taken until it is hidden in the portal.
+ public const string Terminated = "Terminated";
+ /// Failed in RavenDB Cloud.
+ public const string Error = "Error";
+ /// Waiting for a payment before RavenDB Cloud creates it.
+ public const string AwaitingPayment = "AwaitingPayment";
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudBuilderExtensions.cs
new file mode 100644
index 000000000..a24169473
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudBuilderExtensions.cs
@@ -0,0 +1,269 @@
+using System.ComponentModel;
+using System.Text.RegularExpressions;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Pipelines;
+using CommunityToolkit.Aspire.Hosting.RavenDB;
+using CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+
+namespace Aspire.Hosting;
+
+///
+/// Publishes a RavenDB server to RavenDB Cloud.
+///
+public static partial class RavenDBCloudBuilderExtensions
+{
+ ///
+ /// Publishes the server to a RavenDB Cloud product this AppHost owns: aspire deploy creates it from
+ /// when there is none named , creates the databases declared
+ /// with ensureCreated, and gives every application that references the server the product URL and a client
+ /// certificate of its own. aspire run still starts the local container.
+ ///
+ ///
+ ///
+ /// Every deployment starts with a plan: it compares the product with the AppHost and stops on any difference, unless
+ /// the deployment is approved with the environment variable RavenDB__Cloud__ApproveChanges=true, in which case
+ /// it applies the changes the Cloud API can make. The approval is read from the process environment only, never from
+ /// configuration files, so it cannot be committed. aspire do ravendb-cloud-plan-<resource name> shows the plan only.
+ ///
+ ///
+ /// The product name is the product's identity: a deployment from any machine, CI included, finds the product by it.
+ /// Renaming the product in the AppHost creates a new product; the old one keeps running until it is terminated in the
+ /// portal. aspire publish never calls the Cloud API.
+ ///
+ ///
+ /// Each application gets a new certificate, with admin access to the databases it references only, on every
+ /// deployment; the previous ones are revoked once the applications run with the new ones. The URL and the certificate
+ /// reach the application as the client integration's settings, through the compute environment's own mechanism.
+ ///
+ ///
+ /// The resource builder for the RavenDB server.
+ /// A secret parameter holding a RavenDB Cloud API key. The key has account-owner rights.
+ /// The product's display name, used exactly as given; unique in the account.
+ /// What the product is made of: or .
+ /// Optional settings, such as the IP ranges allowed to reach the product.
+ /// The for the RavenDB server resource.
+ [AspireExportIgnore(Reason = "Polyglot AppHosts choose the spec with the overload that takes a RavenDBCloudSpecBuilder callback.")]
+ public static IResourceBuilder PublishAsRavenDBCloud(
+ this IResourceBuilder builder,
+ IResourceBuilder apiKey,
+ string productName,
+ RavenDBCloudSpec spec,
+ Action? configure = null)
+ {
+ ArgumentNullException.ThrowIfNull(builder);
+ ArgumentNullException.ThrowIfNull(apiKey);
+ ValidateProductName(productName);
+ ArgumentNullException.ThrowIfNull(spec);
+
+ var options = Configure(configure);
+
+ if (options.Subdomain is { } subdomain && !RavenDBCloudDeployment.IsValidSubdomain(subdomain))
+ {
+ throw new ArgumentException(
+ $"RavenDB Cloud does not accept the subdomain '{subdomain}': use up to {RavenDBCloudDeployment.MaxSubdomainLength} " +
+ "letters, digits and dashes, not starting or ending with a dash.",
+ nameof(configure));
+ }
+
+ return builder.ApplicationBuilder.ExecutionContext.IsPublishMode
+ ? Publish(builder, new RavenDBCloudDeployment(builder.Resource, apiKey.Resource, RavenDBCloudMode.Managed, productName.Trim(), spec, null, options), nameof(PublishAsRavenDBCloud))
+ : builder;
+ }
+
+ ///
+ /// Publishes the server to a RavenDB Cloud product this AppHost owns, with the product's spec chosen by
+ /// ; for polyglot AppHosts, which cannot call the factories.
+ /// See .
+ ///
+ /// The resource builder for the RavenDB server.
+ /// A secret parameter holding a RavenDB Cloud API key. The key has account-owner rights.
+ /// The product's display name, used exactly as given; unique in the account.
+ /// Calls exactly one of development or production.
+ /// Optional settings, such as the IP ranges allowed to reach the product.
+ /// The for the RavenDB server resource.
+ [AspireExport(RunSyncOnBackgroundThread = true)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static IResourceBuilder PublishAsRavenDBCloud(
+ this IResourceBuilder builder,
+ IResourceBuilder apiKey,
+ string productName,
+ Action spec,
+ Action? configure = null)
+ {
+ ArgumentNullException.ThrowIfNull(spec);
+
+ var chosen = new RavenDBCloudSpecBuilder();
+ spec(chosen);
+
+ return builder.PublishAsRavenDBCloud(
+ apiKey,
+ productName,
+ chosen.Spec ?? throw new ArgumentException(
+ "Choose the RavenDB Cloud product's spec: call development or production.",
+ nameof(spec)),
+ configure);
+ }
+
+ ///
+ /// Publishes the server to an existing RavenDB Cloud product, which other AppHosts may use too: aspire deploy
+ /// never creates, changes or terminates it. It creates the databases declared with ensureCreated and gives
+ /// every application that references the server the product URL and a client certificate of its own, named after
+ /// . aspire run still starts the local container.
+ ///
+ ///
+ /// The client name keeps this AppHost's certificates apart from those of the product's other clients: the
+ /// deployment only revokes certificates of its own client. Give each AppHost and environment that uses the product
+ /// its own client name. The product's owner allows the deploying machine and the applications' outbound addresses
+ /// in its AllowedIps.
+ ///
+ /// The resource builder for the RavenDB server.
+ /// A secret parameter holding a RavenDB Cloud API key of the account that holds the product.
+ /// The product's display name.
+ /// The name of this AppHost among the product's clients: letters, digits and dashes.
+ /// Optional settings.
+ /// The for the RavenDB server resource.
+ [AspireExport(RunSyncOnBackgroundThread = true)]
+ public static IResourceBuilder PublishAsExistingRavenDBCloud(
+ this IResourceBuilder builder,
+ IResourceBuilder apiKey,
+ string productName,
+ string clientName,
+ Action? configure = null)
+ {
+ ArgumentNullException.ThrowIfNull(builder);
+ ArgumentNullException.ThrowIfNull(apiKey);
+ ValidateProductName(productName);
+ ArgumentException.ThrowIfNullOrWhiteSpace(clientName);
+
+ if (!ClientNamePattern().IsMatch(clientName))
+ {
+ throw new ArgumentException(
+ $"'{clientName}' is not a valid client name: use letters, digits and dashes, starting with a letter or a digit.",
+ nameof(clientName));
+ }
+
+ var options = Configure(configure);
+
+ if (options.TerminateOnDestroy)
+ {
+ throw new ArgumentException(
+ "PublishAsExistingRavenDBCloud never terminates the product, so TerminateOnDestroy cannot be set.",
+ nameof(configure));
+ }
+
+ return builder.ApplicationBuilder.ExecutionContext.IsPublishMode
+ ? Publish(builder, new RavenDBCloudDeployment(builder.Resource, apiKey.Resource, RavenDBCloudMode.Attached, productName.Trim(), null, clientName, options), nameof(PublishAsExistingRavenDBCloud))
+ : builder;
+ }
+
+ private static RavenDBCloudOptions Configure(Action? configure)
+ {
+ var options = new RavenDBCloudOptions();
+ configure?.Invoke(options);
+ return options;
+ }
+
+ private static void ValidateProductName(string productName)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(productName);
+
+ if (productName.Trim().Length > RavenDBCloudDeployment.MaxProductNameLength)
+ {
+ throw new ArgumentException(
+ $"RavenDB Cloud accepts product names of up to {RavenDBCloudDeployment.MaxProductNameLength} characters.",
+ nameof(productName));
+ }
+ }
+
+ private static IResourceBuilder Publish(
+ IResourceBuilder builder,
+ RavenDBCloudDeployment deployment,
+ string method)
+ {
+ builder.ApplicationBuilder.Services.TryAddSingleton();
+ builder.ApplicationBuilder.Services.TryAddSingleton();
+ builder.ApplicationBuilder.Services.TryAddSingleton();
+
+ builder.WithPublishStrategy(new RavenDBPublishStrategy(method, ReferenceExpression.Create($"{deployment.Endpoint}")));
+
+ // Every application that uses the server gets a certificate value of its own; the deployment fills it in.
+ builder.ApplicationBuilder.Eventing.Subscribe((@event, _) =>
+ {
+ Validate(@event.Model, deployment);
+
+ foreach (var consumer in RavenDBConsumers.Find(@event.Model, builder.Resource))
+ {
+ var certificate = new RavenDBCloudCertificate(builder.Resource, consumer.Resource);
+ deployment.Certificates.Add(certificate);
+ RavenDBClientConfiguration.DeliverCertificate(consumer, builder.Resource, certificate);
+ }
+
+ CheckVariableNames(@event.Model);
+
+ return Task.CompletedTask;
+ });
+
+ return builder
+ .WithAnnotation(deployment)
+ .WithPipelineStepFactory(_ => RavenDBCloudPipelineSteps.Create(deployment))
+ .WithPipelineConfiguration(context => RavenDBCloudPipelineSteps.Configure(deployment, context));
+ }
+
+ /// What can be checked before anything runs, so a mistake never gets as far as the Cloud API.
+ private static void Validate(DistributedApplicationModel model, RavenDBCloudDeployment deployment)
+ {
+ var sameProduct = model.Resources
+ .OfType()
+ .Where(s => s != deployment.Server && s.Annotations.OfType()
+ .Any(d => string.Equals(d.ProductName, deployment.ProductName, StringComparison.OrdinalIgnoreCase)))
+ .Select(s => s.Name)
+ .ToList();
+
+ if (sameProduct.Count > 0)
+ {
+ throw new DistributedApplicationException(
+ $"RavenDB servers '{deployment.Server.Name}' and '{string.Join("', '", sameProduct)}' are published to the same " +
+ $"RavenDB Cloud product '{deployment.ProductName}'. One product backs one server: give each its own product name.");
+ }
+
+ foreach (var database in deployment.Server.Databases.Values)
+ {
+ if (!DatabaseNamePattern().IsMatch(database))
+ {
+ throw new DistributedApplicationException(
+ $"'{database}' is not a valid RavenDB database name. Use letters, digits, '_', '-' or '.'.");
+ }
+ }
+ }
+
+ ///
+ /// Docker Compose names a variable after each deploy-time value, with everything but letters and digits turned into
+ /// _: server a-b with application c and server a with application b-c would share
+ /// one, and one application would get the other's certificate.
+ ///
+ private static void CheckVariableNames(DistributedApplicationModel model)
+ {
+ var values = model.Resources
+ .SelectMany(r => r.Annotations.OfType())
+ .SelectMany(d => d.Certificates
+ .Select(c => (Value: (RavenDBCloudDeployTimeValue)c, What: $"the certificate of '{c.Consumer.Name}' for '{d.Server.Name}'"))
+ .Prepend((Value: d.Endpoint, What: $"the URL of '{d.Server.Name}'")));
+
+ foreach (var shared in values.GroupBy(v => ComposeVariable(v.Value.ValueExpression)).Where(g => g.Count() > 1))
+ {
+ throw new DistributedApplicationException(
+ $"{string.Join(" and ", shared.Select(v => v.What))} would share the Docker Compose variable {shared.Key}, so an " +
+ "application would get a value that is not its own. Rename one of the resources.");
+ }
+ }
+
+ private static string ComposeVariable(string expression) =>
+ string.Concat(expression.Trim('{', '}').Select(c => char.IsAsciiLetterOrDigit(c) ? char.ToUpperInvariant(c) : '_'));
+
+ [GeneratedRegex("^[A-Za-z0-9][A-Za-z0-9-]*$")]
+ private static partial Regex ClientNamePattern();
+
+ [GeneratedRegex("^[A-Za-z0-9_.-]+$")]
+ private static partial Regex DatabaseNamePattern();
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudCertificates.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudCertificates.cs
new file mode 100644
index 000000000..5803d740b
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudCertificates.cs
@@ -0,0 +1,203 @@
+using System.IO.Compression;
+using System.Security.Cryptography.X509Certificates;
+using Microsoft.Extensions.Logging;
+using Raven.Client.ServerWide.Operations.Certificates;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// The applications' client certificates on the product's server, reached with the client admin certificate.
+///
+///
+/// The server keeps no private keys, and a CI runner keeps no files between deployments, so a certificate cannot be
+/// reused: every deployment issues each application a new one, hands it over as a value, and revokes the previous ones
+/// once the applications run with the new ones.
+///
+internal sealed class RavenDBCloudCertificates(ILogger logger)
+{
+ /// Attempts to revoke a certificate before the deployment fails.
+ internal const int RevokeAttempts = 3;
+
+ /// Delay between two attempts to revoke a certificate; shortened in tests.
+ internal TimeSpan RevokeRetryDelay { get; init; } = TimeSpan.FromSeconds(2);
+
+ ///
+ /// Issues each application a certificate named after it, with admin access to the databases it references and to
+ /// nothing else, and sets it as the application's value.
+ ///
+ public async Task IssueAsync(
+ IRavenDBServerAdministration server,
+ RavenDBCloudDeployment deployment,
+ IReadOnlyList consumers,
+ CancellationToken cancellationToken)
+ {
+ foreach (var certificate in deployment.Certificates)
+ {
+ var databases = consumers.FirstOrDefault(c => ReferenceEquals(c.Resource, certificate.Consumer))?.Databases ?? [];
+ var name = deployment.CertificateName(certificate.Consumer);
+ var permissions = databases.ToDictionary(d => d, _ => DatabaseAccess.Admin, StringComparer.OrdinalIgnoreCase);
+
+ if (databases.Count == 0)
+ {
+ logger.LogWarning(
+ "'{Resource}' references '{Server}', which declares no database, so its certificate grants access to no " +
+ "database. Declare the databases with AddDatabase(...).",
+ certificate.Consumer.Name,
+ deployment.Server.Name);
+ }
+
+ var bundle = await server.CreateClientCertificateAsync(name, permissions, cancellationToken).ConfigureAwait(false);
+ var pfx = ExtractPfx(bundle)
+ ?? throw new InvalidOperationException($"The certificate RavenDB issued for '{certificate.Consumer.Name}' contains no .pfx file.");
+
+ certificate.Value = Convert.ToBase64String(pfx);
+ certificate.Thumbprint = GetThumbprint(pfx);
+
+ logger.LogInformation(
+ "Issued client certificate '{Name}' ({Thumbprint}) to '{Resource}' with access to {Databases}.",
+ name,
+ certificate.Thumbprint,
+ certificate.Consumer.Name,
+ databases.Count == 0 ? "no database" : string.Join(", ", databases));
+ }
+ }
+
+ ///
+ /// Revokes this AppHost's certificates other than the ones issued by this deployment: the previous ones of every
+ /// application, and those of applications that are gone. Any other certificate is left alone.
+ ///
+ public async Task RevokeReplacedAsync(IRavenDBServerAdministration server, RavenDBCloudDeployment deployment, CancellationToken cancellationToken)
+ {
+ var issued = deployment.Certificates
+ .Select(c => c.Thumbprint)
+ .OfType()
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+
+ foreach (var certificate in await GetOwnAsync(server, deployment, cancellationToken).ConfigureAwait(false))
+ {
+ if (!issued.Contains(certificate.Thumbprint))
+ {
+ await RevokeAsync(server, deployment, certificate, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ /// Revokes every certificate of this AppHost, for a product that keeps running after destroy.
+ public async Task RevokeAllAsync(IRavenDBServerAdministration server, RavenDBCloudDeployment deployment, CancellationToken cancellationToken)
+ {
+ foreach (var certificate in await GetOwnAsync(server, deployment, cancellationToken).ConfigureAwait(false))
+ {
+ await RevokeAsync(server, deployment, certificate, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ /// The names of the integration's certificates on the product that this AppHost does not issue, and so never revokes.
+ public static async Task> GetOtherClientsAsync(
+ IRavenDBServerAdministration server,
+ RavenDBCloudDeployment deployment,
+ CancellationToken cancellationToken)
+ {
+ var all = await server.GetCertificatesAsync("aspire.", cancellationToken).ConfigureAwait(false);
+
+ return [.. all.Where(c => !IsIssuedByThisAppHost(c, deployment)).Select(c => c.Name).Order(StringComparer.Ordinal)];
+ }
+
+ private static async Task> GetOwnAsync(
+ IRavenDBServerAdministration server,
+ RavenDBCloudDeployment deployment,
+ CancellationToken cancellationToken)
+ {
+ var registered = await server.GetCertificatesAsync(deployment.CertificateNamePrefix, cancellationToken).ConfigureAwait(false);
+
+ return [.. registered.Where(c => IsIssuedByThisAppHost(c, deployment))];
+ }
+
+ ///
+ /// Whether this AppHost issued : named as it names its certificates, with ValidUser
+ /// clearance and Admin on databases the server declares, nothing more. A certificate that only shares the name, such
+ /// as an Operator one made by hand in the Studio, is never revoked.
+ ///
+ internal static bool IsIssuedByThisAppHost(RegisteredCertificate certificate, RavenDBCloudDeployment deployment) =>
+ deployment.IsOwnCertificate(certificate.Name) &&
+ certificate.Clearance == SecurityClearance.ValidUser &&
+ certificate.Permissions.All(p =>
+ p.Value == DatabaseAccess.Admin &&
+ deployment.Server.Databases.Values.Contains(p.Key, StringComparer.OrdinalIgnoreCase));
+
+ private async Task RevokeAsync(
+ IRavenDBServerAdministration server,
+ RavenDBCloudDeployment deployment,
+ RegisteredCertificate certificate,
+ CancellationToken cancellationToken)
+ {
+ for (var attempt = 1; ; attempt++)
+ {
+ try
+ {
+ await server.DeleteCertificateAsync(certificate.Thumbprint, cancellationToken).ConfigureAwait(false);
+ logger.LogInformation("Revoked client certificate '{Name}' ({Thumbprint}).", certificate.Name, certificate.Thumbprint);
+ return;
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ if (attempt >= RevokeAttempts)
+ {
+ // A certificate left valid keeps its access: the deployment must not look successful.
+ throw new InvalidOperationException(
+ $"Could not revoke client certificate '{certificate.Name}' ({certificate.Thumbprint}) of RavenDB Cloud product " +
+ $"'{deployment.ProductName}' after {RevokeAttempts} attempts: {exception.Message} Revoke it in the RavenDB Studio " +
+ "(Manage Server, Certificates) or deploy again.",
+ exception);
+ }
+
+ logger.LogWarning(
+ "Could not revoke client certificate '{Name}' ({Thumbprint}), attempt {Attempt} of {Attempts}: {Message}",
+ certificate.Name,
+ certificate.Thumbprint,
+ attempt,
+ RevokeAttempts,
+ exception.Message);
+
+ await Task.Delay(RevokeRetryDelay, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ /// The certificate comes as a zip bundle (pfx and pem files) or as a bare pfx.
+ public static byte[]? ExtractPfx(byte[] bundle)
+ {
+ if (bundle.Length < 4 || bundle[0] != 'P' || bundle[1] != 'K')
+ {
+ return bundle.Length == 0 ? null : bundle;
+ }
+
+ using var archive = new ZipArchive(new MemoryStream(bundle), ZipArchiveMode.Read);
+ var entry = archive.Entries.FirstOrDefault(e => e.Name.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase));
+
+ if (entry is null)
+ {
+ return null;
+ }
+
+ using var stream = entry.Open();
+ using var buffer = new MemoryStream();
+ stream.CopyTo(buffer);
+
+ return buffer.ToArray();
+ }
+
+ /// Loads a .pfx without a password, as RavenDB issues them.
+ public static X509Certificate2 Load(byte[] pfx) =>
+#if NET9_0_OR_GREATER
+ X509CertificateLoader.LoadPkcs12(pfx, password: null);
+#else
+ new(pfx, (string?)null);
+#endif
+
+ /// The thumbprint of the certificate in a .pfx.
+ public static string GetThumbprint(byte[] pfx)
+ {
+ using var certificate = Load(pfx);
+ return certificate.Thumbprint;
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudDeployment.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudDeployment.cs
new file mode 100644
index 000000000..f240d73fc
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudDeployment.cs
@@ -0,0 +1,166 @@
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using Aspire.Hosting.ApplicationModel;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+/// Whether the AppHost owns the product or uses one that exists.
+internal enum RavenDBCloudMode
+{
+ /// PublishAsRavenDBCloud: the deployment creates the product and keeps it to its specification.
+ Managed,
+
+ /// PublishAsExistingRavenDBCloud: the product exists; the deployment never creates, changes or terminates it.
+ Attached,
+}
+
+///
+/// Attached to a published to RavenDB Cloud: what the AppHost asks for and, while
+/// the deployment runs, what it found.
+///
+internal sealed class RavenDBCloudDeployment : IResourceAnnotation
+{
+ /// The longest subdomain RavenDB Cloud accepts.
+ public const int MaxSubdomainLength = 13;
+
+ /// The longest product name RavenDB Cloud accepts.
+ public const int MaxProductNameLength = 100;
+
+ public RavenDBCloudDeployment(
+ RavenDBServerResource server,
+ ParameterResource apiKey,
+ RavenDBCloudMode mode,
+ string productName,
+ RavenDBCloudSpec? spec,
+ string? clientName,
+ RavenDBCloudOptions options)
+ {
+ Server = server;
+ ApiKey = apiKey;
+ Mode = mode;
+ ProductName = productName;
+ Spec = spec;
+ ClientName = clientName;
+ Options = options;
+ Endpoint = new RavenDBCloudEndpoint(server);
+ Subdomain = options.Subdomain ?? DeriveSubdomain(productName);
+
+ // Managed: the product belongs to this AppHost, so its applications' names are enough. Attached: other
+ // AppHosts use the product too, so the client name keeps their certificates apart. Aspire resource names have
+ // no dots, which tells the two schemes apart.
+ CertificateNamePrefix = mode == RavenDBCloudMode.Managed ? "aspire." : $"aspire.{clientName!.ToLowerInvariant()}.";
+ }
+
+ /// The server the deployment publishes.
+ public RavenDBServerResource Server { get; }
+
+ /// The parameter that holds the Cloud API key.
+ public ParameterResource ApiKey { get; }
+
+ /// Whether the AppHost manages the product or attaches to it.
+ public RavenDBCloudMode Mode { get; }
+
+ /// The display name the product is found and created by; its identity.
+ public string ProductName { get; }
+
+ /// What a managed product is made of; when attached.
+ public RavenDBCloudSpec? Spec { get; }
+
+ /// The name that keeps this AppHost's certificates apart on an attached product.
+ public string? ClientName { get; }
+
+ /// The options set in the AppHost.
+ public RavenDBCloudOptions Options { get; }
+
+ /// The subdomain a new product is created with.
+ public string Subdomain { get; }
+
+ /// The URLs of the product's nodes, separated by commas, that the applications get.
+ public RavenDBCloudEndpoint Endpoint { get; }
+
+ /// The certificate values of the applications that use the server, set when the model is complete.
+ public List Certificates { get; } = [];
+
+ /// How this AppHost's certificate names start: aspire., or aspire.<client name>. when attached.
+ public string CertificateNamePrefix { get; }
+
+ /// The name the product knows an application's certificate by.
+ public string CertificateName(IResource consumer) => (CertificateNamePrefix + consumer.Name).ToLowerInvariant();
+
+ ///
+ /// Whether a certificate on the product is one this AppHost issues: managed, aspire.<application>;
+ /// attached, aspire.<client>.<anything>. Never another client's.
+ ///
+ public bool IsOwnCertificate(string? name)
+ {
+ if (name is null || !name.StartsWith(CertificateNamePrefix, StringComparison.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+
+ return Mode == RavenDBCloudMode.Attached || !name.AsSpan(CertificateNamePrefix.Length).Contains('.');
+ }
+
+ /// Delay between two status checks while a product changes; shortened in tests.
+ public TimeSpan PollInterval { get; set; } = TimeSpan.FromSeconds(10);
+
+ /// How long a deployment waits for a new or changed product to become active; creating one takes minutes.
+ public TimeSpan ProvisioningTimeout { get; set; } = TimeSpan.FromMinutes(30);
+
+ /// How long a product that still reports Active right after a change request is given to start it.
+ public TimeSpan ChangeGracePeriod { get; set; } = TimeSpan.FromMinutes(1);
+
+ ///
+ /// How long the deployment waits for the product's server to accept connections. Right after a change the product
+ /// reports Active a little before its node answers; much longer means this machine's address is not allowed.
+ ///
+ public TimeSpan ReachableTimeout { get; set; } = TimeSpan.FromMinutes(5);
+
+ // Found while the deployment runs.
+
+ /// The product's id, once the deployment found or created it.
+ public string? ProductId { get; set; }
+
+ /// The URLs of the product's nodes.
+ public IReadOnlyList NodeUrls { get; set; } = [];
+
+ /// Nodes in the product's cluster; the replication factor of new databases.
+ public int NodeCount { get; set; } = 1;
+
+ ///
+ /// The client admin certificate of the product, downloaded once per deployment and never disposed: the RavenDB client
+ /// caches its HTTP clients per certificate thumbprint and keeps the first instance it was given, so a disposed one
+ /// breaks every later TLS handshake with the product.
+ ///
+ public X509Certificate2? AdminCertificate { get; set; }
+
+ /// The plan the deployment follows; computed by the plan step.
+ public RavenDBCloudPlan? Plan { get; set; }
+
+ ///
+ /// The product name's letters, digits and dashes; when that is too long, its beginning and a hash of the whole name,
+ /// so shop-staging and shop-production still get different subdomains.
+ ///
+ internal static string DeriveSubdomain(string productName)
+ {
+ var allowed = new string([.. productName.ToLowerInvariant().Where(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-')]).Trim('-');
+
+ if (allowed.Length is > 0 and <= MaxSubdomainLength)
+ {
+ return allowed;
+ }
+
+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(productName)))[..5].ToLowerInvariant();
+ var prefix = allowed[..Math.Min(allowed.Length, MaxSubdomainLength - hash.Length - 1)].TrimEnd('-');
+
+ return prefix.Length == 0 ? $"p{hash}" : $"{prefix}-{hash}";
+ }
+
+ /// Whether RavenDB Cloud accepts .
+ internal static bool IsValidSubdomain(string subdomain) =>
+ subdomain.Length is > 0 and <= MaxSubdomainLength &&
+ subdomain.All(c => char.IsAsciiLetterOrDigit(c) || c == '-') &&
+ !subdomain.StartsWith('-') &&
+ !subdomain.EndsWith('-');
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudEnvironment.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudEnvironment.cs
new file mode 100644
index 000000000..3a30f4cf6
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudEnvironment.cs
@@ -0,0 +1,19 @@
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// Where a deployment reads the settings that must come from the person or the CI job running it: the process
+/// environment, never configuration files, user secrets or the AppHost's code. A committed file can therefore neither
+/// approve every future change nor send the API key to another endpoint. Behind an interface for the tests.
+///
+internal interface IRavenDBCloudEnvironment
+{
+ /// The value of , or when it is not set.
+ string? Get(string variable);
+}
+
+/// The environment of the process that deploys.
+internal sealed class ProcessEnvironment : IRavenDBCloudEnvironment
+{
+ ///
+ public string? Get(string variable) => Environment.GetEnvironmentVariable(variable);
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudOptions.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudOptions.cs
new file mode 100644
index 000000000..ccb6edb27
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudOptions.cs
@@ -0,0 +1,99 @@
+using Aspire.Hosting;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+/// Cloud provider a RavenDB Cloud product runs on.
+public enum RavenDBCloudProvider
+{
+ /// Amazon Web Services.
+ Aws,
+
+ /// Microsoft Azure.
+ Azure,
+
+ /// Google Cloud Platform.
+ Gcp,
+}
+
+///
+/// RavenDB Cloud product tier. The free tier is not here: RavenDB Cloud does not create free products through its API,
+/// so attach to one created in the portal with PublishAsExistingRavenDBCloud.
+///
+public enum RavenDBCloudTier
+{
+ /// Development tier.
+ Development,
+
+ /// Production tier.
+ Production,
+}
+
+/// Storage type of a product's data disk.
+public enum RavenDBCloudStorageType
+{
+ /// Standard SSD.
+ SsdStandard,
+
+ /// Premium SSD, with provisioned IOPS and throughput where the provider offers them.
+ SsdPremium,
+}
+
+///
+/// Where a product keeps its data. RavenDB Cloud decides which layouts a tier and instance type allow, and a product
+/// keeps its layout for life: the Cloud API cannot change it.
+///
+public enum RavenDBCloudDiskLayout
+{
+ /// On the instance's system disk.
+ RootOnly,
+
+ /// On a data disk of its own, apart from the system disk.
+ SingleDataDisk,
+}
+
+///
+/// Optional settings of a server published to RavenDB Cloud. Everything that decides cost or where the data lives is
+/// in instead, which is required.
+///
+[AspireExport(ExposeProperties = true, ExposeMethods = true)]
+public sealed class RavenDBCloudOptions
+{
+ ///
+ /// IP ranges, in CIDR notation, that reach the product: the machine that runs aspire deploy (or the CI
+ /// runner), and the outbound addresses of the environment the applications run in. RavenDB Cloud rejects
+ /// everything else.
+ ///
+ ///
+ /// A product the deployment creates gets these ranges; the Cloud API requires at least one and offers no way to
+ /// change them later, so from then on they are edited in the portal. On every deployment the plan checks that each
+ /// range is allowed on the product and stops, naming the missing ones, when one is not.
+ ///
+ public IList AllowedIps { get; } = [];
+
+ ///
+ /// Subdomain of the node URLs of a product the deployment creates: up to 13 letters, digits and dashes, unique in
+ /// the account. When unset, it is derived from the product name.
+ ///
+ public string? Subdomain { get; set; }
+
+ ///
+ /// Terminates the product, found by its name, in aspire destroy. Off by default: terminating a product
+ /// deletes its data. Only for PublishAsRavenDBCloud: a product the AppHost attaches to is never terminated.
+ ///
+ public bool TerminateOnDestroy { get; set; }
+
+ /// Allows the given IP ranges to reach the product. See .
+ /// IP ranges in CIDR notation, such as 203.0.113.0/24.
+ /// These options, for chaining.
+ public RavenDBCloudOptions WithAllowedIps(params string[] allowedIps)
+ {
+ ArgumentNullException.ThrowIfNull(allowedIps);
+
+ foreach (var range in allowedIps)
+ {
+ AllowedIps.Add(range);
+ }
+
+ return this;
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPipelineSteps.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPipelineSteps.cs
new file mode 100644
index 000000000..12559578d
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPipelineSteps.cs
@@ -0,0 +1,399 @@
+using Aspire.Hosting;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Pipelines;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// The deploy and destroy steps of a server published to RavenDB Cloud. Their names are part of the public contract:
+/// aspire do ravendb-cloud-plan-<name> shows the plan without changing anything.
+///
+internal static class RavenDBCloudPipelineSteps
+{
+ private const string StepPrefix = "ravendb-cloud-";
+
+ /// The step that computes and shows the plan for .
+ public static string PlanStepName(RavenDBServerResource server) => $"{StepPrefix}plan-{server.Name}";
+
+ /// The step that creates or changes the product of .
+ public static string ProvisionStepName(RavenDBServerResource server) => $"{StepPrefix}provision-{server.Name}";
+
+ /// The step that creates the databases declares.
+ public static string DatabasesStepName(RavenDBServerResource server) => $"{StepPrefix}databases-{server.Name}";
+
+ /// The step that issues the applications of their certificates.
+ public static string CertificatesStepName(RavenDBServerResource server) => $"{StepPrefix}certificates-{server.Name}";
+
+ /// The step that revokes the certificates the applications of no longer use.
+ public static string CleanupStepName(RavenDBServerResource server) => $"{StepPrefix}cleanup-{server.Name}";
+
+ /// The step that revokes the certificates of and, when asked, terminates its product.
+ public static string DestroyStepName(RavenDBServerResource server) => $"{StepPrefix}destroy-{server.Name}";
+
+ /// The pipeline steps that deploy and destroy .
+ public static IEnumerable Create(RavenDBCloudDeployment deployment)
+ {
+ var server = deployment.Server;
+
+ var plan = new PipelineStep
+ {
+ Name = PlanStepName(server),
+ Description = $"Compares RavenDB Cloud product '{deployment.ProductName}' with the AppHost and decides what the deployment does",
+ Resource = server,
+ Action = context => PlanAsync(deployment, context),
+ };
+
+ // Before anything is built or changed.
+ plan.RequiredBy(WellKnownPipelineSteps.DeployPrereq);
+
+ var provision = new PipelineStep
+ {
+ Name = ProvisionStepName(server),
+ Description = $"Creates RavenDB Cloud product '{deployment.ProductName}' or applies the approved changes, and waits until it is active",
+ Resource = server,
+ Tags = [WellKnownPipelineTags.ProvisionInfrastructure],
+ Action = async context =>
+ {
+ using var client = await CreateClientAsync(deployment, context).ConfigureAwait(false);
+ var currentPlan = deployment.Plan ?? await ComputePlanAsync(deployment, client, context).ConfigureAwait(false);
+
+ await CreateProducts(client, context).ProvisionAsync(deployment, currentPlan, context.CancellationToken).ConfigureAwait(false);
+
+ context.Summary.Add($"RavenDB Cloud ({server.Name})", deployment.Endpoint.Value!);
+ },
+ };
+ provision.DependsOn(plan);
+ provision.RequiredBy(WellKnownPipelineSteps.Deploy);
+
+ var databases = new PipelineStep
+ {
+ Name = DatabasesStepName(server),
+ Description = $"Creates the databases of '{server.Name}' declared with ensureCreated",
+ Resource = server,
+ Action = context => WithServerAsync(deployment, context, async (_, administration) =>
+ {
+ foreach (var database in server.DatabasesToCreate)
+ {
+ if (await administration.DatabaseExistsAsync(database, context.CancellationToken).ConfigureAwait(false))
+ {
+ continue;
+ }
+
+ if (await administration.CreateDatabaseAsync(database, deployment.NodeCount, context.CancellationToken).ConfigureAwait(false))
+ {
+ context.Logger.LogInformation("Created database '{Database}' on {Nodes} node(s).", database, deployment.NodeCount);
+ }
+ }
+ }),
+ };
+ databases.DependsOn(provision);
+ databases.RequiredBy(WellKnownPipelineSteps.Deploy);
+
+ var certificates = new PipelineStep
+ {
+ Name = CertificatesStepName(server),
+ Description = $"Issues a new client certificate to each application that uses '{server.Name}'",
+ Resource = server,
+ Action = context => WithServerAsync(deployment, context, (_, administration) =>
+ new RavenDBCloudCertificates(context.Logger).IssueAsync(
+ administration,
+ deployment,
+ RavenDBConsumers.Find(context.Model, server),
+ context.CancellationToken)),
+ };
+ certificates.DependsOn(databases);
+ certificates.RequiredBy(WellKnownPipelineSteps.Deploy);
+
+ var cleanup = new PipelineStep
+ {
+ Name = CleanupStepName(server),
+ Description = $"Revokes the client certificates of '{server.Name}' that this deployment replaced",
+ Resource = server,
+ Action = context => WithServerAsync(deployment, context, (_, administration) =>
+ new RavenDBCloudCertificates(context.Logger).RevokeReplacedAsync(administration, deployment, context.CancellationToken)),
+ };
+ cleanup.DependsOn(certificates);
+ cleanup.RequiredBy(WellKnownPipelineSteps.Deploy);
+
+ var destroy = new PipelineStep
+ {
+ Name = DestroyStepName(server),
+ Description = $"Revokes the client certificates of '{server.Name}' and terminates RavenDB Cloud product '{deployment.ProductName}' if TerminateOnDestroy is set",
+ Resource = server,
+ Action = async context =>
+ {
+ using var client = await CreateClientAsync(deployment, context).ConfigureAwait(false);
+ var products = CreateProducts(client, context);
+
+ if (Endpoint(context) is var endpoint && endpoint != DefaultEndpoint)
+ {
+ context.Logger.LogWarning("The RavenDB Cloud API at {Endpoint}, from {Variable}, not the production one.", endpoint, EndpointVariable);
+ }
+
+ if (await products.DestroyAsync(deployment, context.CancellationToken).ConfigureAwait(false) is null)
+ {
+ return;
+ }
+
+ using var administration = await ConnectAsync(deployment, client, context).ConfigureAwait(false);
+
+ await new RavenDBCloudCertificates(context.Logger).RevokeAllAsync(administration, deployment, context.CancellationToken).ConfigureAwait(false);
+ },
+ };
+ destroy.DependsOn(WellKnownPipelineSteps.DestroyPrereq);
+ destroy.RequiredBy(WellKnownPipelineSteps.Destroy);
+
+ return [plan, provision, databases, certificates, cleanup, destroy];
+ }
+
+ /// Orders the steps against the ones Aspire and the compute environments add.
+ public static void Configure(RavenDBCloudDeployment deployment, PipelineConfigurationContext context)
+ {
+ var server = deployment.Server;
+ var plan = AspireConventions.Required(context, PlanStepName(server));
+ var provision = AspireConventions.Required(context, ProvisionStepName(server));
+ var certificates = AspireConventions.Required(context, CertificatesStepName(server));
+ var cleanup = AspireConventions.Required(context, CleanupStepName(server));
+ var destroy = AspireConventions.Required(context, DestroyStepName(server));
+
+ // The API key is a parameter, resolved (or prompted for) by process-parameters.
+ if (context.Steps.Any(s => s.Name == WellKnownPipelineSteps.ProcessParameters))
+ {
+ plan.DependsOn(WellKnownPipelineSteps.ProcessParameters);
+ destroy.DependsOn(WellKnownPipelineSteps.ProcessParameters);
+ }
+
+ // The environments resolve the applications' values (the product URL, the certificates) when they prepare
+ // their artifacts: the values have to be set by then.
+ foreach (var environment in context.Model.Resources.OfType())
+ {
+ if (context.Steps.FirstOrDefault(s => s.Name == AspireConventions.Prepare(environment)) is { } prepare)
+ {
+ prepare.DependsOn(provision);
+ prepare.DependsOn(certificates);
+ }
+ }
+
+ // The previous certificates are revoked only once the applications run with the new ones, and the product only
+ // goes away once the applications are stopped.
+ // The steps of every RavenDB Cloud server are left out, so two servers do not wait for each other.
+ foreach (var step in context.Steps.Where(s => !s.Name.StartsWith(StepPrefix, StringComparison.Ordinal)))
+ {
+ if (step.RequiredBySteps.Contains(WellKnownPipelineSteps.Deploy))
+ {
+ cleanup.DependsOn(step);
+ }
+
+ if (step.RequiredBySteps.Contains(WellKnownPipelineSteps.Destroy))
+ {
+ destroy.DependsOn(step);
+ }
+ }
+ }
+
+ private static async Task PlanAsync(RavenDBCloudDeployment deployment, PipelineStepContext context)
+ {
+ using var client = await CreateClientAsync(deployment, context).ConfigureAwait(false);
+ var plan = await ComputePlanAsync(deployment, client, context).ConfigureAwait(false);
+
+ if (Endpoint(context) is var endpoint && endpoint != DefaultEndpoint)
+ {
+ plan.Add($"endpoint: the RavenDB Cloud API at {endpoint}, from {EndpointVariable}, not the production one");
+ }
+
+ // The certificates other clients of an existing product use: one may be an earlier name of this AppHost's.
+ if (plan.Product is { Status: ProductStatus.Active } product && product.Dns?.Any() == true && !plan.Blocks)
+ {
+ await AddOtherClientsAsync(deployment, client, context, plan).ConfigureAwait(false);
+ }
+
+ var report = $"Plan for RavenDB Cloud product '{deployment.ProductName}':{Environment.NewLine}{plan}";
+
+ // One task per line: the CLI shows tasks, so the plan is what the person who deploys reads first.
+ foreach (var line in plan.Lines)
+ {
+ var task = await context.ReportingStep.CreateTaskAsync(line.Text, context.CancellationToken).ConfigureAwait(false);
+ await task.CompleteAsync(line.Text, line.Blocks ? CompletionState.CompletedWithError : CompletionState.Completed, context.CancellationToken).ConfigureAwait(false);
+ }
+
+ if (plan.Blocks)
+ {
+ context.Logger.LogError("{Plan}", report);
+ throw new InvalidOperationException(report);
+ }
+
+ context.Logger.LogInformation("{Plan}", report);
+ deployment.Plan = plan;
+ }
+
+ private static async Task ComputePlanAsync(RavenDBCloudDeployment deployment, RavenDBCloudApiClient client, PipelineStepContext context)
+ {
+ var environment = context.Services.GetRequiredService();
+ var approved = bool.TryParse(environment.Get(RavenDBCloudDeploymentApproval.Variable), out var value) && value;
+
+ return await RavenDBCloudPlanner.PlanAsync(
+ client,
+ deployment,
+ RavenDBConsumers.Find(context.Model, deployment.Server),
+ approved,
+ context.CancellationToken).ConfigureAwait(false);
+ }
+
+ private static async Task AddOtherClientsAsync(RavenDBCloudDeployment deployment, RavenDBCloudApiClient client, PipelineStepContext context, RavenDBCloudPlan plan)
+ {
+ var urls = RavenDBCloudProducts.GetNodeUrls(plan.Product!);
+
+ deployment.ProductId = plan.ProductId;
+ var certificate = await CreateProducts(client, context).GetAdminCertificateAsync(deployment, context.CancellationToken).ConfigureAwait(false);
+ using var administration = context.Services.GetRequiredService().Create(urls, certificate);
+
+ IReadOnlyList others;
+
+ try
+ {
+ await administration.PingAsync(context.CancellationToken).ConfigureAwait(false);
+ others = await RavenDBCloudCertificates.GetOtherClientsAsync(administration, deployment, context.CancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception exception) when (RavenDBServerAdministration.IsUnreachable(exception))
+ {
+ // Every later step talks to the server: stop before anything is built or changed.
+ context.Logger.LogDebug(exception, "RavenDB Cloud product '{Product}' did not answer.", deployment.ProductName);
+ plan.Add(
+ $"unreachable: '{deployment.ProductName}' at {string.Join(", ", urls)} does not answer this machine. Add its address to the product's " +
+ "allowed IPs in the RavenDB Cloud portal and deploy again.",
+ blocks: true);
+ return;
+ }
+
+ if (others.Count > 0)
+ {
+ plan.Add(
+ $"other certificates: {string.Join(", ", others)} on '{deployment.ProductName}' are not ones this AppHost issues for " +
+ "its current databases, so they are left alone. If one is from an earlier name of this AppHost or a database it no " +
+ $"longer declares, revoke it in the Studio: {urls[0]}/studio/index.html#admin/settings/certificates");
+ }
+ }
+
+ /// Runs against the product's server, with its client admin certificate.
+ private static async Task WithServerAsync(
+ RavenDBCloudDeployment deployment,
+ PipelineStepContext context,
+ Func action)
+ {
+ using var client = await CreateClientAsync(deployment, context).ConfigureAwait(false);
+ using var administration = await ConnectAsync(deployment, client, context).ConfigureAwait(false);
+
+ await action(client, administration).ConfigureAwait(false);
+ }
+
+ ///
+ /// Connects to the product's server with its admin certificate, once the server accepts connections: right after a
+ /// change the product reports Active a little before its node answers.
+ ///
+ private static async Task ConnectAsync(RavenDBCloudDeployment deployment, RavenDBCloudApiClient client, PipelineStepContext context)
+ {
+ var certificate = await CreateProducts(client, context).GetAdminCertificateAsync(deployment, context.CancellationToken).ConfigureAwait(false);
+ var administration = context.Services.GetRequiredService()
+ .Create(deployment.NodeUrls, certificate);
+
+ try
+ {
+ var deadline = DateTimeOffset.UtcNow + deployment.ReachableTimeout;
+ var waiting = false;
+
+ while (true)
+ {
+ try
+ {
+ await administration.PingAsync(context.CancellationToken).ConfigureAwait(false);
+ return administration;
+ }
+ catch (Exception exception) when (RavenDBServerAdministration.IsUnreachable(exception))
+ {
+ if (DateTimeOffset.UtcNow >= deadline)
+ {
+ throw new InvalidOperationException(
+ $"RavenDB Cloud product '{deployment.ProductName}' at {deployment.Endpoint.Value} did not answer for " +
+ $"{deployment.ReachableTimeout}. Check that the address of this machine is among the product's allowed IPs.",
+ exception);
+ }
+
+ if (!waiting)
+ {
+ context.Logger.LogInformation(
+ "Waiting for RavenDB Cloud product '{Product}' at {Url} to accept connections.",
+ deployment.ProductName,
+ deployment.Endpoint.Value);
+ waiting = true;
+ }
+ }
+
+ await Task.Delay(deployment.PollInterval, context.CancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch
+ {
+ administration.Dispose();
+ throw;
+ }
+ }
+
+ private static async Task CreateClientAsync(RavenDBCloudDeployment deployment, PipelineStepContext context)
+ {
+ var apiKey = await deployment.ApiKey.GetValueAsync(context.CancellationToken).ConfigureAwait(false);
+
+ if (string.IsNullOrWhiteSpace(apiKey))
+ {
+ throw new InvalidOperationException(
+ $"RavenDB Cloud needs an API key for '{deployment.Server.Name}'. Set the '{deployment.ApiKey.Name}' parameter.");
+ }
+
+ return context.Services.GetRequiredService().Create(Endpoint(context), apiKey);
+ }
+
+ ///
+ /// The Cloud API: the production one, or another from in the process environment.
+ ///
+ private static string Endpoint(PipelineStepContext context)
+ {
+ var endpoint = context.Services.GetRequiredService().Get(EndpointVariable) is { Length: > 0 } other
+ ? other
+ : DefaultEndpoint;
+
+ // The API key has account-owner rights; plain HTTP is only for a local stand-in of the API.
+ if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttps && !uri.IsLoopback))
+ {
+ throw new InvalidOperationException(
+ $"The RavenDB Cloud API endpoint '{endpoint}' in {EndpointVariable} must be an https URL: the API key sent to it has account-owner rights.");
+ }
+
+ return endpoint;
+ }
+
+ /// The environment variable with the Cloud API endpoint.
+ internal const string EndpointVariable = "RAVENDB_CLOUD_ENDPOINT";
+
+ private const string DefaultEndpoint = "https://api.cloud.ravendb.net";
+
+ private static RavenDBCloudProducts CreateProducts(RavenDBCloudApiClient client, PipelineStepContext context) =>
+ new(client, context.Logger);
+}
+
+///
+/// The Aspire steps the RavenDB Cloud steps are ordered against. Aspire names them by convention only, so the names
+/// live here: a rename in Aspire shows up in one place.
+///
+internal static class AspireConventions
+{
+ /// The step in which a compute environment resolves its values into its artifacts.
+ public static string Prepare(IResource environment) => $"prepare-{environment.Name}";
+
+ /// A step of this integration, which must exist: a missing one is a bug, never something to skip.
+ public static PipelineStep Required(PipelineConfigurationContext context, string name) =>
+ context.Steps.FirstOrDefault(s => s.Name == name)
+ ?? throw new DistributedApplicationException(
+ $"The pipeline has no step '{name}', which the RavenDB Cloud integration orders its own steps against. This " +
+ "version of the integration does not support the Aspire version in use.");
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPlan.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPlan.cs
new file mode 100644
index 000000000..311b6f9e3
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudPlan.cs
@@ -0,0 +1,524 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Sockets;
+using Aspire.Hosting.ApplicationModel;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+/// One line of the plan, as the deployment prints it.
+/// What happens, such as change: instance Dev10 -> Dev20.
+/// Whether the line stops the deployment.
+internal sealed record RavenDBCloudPlanLine(string Text, bool Blocks = false);
+
+///
+/// What the deployment will do to the product, decided before anything is built or changed: every difference between
+/// the AppHost and the product either stops the deployment or is applied with explicit consent.
+///
+internal sealed class RavenDBCloudPlan
+{
+ /// The lines the person who deploys reads, in order.
+ public List Lines { get; } = [];
+
+ /// The product found by name; when there is none.
+ public string? ProductId { get; set; }
+
+ /// The details of the product found by name; when there is none.
+ public ProductDetails? Product { get; set; }
+
+ /// The product to create; when it exists or the AppHost attaches to one.
+ public ProductCreateRequest? Create { get; set; }
+
+ /// The instance type the product changes to; when it stays.
+ public string? InstanceTypeChange { get; set; }
+
+ /// The change of the product's data disk; when it stays.
+ public ChangeStorageRequest? StorageChange { get; set; }
+
+ /// Whether the plan changes the product.
+ public bool HasChanges => InstanceTypeChange is not null || StorageChange is not null;
+
+ /// Whether a line stops the deployment.
+ public bool Blocks => Lines.Any(l => l.Blocks);
+
+ /// Adds a line; a blocking one stops the deployment.
+ public void Add(string text, bool blocks = false) => Lines.Add(new RavenDBCloudPlanLine(text, blocks));
+
+ /// The plan as the deployment log shows it, with ! before the lines that stop it.
+ public override string ToString() => string.Join(Environment.NewLine, Lines.Select(l => (l.Blocks ? " ! " : " ") + l.Text));
+}
+
+/// Computes the from the AppHost, the product and the Cloud API's offer.
+internal static class RavenDBCloudPlanner
+{
+ /// The compute environments that deliver the product URL and the certificates to the applications.
+ internal static readonly IReadOnlyDictionary SupportedEnvironments = new Dictionary(StringComparer.Ordinal)
+ {
+ ["Aspire.Hosting.Docker.DockerComposeEnvironmentResource"] = "Docker Compose",
+ };
+
+ /// The Cloud API.
+ /// The AppHost's side.
+ /// The applications that use the server.
+ /// Whether the deployment approves changes to the product.
+ /// Cancels the calls.
+ public static async Task PlanAsync(
+ RavenDBCloudApiClient client,
+ RavenDBCloudDeployment deployment,
+ IReadOnlyList consumers,
+ bool approved,
+ CancellationToken cancellationToken)
+ {
+ var plan = new RavenDBCloudPlan();
+ var (productId, product) = await RavenDBCloudProducts.FindAsync(client, deployment.ProductName, cancellationToken).ConfigureAwait(false);
+ plan.ProductId = productId;
+ plan.Product = product;
+
+ foreach (var range in deployment.Options.AllowedIps)
+ {
+ if (!IPNetwork.TryParse(range.Trim(), out var network))
+ {
+ plan.Add(
+ $"allowed IP range '{range}' is not a valid CIDR range: write it as RavenDB Cloud takes it, such as " +
+ "203.0.113.0/24, or 203.0.113.7/32 for one address.",
+ blocks: true);
+ }
+ else if (network.PrefixLength < (network.BaseAddress.AddressFamily == AddressFamily.InterNetwork ? 16 : 48))
+ {
+ plan.Add(
+ $"wide allowed IPs: {range} lets a large part of the internet reach '{deployment.ProductName}', which then " +
+ "relies on its certificates alone. Allow the outbound addresses of the machines that connect instead.");
+ }
+ }
+
+ // RavenDB Cloud could not set the product up, or waits for a payment: it can neither change nor serve.
+ if (product?.Status is ProductStatus.Error)
+ {
+ plan.Add($"error: '{deployment.ProductName}' is in error in RavenDB Cloud. See the portal for details.", blocks: true);
+ }
+ else if (product?.Status is ProductStatus.AwaitingPayment)
+ {
+ plan.Add($"awaiting payment: '{deployment.ProductName}' waits for a payment. Complete it in the portal and deploy again.", blocks: true);
+ }
+ else if (deployment.Mode == RavenDBCloudMode.Attached)
+ {
+ if (product is null)
+ {
+ plan.Add(
+ $"missing: there is no RavenDB Cloud product '{deployment.ProductName}'. PublishAsExistingRavenDBCloud never creates " +
+ "one: create it in the portal, or use PublishAsRavenDBCloud.",
+ blocks: true);
+ }
+ else
+ {
+ plan.Add($"attach: '{deployment.ProductName}' ({Describe(product)}), as client '{deployment.ClientName}'");
+ }
+ }
+ else
+ {
+ await PlanManagedAsync(client, deployment, plan, approved, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (product is not null)
+ {
+ CheckAllowedIps(deployment, product, plan);
+ }
+
+ CheckEnvironments(deployment, consumers, plan);
+
+ return plan;
+ }
+
+ private static async Task PlanManagedAsync(
+ RavenDBCloudApiClient client,
+ RavenDBCloudDeployment deployment,
+ RavenDBCloudPlan plan,
+ bool approved,
+ CancellationToken cancellationToken)
+ {
+ var spec = deployment.Spec!;
+ var offered = await CheckOfferAsync(client, deployment, spec, plan, cancellationToken).ConfigureAwait(false);
+
+ if (plan.Product is not { } product)
+ {
+ switch (await RavenDBCloudProducts.FindNameHolderAsync(client, deployment.ProductName, cancellationToken).ConfigureAwait(false))
+ {
+ case null:
+ break;
+
+ // A destroy that terminated it moments ago: it is hidden, and the name freed, once it is terminated.
+ case ProductStatus.Terminating:
+ plan.Add(
+ $"name: '{deployment.ProductName}' is held by a product that is still being terminated. Deploy again once " +
+ "RavenDB Cloud has terminated it.",
+ blocks: true);
+ return;
+
+ default:
+ plan.Add(
+ $"name: '{deployment.ProductName}' is held by a terminated product, which RavenDB Cloud keeps until it is " +
+ "hidden. Hide that product in the RavenDB Cloud portal, or choose another name.",
+ blocks: true);
+ return;
+ }
+
+ PlanCreate(deployment, spec, offered, plan);
+ return;
+ }
+
+ var changes = new List();
+ var impossible = new List();
+ void CannotChange(string change) => impossible.Add($"{change}. Create a product with another name, or change the AppHost back.");
+
+ if (!Same(product.CloudProvider, spec.Provider.ToString()))
+ {
+ CannotChange($"provider {product.CloudProvider} -> {spec.Provider}");
+ }
+
+ if (!Same(product.Region, spec.Region))
+ {
+ CannotChange($"region {product.Region} -> {spec.Region}");
+ }
+
+ // There is no Cloud API call to change the release channel.
+ if (!Same(product.ReleaseChannel, spec.ReleaseChannel))
+ {
+ CannotChange($"release channel {product.ReleaseChannel} -> {spec.ReleaseChannel} (change it in the portal)");
+ }
+
+ // The Cloud API has no call that moves a product's data to another disk layout.
+ if (product.HardwareInfo is { } hardware && LayoutOf(hardware) != spec.DiskLayout)
+ {
+ CannotChange($"disk layout {LayoutOf(hardware)} -> {spec.DiskLayout}");
+ }
+
+ // The Cloud API refuses an instance type of another tier ("not available for the product tier").
+ if (!Same(product.Tier, spec.Tier.ToString()))
+ {
+ CannotChange($"tier {product.Tier} -> {spec.Tier} (RavenDB Cloud cannot change the tier of a product)");
+ }
+ else if (!Same(product.InstanceType, spec.InstanceType))
+ {
+ changes.Add($"instance {product.InstanceType} -> {spec.InstanceType}");
+ plan.InstanceTypeChange = spec.InstanceType;
+ }
+
+ if (product.HardwareInfo?.DataDisk is { } storage)
+ {
+ var size = spec.DiskSizeInGb;
+ var storageChanges = new List();
+
+ // Usually nobody changed the AppHost: RavenDB Cloud grows a disk that fills up.
+ if (size < storage.Size)
+ {
+ impossible.Add(
+ $"disk {storage.Size} GB -> {size} GB. A disk cannot shrink, and RavenDB Cloud grows one that fills up: " +
+ $"set the disk size in the AppHost to {storage.Size} GB.");
+ }
+ else if (size > storage.Size && storage.AvailableDiskSizes is { Count: > 0 } resizable && !resizable.Contains(size))
+ {
+ impossible.Add(
+ $"disk {storage.Size} GB -> {size} GB. RavenDB Cloud grows this disk to {List(resizable)} GB only: set one " +
+ "of them in the AppHost.");
+ }
+ else if (size > storage.Size)
+ {
+ storageChanges.Add($"disk {storage.Size} GB -> {size} GB");
+ }
+
+ if (!Same(storage.Type, spec.StorageType.ToString()))
+ {
+ storageChanges.Add($"storage {storage.Type} -> {spec.StorageType}");
+ }
+
+ if (spec.Iops is { } iops && iops != storage.Iops)
+ {
+ storageChanges.Add($"IOPS {Show(storage.Iops)} -> {iops}");
+ }
+
+ if (spec.Throughput is { } throughput && throughput != storage.Throughput)
+ {
+ storageChanges.Add($"throughput {Show(storage.Throughput)} -> {throughput} MB/s");
+ }
+
+ if (storageChanges.Count > 0 && size >= storage.Size)
+ {
+ changes.AddRange(storageChanges);
+ plan.StorageChange = new ChangeStorageRequest(
+ plan.ProductId!,
+ spec.StorageType.ToString(),
+ size,
+ spec.Iops ?? storage.Iops,
+ spec.Throughput ?? storage.Throughput);
+ }
+ }
+
+ foreach (var line in impossible)
+ {
+ plan.Add($"impossible: {line}", blocks: true);
+ }
+
+ if (changes.Count == 0)
+ {
+ if (impossible.Count == 0)
+ {
+ plan.Add($"no changes: '{deployment.ProductName}' ({Describe(product)})");
+ }
+
+ return;
+ }
+
+ var change = $"change '{deployment.ProductName}': {string.Join(", ", changes)}";
+
+ if (approved)
+ {
+ plan.Add($"{change} (approved by {RavenDBCloudDeploymentApproval.Variable})");
+ }
+ else
+ {
+ plan.InstanceTypeChange = null;
+ plan.StorageChange = null;
+ plan.Add(
+ $"{change}. Deploy with {RavenDBCloudDeploymentApproval.Variable}=true to apply it.",
+ blocks: true);
+ }
+ }
+
+ private static void PlanCreate(RavenDBCloudDeployment deployment, RavenDBCloudSpec spec, bool offered, RavenDBCloudPlan plan)
+ {
+ if (deployment.Options.AllowedIps.Count == 0)
+ {
+ plan.Add(
+ $"creating '{deployment.ProductName}' needs at least one allowed IP range, and the Cloud API cannot add them later. " +
+ "Set them with options.WithAllowedIps(...): the machine that deploys, the CI runner, and the outbound addresses " +
+ "of the applications' environment.",
+ blocks: true);
+ }
+
+
+ if (!RavenDBCloudDeployment.IsValidSubdomain(deployment.Subdomain))
+ {
+ plan.Add(
+ $"subdomain '{deployment.Subdomain}' is not valid: use up to {RavenDBCloudDeployment.MaxSubdomainLength} letters, " +
+ "digits and dashes, not starting or ending with a dash.",
+ blocks: true);
+ }
+
+ if (!offered)
+ {
+ return;
+ }
+
+ plan.Create = new ProductCreateRequest(
+ CloudProvider: spec.Provider.ToString(),
+ InstanceTypeName: spec.InstanceType,
+ DisplayName: deployment.ProductName,
+ ReleaseChannel: spec.ReleaseChannel,
+ SubdomainName: deployment.Subdomain,
+ Tier: spec.Tier.ToString(),
+ Region: spec.Region,
+ DiskSize: spec.DiskSizeInGb,
+ Iops: spec.Iops,
+ Throughput: spec.Throughput,
+ StorageTypeName: spec.StorageType.ToString(),
+ AllowedIps: [.. deployment.Options.AllowedIps],
+ DiskLayout: spec.DiskLayout.ToString());
+
+ if (!plan.Blocks)
+ {
+ plan.Add(
+ $"create '{deployment.ProductName}': {spec}, allowed IPs {string.Join(", ", deployment.Options.AllowedIps)}");
+ }
+ }
+
+ /// Whether RavenDB Cloud offers , with a blocking line for anything it does not.
+ private static async Task CheckOfferAsync(
+ RavenDBCloudApiClient client,
+ RavenDBCloudDeployment deployment,
+ RavenDBCloudSpec spec,
+ RavenDBCloudPlan plan,
+ CancellationToken cancellationToken)
+ {
+ // The channel does not depend on the region or the instance type, so it is checked even when they are wrong.
+ var offered = true;
+ var channels = (await client.GetReleaseChannelsAsync(cancellationToken).ConfigureAwait(false)).ReleaseChannels?
+ .Where(c => c.Name is not null)
+ .ToList() ?? [];
+
+ if (channels.Count > 0 && !channels.Any(c => Same(c.Name, spec.ReleaseChannel)))
+ {
+ var available = channels.Select(c => c.RavenVersion is { } version ? $"{c.Name} (RavenDB {version})" : c.Name);
+ plan.Add($"release channel '{spec.ReleaseChannel}' does not exist. Available: {List(available)}.", blocks: true);
+ offered = false;
+ }
+
+ var provider = spec.Provider.ToString();
+ var regions = await client.GetRegionsAsync(provider, cancellationToken).ConfigureAwait(false);
+
+ if (!regions.Any(r => Same(r, spec.Region)))
+ {
+ plan.Add($"region '{spec.Region}' is not offered on {provider}. Offered: {List(regions)}.", blocks: true);
+ return false;
+ }
+
+ var types = await client.GetInstanceTypesAsync(provider, spec.Region, cancellationToken).ConfigureAwait(false);
+ var type = types.FirstOrDefault(t => Same(t.Name, spec.InstanceType));
+ var ofTier = types.Where(t => t.Name is not null && Same(t.Tier, spec.Tier.ToString())).Select(DescribeInstance).ToList();
+
+ if (type is null || !Same(type.Tier, spec.Tier.ToString()))
+ {
+ plan.Add(
+ $"instance type '{spec.InstanceType}' is not offered for the {spec.Tier} tier in {provider} {spec.Region}. " +
+ $"Offered: {List(ofTier)}.",
+ blocks: true);
+ return false;
+ }
+
+ // The sizes a new product chooses from. An existing disk keeps its size, which RavenDB Cloud may have grown past
+ // them, and grows only to the sizes it lists for that disk: the comparison with the product checks those.
+ var sizes = type.Parameters?.AvailableDiskSizes?.Where(s => s > 0).ToList() ?? [];
+
+ if (plan.Product is null && sizes.Count > 0 && !sizes.Contains(spec.DiskSizeInGb))
+ {
+ plan.Add($"disk size {spec.DiskSizeInGb} GB is not offered for instance type '{type.Name}'. Offered: {List(sizes)} GB.", blocks: true);
+ offered = false;
+ }
+
+ if (type.Parameters?.AvailableStorageTypes is { Count: > 0 } storageTypes)
+ {
+ var storage = storageTypes.FirstOrDefault(s => Same(s.Name, spec.StorageType.ToString()));
+
+ if (storage is null)
+ {
+ plan.Add(
+ $"storage type {spec.StorageType} is not offered for instance type '{type.Name}'. Offered: {List(storageTypes.Select(s => s.Name))}.",
+ blocks: true);
+ offered = false;
+ }
+ else if (spec.Iops is { } iops && storage.IopsRange is { } range && (iops < range.Min || iops > range.Max))
+ {
+ plan.Add($"{iops} IOPS is outside the range offered for {spec.StorageType}: {range.Min} to {range.Max}.", blocks: true);
+ offered = false;
+ }
+ }
+
+ deployment.NodeCount = Math.Max(type.Parameters?.NumberOfNodes ?? 1, 1);
+
+ return offered;
+ }
+
+ /// Each range the AppHost allows must be covered by one the product allows; the API cannot add it.
+ private static void CheckAllowedIps(RavenDBCloudDeployment deployment, ProductDetails product, RavenDBCloudPlan plan)
+ {
+ var allowed = (product.Security?.AllowedIps ?? [])
+ .Select(r => IPNetwork.TryParse(r, out var parsed) ? parsed : (IPNetwork?)null)
+ .OfType()
+ .ToList();
+
+ // Covered: the requested range lies inside an allowed one.
+ var missing = deployment.Options.AllowedIps
+ .Where(r => IPNetwork.TryParse(r.Trim(), out var requested) &&
+ !allowed.Any(a => requested.PrefixLength >= a.PrefixLength && a.Contains(requested.BaseAddress)))
+ .ToList();
+
+ if (missing.Count > 0)
+ {
+ plan.Add(
+ $"allowed IPs: {string.Join(", ", missing)} not allowed on '{deployment.ProductName}'. Add them in the RavenDB Cloud " +
+ "portal (the Cloud API cannot change them) and deploy again.",
+ blocks: true);
+ }
+ }
+
+ /// An application deployed where the URL and certificate cannot be delivered would start without them.
+ private static void CheckEnvironments(RavenDBCloudDeployment deployment, IReadOnlyList consumers, RavenDBCloudPlan plan)
+ {
+ var supported = string.Join(", ", SupportedEnvironments.Values);
+
+ foreach (var consumer in consumers)
+ {
+ // Exactly one compute environment, of a supported type: anything else could carry the certificate somewhere
+ // it is not a secret, or nowhere.
+ var environments = consumer.Resource.Annotations.OfType().Select(t => t.ComputeEnvironment).ToList();
+
+ if (environments is [{ } only] && SupportedEnvironments.ContainsKey(only.GetType().FullName ?? string.Empty))
+ {
+ continue;
+ }
+
+ var where = environments switch
+ {
+ [] or [null] => "no compute environment",
+ [{ } one] => $"'{one.Name}'",
+ _ => $"{environments.Count} compute environments",
+ };
+
+ plan.Add(
+ $"no target: '{consumer.Resource.Name}' is deployed to {where}, where the RavenDB Cloud integration cannot deliver " +
+ $"the URL and certificate of '{deployment.Server.Name}'. Supported: {supported}, as an application's only compute environment.",
+ blocks: true);
+ }
+ }
+
+ /// One line about an existing product, in the words of .
+ internal static string Describe(ProductDetails product)
+ {
+ var storage = product.HardwareInfo is { DataDisk: { } s } h ? $", {s.Size} GB {s.Type} on {LayoutOf(h)}" : string.Empty;
+ return $"{product.Tier} {product.InstanceType}, {product.CloudProvider} {product.Region}{storage}, channel {product.ReleaseChannel}";
+ }
+
+ private static bool Same(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
+
+ /// A product with a data disk keeps its data there; one without keeps it on the system disk.
+ private static RavenDBCloudDiskLayout LayoutOf(HardwareInfo hardware) =>
+ hardware.AdditionalStorage is null ? RavenDBCloudDiskLayout.RootOnly : RavenDBCloudDiskLayout.SingleDataDisk;
+
+ /// An instance type with what it is, such as Dev10 (2 vCPU, 0.5 GB RAM, 1 node, disks 10/15/20/25 GB).
+ private static string DescribeInstance(InstanceTypeItem type)
+ {
+ var parameters = type.Parameters;
+ var details = new List();
+
+ if (parameters?.VirtualCpus is { } cpus)
+ {
+ details.Add($"{cpus} vCPU");
+ }
+
+ if (parameters?.Ram is { } ram)
+ {
+ details.Add($"{ram.ToString("0.#", CultureInfo.InvariantCulture)} GB RAM");
+ }
+
+ if (parameters?.NumberOfNodes is { } nodes)
+ {
+ details.Add(nodes == 1 ? "1 node" : $"{nodes} nodes");
+ }
+
+ if (parameters?.AvailableDiskSizes is { Count: > 0 } disks)
+ {
+ details.Add($"disks {string.Join("/", disks)} GB");
+ }
+
+ return details.Count == 0 ? type.Name! : $"{type.Name} ({string.Join(", ", details)})";
+ }
+
+ private static string Show(int? value) => value?.ToString(CultureInfo.InvariantCulture) ?? "default";
+
+ private static string Show(double? value) => value?.ToString(CultureInfo.InvariantCulture) ?? "default";
+
+ private static string List(IEnumerable values)
+ {
+ var items = values.Where(v => v is not null).Select(v => Convert.ToString(v, CultureInfo.InvariantCulture)).ToList();
+ return items.Count == 0 ? "none" : string.Join(", ", items);
+ }
+
+}
+
+/// The environment variable that approves changes to products.
+internal static class RavenDBCloudDeploymentApproval
+{
+ ///
+ /// The environment variable that approves the changes the plan shows. It is read from the process environment only,
+ /// so a committed settings file cannot approve every change for good.
+ ///
+ public const string Variable = "RavenDB__Cloud__ApproveChanges";
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudProducts.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudProducts.cs
new file mode 100644
index 000000000..bd3f4677a
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudProducts.cs
@@ -0,0 +1,322 @@
+using System.Security.Cryptography.X509Certificates;
+using Microsoft.Extensions.Logging;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// The lifecycle of a RavenDB Cloud product through the Cloud API: create it or apply the approved plan, wait until it
+/// is active, and terminate it on destroy when asked to. The product is always found by its name, from any machine.
+///
+internal sealed class RavenDBCloudProducts(RavenDBCloudApiClient client, ILogger logger)
+{
+ ///
+ /// The live product named . A terminated product stays listed for a while, so only
+ /// live ones count, and two live ones with the same name are an error: the name is the product's identity.
+ ///
+ public static async Task<(string? ProductId, ProductDetails? Details)> FindAsync(
+ RavenDBCloudApiClient client,
+ string productName,
+ CancellationToken cancellationToken)
+ {
+ var live = new List<(string Id, ProductDetails Details)>();
+
+ foreach (var match in (await client.ListProductsAsync(cancellationToken).ConfigureAwait(false))
+ .Where(p => p.Id is not null && string.Equals(p.Name, productName, StringComparison.OrdinalIgnoreCase)))
+ {
+ if (await client.GetProductAsync(match.Id!, cancellationToken).ConfigureAwait(false) is { } details && !IsGone(details.Status))
+ {
+ live.Add((match.Id!, details));
+ }
+ }
+
+ return live.Count switch
+ {
+ 0 => (null, null),
+ 1 => live[0],
+ _ => throw new InvalidOperationException(
+ $"The account has {live.Count} RavenDB Cloud products named '{productName}'. The name identifies the product: " +
+ "rename or terminate the extra ones in the portal."),
+ };
+ }
+
+ ///
+ /// The status of a product the portal still shows under , such as a terminated one:
+ /// RavenDB Cloud keeps names unique among those until they are hidden. Asked when no live product has the name.
+ ///
+ /// The holder's status, or when the name is free.
+ public static async Task FindNameHolderAsync(RavenDBCloudApiClient client, string productName, CancellationToken cancellationToken)
+ {
+ foreach (var match in (await client.ListProductsAsync(cancellationToken).ConfigureAwait(false))
+ .Where(p => p.Id is not null && string.Equals(p.Name, productName, StringComparison.OrdinalIgnoreCase)))
+ {
+ return (await client.GetProductAsync(match.Id!, cancellationToken).ConfigureAwait(false))?.Status ?? ProductStatus.Terminated;
+ }
+
+ return null;
+ }
+
+ /// Carries out and resolves the product's URL on .
+ public async Task ProvisionAsync(RavenDBCloudDeployment deployment, RavenDBCloudPlan plan, CancellationToken cancellationToken)
+ {
+ if (plan.Blocks)
+ {
+ throw new InvalidOperationException($"The plan for RavenDB Cloud product '{deployment.ProductName}' stops the deployment:{Environment.NewLine}{plan}");
+ }
+
+ var productId = plan.ProductId;
+ ProductDetails? details = plan.Product;
+
+ if (productId is null)
+ {
+ var request = plan.Create
+ ?? throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' does not exist and the plan does not create it.");
+
+ logger.LogInformation("Creating RavenDB Cloud product '{Product}': {Spec}.", deployment.ProductName, deployment.Spec);
+
+ productId = await client.CreateProductAsync(request, cancellationToken).ConfigureAwait(false);
+ details = null;
+ }
+ else
+ {
+ logger.LogInformation("Using RavenDB Cloud product '{Product}' ({ProductId}).", deployment.ProductName, productId);
+ }
+
+ details = await WaitForActiveAsync(deployment, productId, details, cancellationToken).ConfigureAwait(false);
+
+ if (plan.HasChanges)
+ {
+ details = await ApplyChangesAsync(deployment, plan, productId, cancellationToken).ConfigureAwait(false);
+ }
+
+ Resolve(deployment, productId, details);
+ logger.LogInformation("RavenDB Cloud product '{Product}' is active at {Url}.", deployment.ProductName, deployment.Endpoint.Value);
+ }
+
+ ///
+ /// Terminates a product the AppHost manages when is set; any
+ /// other product is left running.
+ ///
+ /// The product left running, resolved on when it has a URL; else .
+ public async Task DestroyAsync(RavenDBCloudDeployment deployment, CancellationToken cancellationToken)
+ {
+ var (productId, details) = await FindAsync(client, deployment.ProductName, cancellationToken).ConfigureAwait(false);
+
+ if (productId is null || details is null)
+ {
+ logger.LogInformation("RavenDB Cloud product '{Product}' does not exist; nothing to destroy.", deployment.ProductName);
+ return null;
+ }
+
+ if (deployment.Mode == RavenDBCloudMode.Managed && deployment.Options.TerminateOnDestroy)
+ {
+ // The name alone could be another environment's product: terminate only the one the AppHost describes.
+ if (Mismatches(deployment, details) is { Count: > 0 } mismatches)
+ {
+ throw new InvalidOperationException(
+ $"RavenDB Cloud product '{deployment.ProductName}' ({RavenDBCloudPlanner.Describe(details)}) does not match the " +
+ $"AppHost ({string.Join(", ", mismatches)}), so it is not terminated. If it belongs to another environment, give " +
+ "this one a product name of its own; if the AppHost should terminate it, make the AppHost describe it.");
+ }
+
+ // Works whatever the product's state, also while it is being created and has no URL yet.
+ logger.LogInformation(
+ "Terminating RavenDB Cloud product '{Product}' ({ProductId}: {Description}). Its data is deleted.",
+ deployment.ProductName,
+ productId,
+ RavenDBCloudPlanner.Describe(details));
+ await client.TerminateProductAsync(productId, cancellationToken).ConfigureAwait(false);
+ return null;
+ }
+
+ logger.LogInformation(
+ deployment.Mode == RavenDBCloudMode.Attached
+ ? "RavenDB Cloud product '{Product}' ({ProductId}) is attached to, so it is left running."
+ : "RavenDB Cloud product '{Product}' ({ProductId}) is left running because TerminateOnDestroy is not set. Terminate it in the portal once it is no longer needed.",
+ deployment.ProductName,
+ productId);
+
+ if (details.Dns?.Any(d => !string.IsNullOrWhiteSpace(d)) != true)
+ {
+ return null;
+ }
+
+ Resolve(deployment, productId, details);
+ return details;
+ }
+
+ ///
+ /// What tells the product found by name apart from the one the AppHost describes: what RavenDB Cloud never changes,
+ /// and the instance type. The disk is left out, since RavenDB Cloud grows a disk that fills up, and so is the
+ /// subdomain, which a product made in the portal chose freely.
+ ///
+ private static List Mismatches(RavenDBCloudDeployment deployment, ProductDetails product)
+ {
+ var spec = deployment.Spec!;
+ var mismatches = new List();
+
+ void Compare(string what, string? actual, string expected)
+ {
+ if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase))
+ {
+ mismatches.Add($"{what} {actual ?? "unknown"}, the AppHost says {expected}");
+ }
+ }
+
+ Compare("tier", product.Tier, spec.Tier.ToString());
+ Compare("provider", product.CloudProvider, spec.Provider.ToString());
+ Compare("region", product.Region, spec.Region);
+ Compare("release channel", product.ReleaseChannel, spec.ReleaseChannel);
+ Compare("instance type", product.InstanceType, spec.InstanceType);
+
+ return mismatches;
+ }
+
+ /// The product's client admin certificate, from the Cloud API; downloaded once per deployment.
+ public async Task GetAdminCertificateAsync(RavenDBCloudDeployment deployment, CancellationToken cancellationToken)
+ {
+ if (deployment.AdminCertificate is null)
+ {
+ var productId = deployment.ProductId
+ ?? throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' has not been resolved yet.");
+ var bundle = await client.GetAdminCertificateAsync(productId, cancellationToken).ConfigureAwait(false);
+ var pfx = RavenDBCloudCertificates.ExtractPfx(bundle)
+ ?? throw new InvalidOperationException($"The certificate bundle of RavenDB Cloud product '{deployment.ProductName}' contains no .pfx file.");
+
+ var certificate = RavenDBCloudCertificates.Load(pfx);
+ deployment.AdminCertificate = certificate;
+
+ // Every connection of the deployment uses this one instance, so it lives as long as the process. On Windows
+ // its private key is a file in the user profile until the certificate is disposed: dispose it on exit.
+ AppDomain.CurrentDomain.ProcessExit += (_, _) => certificate.Dispose();
+ }
+
+ return deployment.AdminCertificate;
+ }
+
+ private async Task ApplyChangesAsync(
+ RavenDBCloudDeployment deployment,
+ RavenDBCloudPlan plan,
+ string productId,
+ CancellationToken cancellationToken)
+ {
+ ProductDetails? details = null;
+
+ if (plan.InstanceTypeChange is { } instanceType)
+ {
+ logger.LogInformation("Changing the instance type of RavenDB Cloud product '{Product}' to {InstanceType}.", deployment.ProductName, instanceType);
+ await client.ChangeInstanceTypeAsync(productId, instanceType, cancellationToken).ConfigureAwait(false);
+ details = await WaitForActiveAsync(deployment, productId, null, cancellationToken, afterChange: true).ConfigureAwait(false);
+ }
+
+ if (plan.StorageChange is { } storage)
+ {
+ logger.LogInformation(
+ "Changing the storage of RavenDB Cloud product '{Product}' to {Size} GB {Type}.",
+ deployment.ProductName,
+ storage.Size,
+ storage.StorageType);
+ await client.ChangeStorageAsync(storage, cancellationToken).ConfigureAwait(false);
+ details = await WaitForActiveAsync(deployment, productId, null, cancellationToken, afterChange: true).ConfigureAwait(false);
+ }
+
+ // Read back: the deployment must not report success for a product that is not what the AppHost asked for.
+ var spec = deployment.Spec!;
+ var actual = details!;
+
+ if ((plan.InstanceTypeChange is not null && !string.Equals(actual.InstanceType, spec.InstanceType, StringComparison.OrdinalIgnoreCase)) ||
+ (plan.StorageChange is not null && actual.HardwareInfo?.DataDisk is { } s &&
+ (s.Size != spec.DiskSizeInGb || !string.Equals(s.Type, spec.StorageType.ToString(), StringComparison.OrdinalIgnoreCase))))
+ {
+ throw new InvalidOperationException(
+ $"RavenDB Cloud product '{deployment.ProductName}' is {RavenDBCloudPlanner.Describe(actual)} after the change, not {spec}. " +
+ "See the portal for details.");
+ }
+
+ return actual;
+ }
+
+ private async Task WaitForActiveAsync(
+ RavenDBCloudDeployment deployment,
+ string productId,
+ ProductDetails? details,
+ CancellationToken cancellationToken,
+ bool afterChange = false)
+ {
+ var started = DateTimeOffset.UtcNow;
+ var deadline = started + deployment.ProvisioningTimeout;
+ string? lastStatus = null;
+
+ // Right after a change request the product may still report Active for a moment: wait until it reports the
+ // change, or until it had time to.
+ var sawChange = !afterChange;
+
+ while (true)
+ {
+ details ??= await client.GetProductAsync(productId, cancellationToken).ConfigureAwait(false)
+ ?? throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' disappeared.");
+
+ if (!string.Equals(details.Status, lastStatus, StringComparison.Ordinal))
+ {
+ logger.LogInformation("RavenDB Cloud product '{Product}': {Status}.", deployment.ProductName, details.Status);
+ lastStatus = details.Status;
+ }
+
+ switch (details.Status)
+ {
+ case ProductStatus.Active when sawChange || DateTimeOffset.UtcNow - started > deployment.ChangeGracePeriod:
+ return details;
+
+ case ProductStatus.Creating or ProductStatus.DeployingChanges:
+ sawChange = true;
+ break;
+
+ case ProductStatus.Error:
+ throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' is in error. See the portal for details.");
+
+ case ProductStatus.AwaitingPayment:
+ throw new InvalidOperationException(
+ $"RavenDB Cloud product '{deployment.ProductName}' is awaiting payment. Complete it in the portal and deploy again.");
+
+ case ProductStatus.Terminating or ProductStatus.Terminated:
+ throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' is being terminated.");
+ }
+
+ if (DateTimeOffset.UtcNow > deadline)
+ {
+ throw new TimeoutException(
+ $"RavenDB Cloud product '{deployment.ProductName}' was still '{details.Status}' after {deployment.ProvisioningTimeout}.");
+ }
+
+ // The Cloud API accepts about one request per second.
+ await Task.Delay(deployment.PollInterval, cancellationToken).ConfigureAwait(false);
+ details = null;
+ }
+ }
+
+ /// The URLs of the product's nodes; the API lists host names without a scheme.
+ internal static IReadOnlyList GetNodeUrls(ProductDetails details) =>
+ details.Dns?
+ .Where(d => !string.IsNullOrWhiteSpace(d))
+ .Select(d => (d.Contains("://", StringComparison.Ordinal) ? d : "https://" + d).TrimEnd('/'))
+ .ToList() ?? [];
+
+ /// Takes the product's id, size and node URLs from its details.
+ private static void Resolve(RavenDBCloudDeployment deployment, string productId, ProductDetails details)
+ {
+ var urls = GetNodeUrls(details);
+
+ if (urls.Count == 0)
+ {
+ throw new InvalidOperationException($"RavenDB Cloud product '{deployment.ProductName}' is active but reports no URL.");
+ }
+
+ deployment.ProductId = productId;
+ deployment.NodeCount = Math.Max(details.NodeTags?.Count ?? 1, 1);
+ deployment.NodeUrls = urls;
+
+ // Every node, so that an application reaches the cluster while one node is down.
+ deployment.Endpoint.Value = string.Join(",", urls);
+ }
+
+ private static bool IsGone(string? status) => status is ProductStatus.Terminated or ProductStatus.Terminating;
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudSpec.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudSpec.cs
new file mode 100644
index 000000000..b566c3acd
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudSpec.cs
@@ -0,0 +1,210 @@
+using Aspire.Hosting;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// What a RavenDB Cloud product is made of: everything that decides its cost and where its data lives. Nothing here
+/// has a default: a deployment creates exactly this, and stops when an existing product differs from it.
+///
+///
+/// Create one with or . On every deployment the plan checks the spec
+/// against what RavenDB Cloud offers the account in the region and, when a value is not offered, lists the valid ones:
+/// the regions, the instance types with their size, and the release channels with their RavenDB version. RavenDB Cloud
+/// does not create free products through its API: attach to one created in the portal with
+/// PublishAsExistingRavenDBCloud.
+///
+[AspireExport(ExposeProperties = true)]
+public sealed class RavenDBCloudSpec
+{
+ private RavenDBCloudSpec(
+ RavenDBCloudTier tier,
+ RavenDBCloudProvider provider,
+ string region,
+ string instanceType,
+ int diskSizeInGb,
+ RavenDBCloudStorageType storageType,
+ RavenDBCloudDiskLayout diskLayout,
+ string releaseChannel,
+ int? iops,
+ int? throughput)
+ {
+ Tier = tier;
+ Provider = provider;
+ Region = region;
+ InstanceType = instanceType;
+ DiskSizeInGb = diskSizeInGb;
+ StorageType = storageType;
+ DiskLayout = diskLayout;
+ ReleaseChannel = releaseChannel;
+ Iops = iops;
+ Throughput = throughput;
+ }
+
+ /// The product tier.
+ public RavenDBCloudTier Tier { get; }
+
+ /// The cloud provider.
+ public RavenDBCloudProvider Provider { get; }
+
+ /// The provider region, such as eu-central-1 on AWS or westeurope on Azure.
+ public string Region { get; }
+
+ /// The instance type, such as Dev10 or P20.
+ public string InstanceType { get; }
+
+ /// The data disk size in GB.
+ public int DiskSizeInGb { get; }
+
+ /// The data disk type.
+ public RavenDBCloudStorageType StorageType { get; }
+
+ /// Where the data lives: on the system disk or on a data disk of its own.
+ public RavenDBCloudDiskLayout DiskLayout { get; }
+
+ /// The release channel, which decides the RavenDB version line, such as Stable72.
+ public string ReleaseChannel { get; }
+
+ /// Provisioned IOPS of a premium disk; uses the provider's default.
+ public int? Iops { get; }
+
+ /// Provisioned throughput of a premium disk, in MB/s; uses the provider's default.
+ public int? Throughput { get; }
+
+ /// A development tier product: one node, no automatic backups.
+ /// The cloud provider.
+ /// The provider's region code, such as eu-central-1 on AWS or westeurope on Azure.
+ /// The instance type, such as Dev10.
+ /// The data disk size in GB; each instance type offers its own sizes.
+ /// The data disk type.
+ /// Where the data lives; RavenDB Cloud decides which layouts the tier and instance type allow.
+ /// The release channel, which decides the RavenDB version line, such as Stable72.
+ /// Provisioned IOPS of a premium disk; omit for the provider's default.
+ /// Provisioned throughput of a premium disk in MB/s; omit for the provider's default.
+ /// The specification.
+ [AspireExportIgnore(Reason = "Polyglot AppHosts choose the spec with RavenDBCloudSpecBuilder.")]
+ public static RavenDBCloudSpec Development(
+ RavenDBCloudProvider provider,
+ string region,
+ string instanceType,
+ int diskSizeInGb,
+ RavenDBCloudStorageType storageType,
+ RavenDBCloudDiskLayout diskLayout,
+ string releaseChannel,
+ int? iops = null,
+ int? throughput = null) =>
+ Paid(RavenDBCloudTier.Development, provider, region, instanceType, diskSizeInGb, storageType, diskLayout, releaseChannel, iops, throughput);
+
+ /// A production tier product: three nodes and automatic backups.
+ /// The cloud provider.
+ /// The provider's region code, such as eu-central-1 on AWS or westeurope on Azure.
+ /// The instance type, such as P20.
+ /// The data disk size in GB; each instance type offers its own sizes.
+ /// The data disk type.
+ /// Where the data lives; RavenDB Cloud decides which layouts the tier and instance type allow.
+ /// The release channel, which decides the RavenDB version line, such as Stable72.
+ /// Provisioned IOPS of a premium disk; omit for the provider's default.
+ /// Provisioned throughput of a premium disk in MB/s; omit for the provider's default.
+ /// The specification.
+ [AspireExportIgnore(Reason = "Polyglot AppHosts choose the spec with RavenDBCloudSpecBuilder.")]
+ public static RavenDBCloudSpec Production(
+ RavenDBCloudProvider provider,
+ string region,
+ string instanceType,
+ int diskSizeInGb,
+ RavenDBCloudStorageType storageType,
+ RavenDBCloudDiskLayout diskLayout,
+ string releaseChannel,
+ int? iops = null,
+ int? throughput = null) =>
+ Paid(RavenDBCloudTier.Production, provider, region, instanceType, diskSizeInGb, storageType, diskLayout, releaseChannel, iops, throughput);
+
+ private static RavenDBCloudSpec Paid(
+ RavenDBCloudTier tier,
+ RavenDBCloudProvider provider,
+ string region,
+ string instanceType,
+ int diskSizeInGb,
+ RavenDBCloudStorageType storageType,
+ RavenDBCloudDiskLayout diskLayout,
+ string releaseChannel,
+ int? iops,
+ int? throughput)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(region);
+ ArgumentException.ThrowIfNullOrWhiteSpace(instanceType);
+ ArgumentException.ThrowIfNullOrWhiteSpace(releaseChannel);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(diskSizeInGb);
+
+ if (iops is { } i)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(i, nameof(iops));
+ }
+
+ if (throughput is { } t)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(t, nameof(throughput));
+ }
+
+ return new(tier, provider, region.Trim(), instanceType.Trim(), diskSizeInGb, storageType, diskLayout, releaseChannel.Trim(), iops, throughput);
+ }
+
+ /// One line for logs and the plan, such as Development Dev10, Aws eu-central-1, 20 GB SsdStandard on SingleDataDisk, channel Stable72.
+ public override string ToString()
+ {
+ var performance = (Iops, Throughput) switch
+ {
+ (null, null) => string.Empty,
+ ({ } i, null) => $" ({i} IOPS)",
+ (null, { } t) => $" ({t} MB/s)",
+ ({ } i, { } t) => $" ({i} IOPS, {t} MB/s)",
+ };
+ return $"{Tier} {InstanceType}, {Provider} {Region}, {DiskSizeInGb} GB {StorageType}{performance} on {DiskLayout}, channel {ReleaseChannel}";
+ }
+}
+
+///
+/// Chooses the of a product in a polyglot AppHost, which cannot call the static
+/// factories: call exactly one of its methods.
+///
+[AspireExport(ExposeMethods = true)]
+public sealed class RavenDBCloudSpecBuilder
+{
+ /// The spec the callback chose; until it chooses one.
+ internal RavenDBCloudSpec? Spec { get; private set; }
+
+ /// Chooses : one node, no automatic backups.
+ /// The cloud provider.
+ /// The provider's region code, such as eu-central-1 on AWS or westeurope on Azure.
+ /// The instance type, such as Dev10.
+ /// The data disk size in GB; each instance type offers its own sizes.
+ /// The data disk type.
+ /// Where the data lives; RavenDB Cloud decides which layouts the tier and instance type allow.
+ /// The release channel, which decides the RavenDB version line, such as Stable72.
+ /// Provisioned IOPS of a premium disk; omit for the provider's default.
+ /// Provisioned throughput of a premium disk in MB/s; omit for the provider's default.
+ public void Development(RavenDBCloudProvider provider, string region, string instanceType, int diskSizeInGb, RavenDBCloudStorageType storageType, RavenDBCloudDiskLayout diskLayout, string releaseChannel, int? iops = null, int? throughput = null) =>
+ Choose(RavenDBCloudSpec.Development(provider, region, instanceType, diskSizeInGb, storageType, diskLayout, releaseChannel, iops, throughput));
+
+ /// Chooses : three nodes and automatic backups.
+ /// The cloud provider.
+ /// The provider's region code, such as eu-central-1 on AWS or westeurope on Azure.
+ /// The instance type, such as P20.
+ /// The data disk size in GB; each instance type offers its own sizes.
+ /// The data disk type.
+ /// Where the data lives; RavenDB Cloud decides which layouts the tier and instance type allow.
+ /// The release channel, which decides the RavenDB version line, such as Stable72.
+ /// Provisioned IOPS of a premium disk; omit for the provider's default.
+ /// Provisioned throughput of a premium disk in MB/s; omit for the provider's default.
+ public void Production(RavenDBCloudProvider provider, string region, string instanceType, int diskSizeInGb, RavenDBCloudStorageType storageType, RavenDBCloudDiskLayout diskLayout, string releaseChannel, int? iops = null, int? throughput = null) =>
+ Choose(RavenDBCloudSpec.Production(provider, region, instanceType, diskSizeInGb, storageType, diskLayout, releaseChannel, iops, throughput));
+
+ private void Choose(RavenDBCloudSpec spec)
+ {
+ if (Spec is not null)
+ {
+ throw new InvalidOperationException($"The RavenDB Cloud product is already specified as {Spec}; call one method of RavenDBCloudSpecBuilder only.");
+ }
+
+ Spec = spec;
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudValues.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudValues.cs
new file mode 100644
index 000000000..0bb43b3ba
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBCloudValues.cs
@@ -0,0 +1,39 @@
+using Aspire.Hosting.ApplicationModel;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// A value the RavenDB Cloud deployment only knows once it has found or created the product. The published artifacts
+/// carry a placeholder for it (in Docker Compose, a variable of the .env file); aspire deploy sets it before the
+/// compute environments resolve their values.
+///
+/// The manifest expression, such as {ravendb.url}; Docker Compose names the variable after it.
+internal abstract class RavenDBCloudDeployTimeValue(string expression) : IValueProvider, IManifestExpressionProvider
+{
+ /// The value; until the deployment sets it.
+ public string? Value { get; set; }
+
+ ///
+ public string ValueExpression { get; } = expression;
+
+ ///
+ public ValueTask GetValueAsync(CancellationToken cancellationToken = default) => new(Value);
+
+ /// The manifest expression.
+ public override string ToString() => ValueExpression;
+}
+
+/// The URL of the product.
+internal sealed class RavenDBCloudEndpoint(RavenDBServerResource server)
+ : RavenDBCloudDeployTimeValue($"{{{server.Name}.url}}");
+
+/// An application's client certificate, as base64-encoded .pfx content.
+internal sealed class RavenDBCloudCertificate(RavenDBServerResource server, IResource consumer)
+ : RavenDBCloudDeployTimeValue($"{{{server.Name}-{consumer.Name}.certificate}}")
+{
+ /// The application the certificate is for.
+ public IResource Consumer { get; } = consumer;
+
+ /// The thumbprint of the certificate in .
+ public string? Thumbprint { get; set; }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBServerAdministration.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBServerAdministration.cs
new file mode 100644
index 000000000..92e6e715f
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud/RavenDBServerAdministration.cs
@@ -0,0 +1,197 @@
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using Raven.Client.Documents;
+using Raven.Client.Documents.Conventions;
+using Raven.Client.Exceptions;
+using Raven.Client.Exceptions.Security;
+using Raven.Client.ServerWide;
+using Raven.Client.ServerWide.Operations;
+using Raven.Client.ServerWide.Operations.Certificates;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud;
+
+///
+/// The server-side operations a deployment performs on a RavenDB Cloud product, authenticated with the product's
+/// admin certificate. Behind an interface so the deployment logic can be tested without a server.
+///
+internal interface IRavenDBServerAdministration : IDisposable
+{
+ /// Succeeds once the server answers an authenticated request.
+ Task PingAsync(CancellationToken cancellationToken);
+
+ Task DatabaseExistsAsync(string database, CancellationToken cancellationToken);
+
+ /// when the database was created concurrently.
+ Task CreateDatabaseAsync(string database, int replicationFactor, CancellationToken cancellationToken);
+
+ /// The registered certificates whose name starts with .
+ Task> GetCertificatesAsync(string namePrefix, CancellationToken cancellationToken);
+
+ /// Creates a client certificate with clearance.
+ /// The bundle the server returns (a zip with the .pfx).
+ Task CreateClientCertificateAsync(string name, IReadOnlyDictionary permissions, CancellationToken cancellationToken);
+
+ /// Removes a certificate; one that is already gone is not an error.
+ Task DeleteCertificateAsync(string thumbprint, CancellationToken cancellationToken);
+}
+
+/// A certificate the server trusts. Database names in compare case-insensitively.
+internal sealed record RegisteredCertificate(
+ string Name,
+ string Thumbprint,
+ SecurityClearance Clearance,
+ IReadOnlyDictionary Permissions);
+
+/// Connects to a product's server.
+internal interface IRavenDBServerAdministrationFactory
+{
+ ///
+ /// Connects to the cluster of , its nodes. stays the caller's
+ /// and must outlive every connection: the RavenDB client caches its HTTP clients per certificate thumbprint, with the
+ /// first instance.
+ ///
+ IRavenDBServerAdministration Create(IReadOnlyList urls, X509Certificate2? certificate);
+}
+
+/// Connects with the RavenDB client.
+internal sealed class RavenDBServerAdministrationFactory : IRavenDBServerAdministrationFactory
+{
+ ///
+ public IRavenDBServerAdministration Create(IReadOnlyList urls, X509Certificate2? certificate) =>
+ new RavenDBServerAdministration(urls, certificate);
+}
+
+///
+/// Uses the RavenDB client, so the server certificate is validated the way every RavenDB client validates it:
+/// RequestExecutor.RemoteCertificateValidationCallback applies.
+///
+internal sealed class RavenDBServerAdministration : IRavenDBServerAdministration
+{
+ private readonly DocumentStore _store;
+
+ public RavenDBServerAdministration(IReadOnlyList urls, X509Certificate2? certificate)
+ {
+ _store = new DocumentStore
+ {
+ Urls = [.. urls],
+ Certificate = certificate,
+ // The certificate is the deployment's, shared by every connection: a store disposes its own by default.
+ Conventions = new DocumentConventions { DisposeCertificate = false },
+ };
+ _store.Initialize();
+ }
+
+ private ServerOperationExecutor Server => _store.Maintenance.Server;
+
+ ///
+ /// Whether means the server did not answer, which waiting can fix, rather than that it
+ /// refused the connection or the request, which waiting cannot.
+ ///
+ public static bool IsUnreachable(Exception exception)
+ {
+ var all = Flatten(exception).ToList();
+
+ // A rejected TLS handshake, a certificate that cannot be used, or one RavenDB refuses (its SecurityException).
+ return !all.Any(e => e is System.Security.Authentication.AuthenticationException or CryptographicException or SecurityException) &&
+ all.Any(e => e is HttpRequestException or SocketException or TimeoutException);
+ }
+
+ private static IEnumerable Flatten(Exception exception)
+ {
+ yield return exception;
+
+ IEnumerable inner = exception switch
+ {
+ AggregateException aggregate => aggregate.InnerExceptions,
+ { InnerException: { } single } => [single],
+ _ => [],
+ };
+
+ foreach (var nested in inner.SelectMany(Flatten))
+ {
+ yield return nested;
+ }
+ }
+
+ ///
+ public async Task PingAsync(CancellationToken cancellationToken) =>
+ await Server.SendAsync(new GetDatabaseNamesOperation(0, 1), cancellationToken).ConfigureAwait(false);
+
+ ///
+ public async Task DatabaseExistsAsync(string database, CancellationToken cancellationToken) =>
+ await Server.SendAsync(new GetDatabaseRecordOperation(database), cancellationToken).ConfigureAwait(false) is not null;
+
+ ///
+ public async Task CreateDatabaseAsync(string database, int replicationFactor, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await Server.SendAsync(new CreateDatabaseOperation(new DatabaseRecord(database), replicationFactor), cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+ catch (ConcurrencyException)
+ {
+ return false;
+ }
+ }
+
+ ///
+ public async Task> GetCertificatesAsync(string namePrefix, CancellationToken cancellationToken)
+ {
+ const int PageSize = 1024;
+ var certificates = new List();
+
+ for (var start = 0; ; start += PageSize)
+ {
+ var page = await Server.SendAsync(new GetCertificatesOperation(start, PageSize), cancellationToken).ConfigureAwait(false);
+
+ certificates.AddRange(page
+ .Where(c => c.Name?.StartsWith(namePrefix, StringComparison.OrdinalIgnoreCase) == true)
+ .Select(c => new RegisteredCertificate(
+ c.Name,
+ c.Thumbprint,
+ c.SecurityClearance,
+ // Database names are case-insensitive in RavenDB.
+ new Dictionary(c.Permissions ?? [], StringComparer.OrdinalIgnoreCase))));
+
+ if (page.Length < PageSize)
+ {
+ return certificates;
+ }
+ }
+ }
+
+ ///
+ public async Task CreateClientCertificateAsync(string name, IReadOnlyDictionary permissions, CancellationToken cancellationToken)
+ {
+ var certificate = await Server.SendAsync(
+ new CreateClientCertificateOperation(name, new Dictionary(permissions), SecurityClearance.ValidUser, password: null),
+ cancellationToken).ConfigureAwait(false);
+
+ return certificate.RawData;
+ }
+
+ ///
+ public async Task DeleteCertificateAsync(string thumbprint, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await Server.SendAsync(new DeleteCertificateOperation(thumbprint), cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException && IsAlreadyGone(exception))
+ {
+ // Removed concurrently, or by hand in the Studio: the goal is reached.
+ }
+ }
+
+ private static bool IsAlreadyGone(Exception exception) =>
+ exception.Message.Contains("not found", StringComparison.OrdinalIgnoreCase) ||
+ exception.Message.Contains("does not exist", StringComparison.OrdinalIgnoreCase);
+
+ /// Disposes the document store; the certificate stays the caller's.
+ public void Dispose()
+ {
+ _store.Dispose();
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB/README.md b/src/CommunityToolkit.Aspire.Hosting.RavenDB/README.md
index f17c98e7f..b9f1d2b56 100644
--- a/src/CommunityToolkit.Aspire.Hosting.RavenDB/README.md
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB/README.md
@@ -27,6 +27,10 @@ var myService = builder.AddProject()
Every database added with `AddDatabase(...)` exposes a clickable **RavenDB Studio** link in the Aspire dashboard that opens that database's Documents view directly (for example `http://localhost:9534/studio/index.html#databases/documents?&database=mydb`). The link is added automatically — no extra configuration is required. For secured servers it uses the configured public server URL.
+### Deploy to RavenDB Cloud
+
+`aspire run` starts RavenDB in a local container. To deploy the applications against a RavenDB Cloud product, add the [CommunityToolkit.Aspire.Hosting.RavenDB.Cloud](https://www.nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud) package and call `PublishAsRavenDBCloud(...)` on the server: `aspire deploy` then creates or finds the product and gives every application the product URL and a client certificate of its own.
+
## Additional documentation
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBBuilderExtensions.cs
index a26cdb2d2..37b737851 100644
--- a/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBBuilderExtensions.cs
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBBuilderExtensions.cs
@@ -12,7 +12,7 @@ namespace Aspire.Hosting;
///
/// Provides extension methods for adding RavenDB resources to an .
///
-public static class RavenDBBuilderExtensions
+public static partial class RavenDBBuilderExtensions
{
///
/// Configures the host port that the RavenDB resource is exposed on instead of using randomly assigned port.
@@ -251,7 +251,7 @@ public static IResourceBuilder AddDatabase(this IResour
// Use the resource name as the database name if it's not provided
databaseName ??= name;
- builder.Resource.AddDatabase(name, databaseName);
+ builder.Resource.AddDatabase(name, databaseName, ensureCreated);
var databaseResource = new RavenDBDatabaseResource(name, databaseName, builder.Resource);
string? connectionString = null;
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBPublishStrategy.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBPublishStrategy.cs
new file mode 100644
index 000000000..6ae890e1b
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBPublishStrategy.cs
@@ -0,0 +1,69 @@
+using System.ComponentModel;
+using System.Diagnostics.CodeAnalysis;
+using Aspire.Hosting.ApplicationModel;
+
+namespace Aspire.Hosting.ApplicationModel
+{
+ ///
+ /// How a deployment package, such as the RavenDB Cloud one, publishes a RavenDB server instead of its container.
+ ///
+ /// The method that chose the strategy, as error messages name it, such as PublishAsRavenDBCloud.
+ /// Where the applications connect once deployed; it may only be known at deploy time.
+ [Experimental("CTASPIRERAVENDB001")]
+ public sealed record RavenDBPublishStrategy(string Name, ReferenceExpression Url);
+}
+
+namespace Aspire.Hosting
+{
+ public static partial class RavenDBBuilderExtensions
+ {
+ ///
+ /// For deployment packages: publishes the server with instead of its container. The
+ /// container is left out of the published artifacts, and the applications that reference the server connect to
+ /// the strategy's URL. A server has one strategy. AppHosts call the deployment package's own method, such as
+ /// PublishAsRavenDBCloud.
+ ///
+ /// The resource builder for the RavenDB server.
+ /// The strategy.
+ /// The for the RavenDB server resource.
+ [Experimental("CTASPIRERAVENDB001")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [AspireExportIgnore(Reason = "Deployment packages call it; AppHosts call their own publish methods, such as PublishAsRavenDBCloud.")]
+ public static IResourceBuilder WithPublishStrategy(
+ this IResourceBuilder builder,
+ RavenDBPublishStrategy strategy)
+ {
+ ArgumentNullException.ThrowIfNull(builder);
+ ArgumentNullException.ThrowIfNull(strategy);
+
+ builder.Resource.UsePublishStrategy(strategy);
+ builder.ExcludeFromManifest();
+
+ // WaitFor(server) waits for the local container. Published, there is no container to wait for, and an
+ // environment such as Docker Compose rejects a dependency on a service it does not have.
+ builder.ApplicationBuilder.Eventing.Subscribe((@event, _) =>
+ {
+ foreach (var resource in @event.Model.Resources)
+ {
+ var waits = resource.Annotations
+ .OfType()
+ .Where(wait => IsServerOrItsDatabase(wait.Resource, builder.Resource))
+ .ToList();
+
+ foreach (var wait in waits)
+ {
+ resource.Annotations.Remove(wait);
+ }
+ }
+
+ return Task.CompletedTask;
+ });
+
+ return builder;
+ }
+
+ private static bool IsServerOrItsDatabase(IResource resource, RavenDBServerResource server) =>
+ ReferenceEquals(resource, server) ||
+ (resource is RavenDBDatabaseResource database && ReferenceEquals(database.Parent, server));
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBServerResource.cs b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBServerResource.cs
index 729e48d45..95f2526d6 100644
--- a/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBServerResource.cs
+++ b/src/CommunityToolkit.Aspire.Hosting.RavenDB/RavenDBServerResource.cs
@@ -1,5 +1,8 @@
+using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.X509Certificates;
+using CommunityToolkit.Aspire.Hosting.RavenDB;
+#pragma warning disable CTASPIRERAVENDB001 // The deployment packages' API is this package's own
namespace Aspire.Hosting.ApplicationModel;
@@ -65,6 +68,9 @@ public ReferenceExpression ConnectionStringExpression
{
get
{
+ if (PublishStrategy is { } strategy)
+ return ReferenceExpression.Create($"URL={strategy.Url}");
+
if (IsSecured && !string.IsNullOrEmpty(PublicServerUrl))
return ReferenceExpression.Create($"URL={PublicServerUrl}");
@@ -79,9 +85,40 @@ public ReferenceExpression ConnectionStringExpression
///
/// Format: http://{host}:{port} or https://{host}:{port} depending on security settings.
///
- public ReferenceExpression UriExpression => ReferenceExpression.Create($"{(IsSecured ? "https://" : "http://")}{Host}:{Port}");
+ public ReferenceExpression UriExpression =>
+ PublishStrategy?.Url ?? ReferenceExpression.Create($"{(IsSecured ? "https://" : "http://")}{Host}:{Port}");
+
+ ///
+ /// For deployment packages: the strategy that publishes the server somewhere else than its container, such as
+ /// RavenDB Cloud. means the container itself is published.
+ ///
+ ///
+ /// While it is set, the connection string and point at the strategy's URL. The endpoint
+ /// properties (, , ) still describe the local
+ /// container, which aspire run starts.
+ ///
+ [Experimental("CTASPIRERAVENDB001")]
+ [AspireExportIgnore(Reason = "For deployment packages, not AppHosts.")]
+ public RavenDBPublishStrategy? PublishStrategy { get; private set; }
+
+ ///
+ /// Publishes the server with instead of its container. A server has one strategy.
+ ///
+ internal void UsePublishStrategy(RavenDBPublishStrategy strategy)
+ {
+ if (PublishStrategy is { } existing)
+ {
+ throw new DistributedApplicationException(
+ $"RavenDB server '{Name}' is already published with {existing.Name}, so it cannot also be published with " +
+ $"{strategy.Name}. A server has one publish strategy; to use a different one per environment, choose it " +
+ "with an if in the AppHost.");
+ }
+
+ PublishStrategy = strategy;
+ }
private readonly Dictionary _databases = new();
+ private readonly HashSet _databasesToCreate = new(StringComparer.Ordinal);
///
/// Gets a read-only dictionary of databases associated with this server resource.
@@ -94,13 +131,34 @@ public ReferenceExpression ConnectionStringExpression
///
/// The name of the resource to associate with the database.
/// The name of the database to add.
- internal void AddDatabase(string name, string databaseName)
+ /// Whether the database is created when the server starts.
+ internal void AddDatabase(string name, string databaseName, bool ensureCreated = false)
{
_databases.TryAdd(name, databaseName);
+
+ if (ensureCreated)
+ {
+ _databasesToCreate.Add(databaseName);
+ }
}
+ ///
+ /// For deployment packages: the names of the databases declared with ensureCreated: true. The AppHost creates
+ /// them in run mode; a publish strategy that deploys the server creates them where it deploys it.
+ ///
+ [Experimental("CTASPIRERAVENDB001")]
+ [AspireExportIgnore(Reason = "For deployment packages, not AppHosts.")]
+ public IReadOnlyCollection DatabasesToCreate => _databasesToCreate;
+
IEnumerable> IResourceWithConnectionString.GetConnectionProperties()
{
+ if (PublishStrategy is { } strategy)
+ {
+ // Host and port of a server published elsewhere are not known separately.
+ yield return new("Uri", strategy.Url);
+ yield break;
+ }
+
yield return new("Host", ReferenceExpression.Create($"{Host}"));
yield return new("Port", ReferenceExpression.Create($"{Port}"));
yield return new("Uri", UriExpression);
diff --git a/src/CommunityToolkit.Aspire.RavenDB.Client/DatabaseExistsOperation.cs b/src/CommunityToolkit.Aspire.RavenDB.Client/DatabaseExistsOperation.cs
new file mode 100644
index 000000000..269d87b51
--- /dev/null
+++ b/src/CommunityToolkit.Aspire.RavenDB.Client/DatabaseExistsOperation.cs
@@ -0,0 +1,34 @@
+using Raven.Client.Documents.Conventions;
+using Raven.Client.Http;
+using Raven.Client.ServerWide.Operations;
+using Sparrow.Json;
+
+namespace CommunityToolkit.Aspire.RavenDB.Client;
+
+///
+/// Whether a database exists, asked about that one database. Every certificate may ask, also one limited to its own
+/// databases, which cannot read database records; the answer needs no paging through the server's databases; and a
+/// sharded database is found by its own name, where the list of names holds its shards.
+///
+/// The name of the database.
+internal sealed class DatabaseExistsOperation(string database) : IServerOperation
+{
+ ///
+ public RavenCommand GetCommand(DocumentConventions conventions, JsonOperationContext context) => new DatabaseExistsCommand(database);
+
+ private sealed class DatabaseExistsCommand(string database) : RavenCommand
+ {
+ public override bool IsReadRequest => true;
+
+ public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
+ {
+ url = $"{node.Url}/databases?name={Uri.EscapeDataString(database)}&namesOnly=true";
+
+ return new HttpRequestMessage { Method = HttpMethod.Get };
+ }
+
+ // The server answers 404 when there is no such database, which the request executor passes on as no response.
+ public override void SetResponse(JsonOperationContext context, BlittableJsonReaderObject response, bool fromCache) =>
+ Result = response is not null;
+ }
+}
diff --git a/src/CommunityToolkit.Aspire.RavenDB.Client/README.md b/src/CommunityToolkit.Aspire.RavenDB.Client/README.md
index 6581f123a..5ea84ce6f 100644
--- a/src/CommunityToolkit.Aspire.RavenDB.Client/README.md
+++ b/src/CommunityToolkit.Aspire.RavenDB.Client/README.md
@@ -64,9 +64,21 @@ And then the connection string will be retrieved from the `ConnectionStrings` co
}
```
+For a cluster, list its nodes separated by commas, for example `URL=https://a.example.com,https://b.example.com,https://c.example.com`: the client then reaches the cluster even while one node is down.
+
### Use configuration providers
-The Aspire RavenDB Client component supports [Microsoft.Extensions.Configuration](https://learn.microsoft.com/dotnet/api/microsoft.extensions.configuration). It loads the `RavenDBClientSettings` from configuration by using the `Aspire:RavenDB:Client` key.
+The Aspire RavenDB Client component supports [Microsoft.Extensions.Configuration](https://learn.microsoft.com/dotnet/api/microsoft.extensions.configuration). It loads the `RavenDBClientSettings` from configuration by using the `Aspire:RavenDB:Client` key, and then the `Aspire:RavenDB:Client:{connection name}` key.
+
+### Client certificate from configuration
+
+A secured server needs a client certificate. Configuration can give it as a file (`CertificatePath`, with `CertificatePassword` if the file has one) or as the base64-encoded content of a .pfx file (`CertificateBase64`), which suits a certificate delivered as a value, such as an environment variable:
+
+```
+Aspire__RavenDB__Client__ravendb__CertificateBase64=MIIK...
+```
+
+`Certificate` set in code is used first, then `CertificateBase64`, then `CertificatePath`. The [RavenDB Cloud hosting integration](https://www.nuget.org/packages/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud) delivers every application its certificate this way.
### Use inline delegates
@@ -85,7 +97,7 @@ builder.AddRavenDBClient("ravendb", settings =>
The RavenDBClientSettings class simplifies configuration by allowing you to specify:
- URLs of your RavenDB nodes.
- Database name to connect to or create.
-- Certificate details (via `CertificatePath` and `CertificatePassword` or `Certificate`).
+- Certificate details (via `Certificate`, `CertificateBase64` or `CertificatePath`, with `CertificatePassword`).
- Optional actions to modify the `IDocumentStore`.
Example for creating a new database on a local unsecured RavenDB server:
diff --git a/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientExtension.cs b/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientExtension.cs
index c9e2e61a1..b813463d1 100644
--- a/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientExtension.cs
+++ b/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientExtension.cs
@@ -213,14 +213,11 @@ private static IDocumentStore CreateRavenClient(RavenDBClientSettings ravenDbCli
documentStore.Initialize();
- if (ravenDbClientSettings.CreateDatabase)
+ if (ravenDbClientSettings.CreateDatabase &&
+ !documentStore.Maintenance.Server.Send(new DatabaseExistsOperation(ravenDbClientSettings.DatabaseName!)))
{
- var databaseRecord = documentStore.Maintenance.Server.Send(new GetDatabaseRecordOperation(ravenDbClientSettings.DatabaseName));
- if (databaseRecord == null)
- {
- var newDatabaseRecord = new DatabaseRecord(ravenDbClientSettings.DatabaseName);
- documentStore.Maintenance.Server.Send(new CreateDatabaseOperation(newDatabaseRecord));
- }
+ var newDatabaseRecord = new DatabaseRecord(ravenDbClientSettings.DatabaseName);
+ documentStore.Maintenance.Server.Send(new CreateDatabaseOperation(newDatabaseRecord));
}
return documentStore;
@@ -251,9 +248,10 @@ private static RavenDBClientSettings GetRavenDBClientSettings(this IHostApplicat
ConnectionString = connectionString
};
+ // The nodes of a cluster, separated by commas: the client reaches the cluster through any of them.
if (connectionBuilder.TryGetValue("URL", out var url) && url is string serverUrl)
{
- settings.Urls = new[] { serverUrl };
+ settings.Urls = serverUrl.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
}
if (connectionBuilder.TryGetValue("Database", out var database) && database is string databaseName)
@@ -287,9 +285,10 @@ private static void ValidateSettings(
if (uri!.Scheme == Uri.UriSchemeHttps)
{
- if (string.IsNullOrEmpty(settings.CertificatePath) && settings.Certificate == null)
- throw new ArgumentNullException(nameof(settings.Certificate), "A valid certificate must be provided in 'RavenDBClientSettings.Certificate' " +
- "or a certificate path in 'RavenDBClientSettings.CertificatePath' when using HTTPS.");
+ if (!settings.HasCertificate)
+ throw new ArgumentNullException(nameof(settings.Certificate), "A valid certificate must be provided in 'RavenDBClientSettings.Certificate', " +
+ "its base64-encoded .pfx content in 'RavenDBClientSettings.CertificateBase64' or a certificate path in " +
+ "'RavenDBClientSettings.CertificatePath' when using HTTPS.");
}
}
diff --git a/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientSettings.cs b/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientSettings.cs
index a923c9906..9632977f6 100644
--- a/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientSettings.cs
+++ b/src/CommunityToolkit.Aspire.RavenDB.Client/RavenDBClientSettings.cs
@@ -1,4 +1,5 @@
using Raven.Client.Documents;
+using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace CommunityToolkit.Aspire.RavenDB.Client;
@@ -28,6 +29,14 @@ public sealed class RavenDBClientSettings
///
public X509Certificate2? Certificate { get; set; }
+ ///
+ /// The client certificate as base64-encoded PKCS #12 (.pfx) content, protected by
+ /// if it has one. Deployments that deliver the certificate as a value instead of a file, such as RavenDB Cloud
+ /// through the Aspire hosting integration, set it through configuration
+ /// (Aspire:RavenDB:Client:{connection name}:CertificateBase64).
+ ///
+ public string? CertificateBase64 { get; set; }
+
///
/// The name of the database to connect to.
///
@@ -36,6 +45,7 @@ public sealed class RavenDBClientSettings
///
/// Gets or sets a value indicating whether a new database should be created if it does not already exist.
/// If set to and a database with the specified name already exists, the existing database will be used.
+ /// Creating one needs a certificate with server-wide (Operator) access; checking that it exists does not.
/// The default value is .
///
public bool CreateDatabase { get; set; }
@@ -63,15 +73,51 @@ public sealed class RavenDBClientSettings
public bool DisableTracing { get; set; }
///
- /// Retrieves the used for authentication, if a certificate path is specified.
+ /// Whether a client certificate is configured in any of the supported ways.
///
- /// An instance if the is specified;
- /// otherwise, .
+ internal bool HasCertificate =>
+ Certificate != null || !string.IsNullOrEmpty(CertificateBase64) || !string.IsNullOrEmpty(CertificatePath);
+
+ ///
+ /// Retrieves the used for authentication: , else the one in
+ /// , else the one at .
+ ///
+ /// The certificate, or when none is configured.
internal X509Certificate2? GetCertificate()
{
if (Certificate != null)
return Certificate;
+ if (!string.IsNullOrEmpty(CertificateBase64))
+ {
+ byte[] content;
+
+ try
+ {
+ content = Convert.FromBase64String(CertificateBase64);
+ }
+ catch (FormatException)
+ {
+ // The value is a secret: never echo it.
+ throw new InvalidOperationException(
+ "The RavenDB client certificate in 'CertificateBase64' is not valid base64. It has to be the base64-encoded content of a .pfx file.");
+ }
+
+ try
+ {
+#pragma warning disable SYSLIB0057
+ return new X509Certificate2(content, CertificatePassword);
+#pragma warning restore SYSLIB0057
+ }
+ catch (CryptographicException exception)
+ {
+ throw new InvalidOperationException(
+ $"The RavenDB client certificate in 'CertificateBase64' cannot be loaded: {exception.Message} It has to be the " +
+ "base64-encoded content of a .pfx file, with 'CertificatePassword' set if the file has a password.",
+ exception);
+ }
+ }
+
if (string.IsNullOrEmpty(CertificatePath))
{
return null;
diff --git a/src/Shared/RavenDB/RavenDBClientConfiguration.cs b/src/Shared/RavenDB/RavenDBClientConfiguration.cs
new file mode 100644
index 000000000..331458799
--- /dev/null
+++ b/src/Shared/RavenDB/RavenDBClientConfiguration.cs
@@ -0,0 +1,66 @@
+using Aspire.Hosting.ApplicationModel;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB;
+
+///
+/// The settings of the RavenDB client integration (CommunityToolkit.Aspire.RavenDB.Client) that a deployment package
+/// fills in for an application. The client reads them from Aspire:RavenDB:Client and from
+/// Aspire:RavenDB:Client:{connection name}.
+///
+internal static class RavenDBClientConfiguration
+{
+ /// The client certificate as base64 PKCS #12 (pfx) content.
+ public const string CertificateSetting = "CertificateBase64";
+
+ /// The environment variable of , for one connection or for all of them.
+ public static string Variable(string? connectionName, string setting) =>
+ connectionName is null
+ ? $"Aspire__RavenDB__Client__{setting}"
+ : $"Aspire__RavenDB__Client__{connectionName}__{setting}";
+
+ ///
+ /// Gives the application its client certificate as a value, such as one only known at deploy time, which each
+ /// compute environment delivers its own way (Docker Compose through its .env file).
+ ///
+ ///
+ /// The value goes under every name the application gets a connection string of by, also
+ /// one renamed with WithReference(db, connectionName: ...). When the application uses no other RavenDB server
+ /// it also goes to the default section.
+ ///
+ public static void DeliverCertificate(RavenDBConsumer consumer, RavenDBServerResource server, object certificate)
+ {
+ ArgumentNullException.ThrowIfNull(consumer);
+ ArgumentNullException.ThrowIfNull(server);
+ ArgumentNullException.ThrowIfNull(certificate);
+
+ consumer.Resource.Annotations.Add(new EnvironmentCallbackAnnotation(context =>
+ {
+ // WithReference has written the connection strings by now, under the names the application reads them by.
+ var names = context.EnvironmentVariables
+ .Where(v => v.Key.StartsWith(ConnectionStringsPrefix, StringComparison.Ordinal) && IsOf(server, v.Value))
+ .Select(v => v.Key[ConnectionStringsPrefix.Length..])
+ .ToList();
+
+ foreach (var name in names)
+ {
+ context.EnvironmentVariables[Variable(name, CertificateSetting)] = certificate;
+ }
+
+ if (consumer.ServersReferenced == 1)
+ {
+ context.EnvironmentVariables[Variable(null, CertificateSetting)] = certificate;
+ }
+ }));
+ }
+
+ private const string ConnectionStringsPrefix = "ConnectionStrings__";
+
+ /// Whether is the connection string of or one of its databases.
+ private static bool IsOf(RavenDBServerResource server, object value) =>
+ (value as ConnectionStringReference)?.Resource switch
+ {
+ RavenDBServerResource s => ReferenceEquals(s, server),
+ RavenDBDatabaseResource d => ReferenceEquals(d.Parent, server),
+ _ => false,
+ };
+}
diff --git a/src/Shared/RavenDB/RavenDBConsumers.cs b/src/Shared/RavenDB/RavenDBConsumers.cs
new file mode 100644
index 000000000..780309c95
--- /dev/null
+++ b/src/Shared/RavenDB/RavenDBConsumers.cs
@@ -0,0 +1,89 @@
+using Aspire.Hosting.ApplicationModel;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB;
+
+///
+/// A resource that references a RavenDB server or one of its databases.
+///
+/// The application.
+/// The databases it references; a reference to the server reaches every database declared on it.
+/// How many RavenDB servers the application references in total.
+internal sealed record RavenDBConsumer(
+ IResource Resource,
+ IReadOnlyList Databases,
+ int ServersReferenced);
+
+/// Finds the applications that use a RavenDB server, for a deployment package.
+internal static class RavenDBConsumers
+{
+ // What WithReference(...) records on the referencing resource; Aspire has no public constant for it.
+ private const string ReferenceRelationship = "Reference";
+
+ /// The resources that reference or one of its databases, except those left out of publish.
+ public static IReadOnlyList Find(DistributedApplicationModel model, RavenDBServerResource server)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ ArgumentNullException.ThrowIfNull(server);
+
+ var consumers = new List();
+
+ foreach (var resource in model.Resources)
+ {
+ // A resource left out of publish is not deployed, so it needs no URL or certificate.
+ if (resource is RavenDBServerResource or RavenDBDatabaseResource || resource.IsExcludedFromPublish())
+ {
+ continue;
+ }
+
+ var referencesServer = false;
+ var databases = new SortedSet(StringComparer.OrdinalIgnoreCase);
+ var servers = new HashSet();
+
+ foreach (var referenced in References(resource))
+ {
+ var referencedServer = referenced switch
+ {
+ RavenDBServerResource s => s,
+ RavenDBDatabaseResource d => d.Parent,
+ _ => null,
+ };
+
+ if (referencedServer is null)
+ {
+ continue;
+ }
+
+ servers.Add(referencedServer);
+
+ if (!ReferenceEquals(referencedServer, server))
+ {
+ continue;
+ }
+
+ referencesServer = true;
+
+ if (referenced is RavenDBDatabaseResource database)
+ {
+ databases.Add(database.DatabaseName);
+ }
+ else
+ {
+ databases.UnionWith(server.Databases.Values);
+ }
+ }
+
+ if (referencesServer)
+ {
+ consumers.Add(new RavenDBConsumer(resource, [.. databases], servers.Count));
+ }
+ }
+
+ return consumers;
+ }
+
+ private static IEnumerable References(IResource resource) =>
+ resource.Annotations
+ .OfType()
+ .Where(r => string.Equals(r.Type, ReferenceRelationship, StringComparison.Ordinal))
+ .Select(r => r.Resource);
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests.csproj b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests.csproj
new file mode 100644
index 000000000..0fc25b823
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests.csproj
@@ -0,0 +1,19 @@
+
+
+
+ $(NoWarn);CTASPIRERAVENDB001
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/Fakes.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/Fakes.cs
new file mode 100644
index 000000000..b4d2041a1
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/Fakes.cs
@@ -0,0 +1,511 @@
+using System.Collections.Concurrent;
+using System.IO.Compression;
+using System.Net;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Aspire.Hosting.Pipelines;
+using Microsoft.Extensions.Logging;
+using Raven.Client.ServerWide.Operations.Certificates;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+///
+/// An in-memory RavenDB Cloud API with the endpoints the integration calls, shaped after
+/// https://api.cloud.ravendb.net/api/v1/swagger.json.
+///
+internal sealed class FakeRavenDBCloudApi : HttpMessageHandler, IRavenDBCloudApiClientFactory
+{
+ private int _nextId;
+
+ public ConcurrentDictionary Products { get; } = new();
+
+ public List CreateRequests { get; } = [];
+
+ public List ChangeRequests { get; } = [];
+
+ public List TerminatedProductIds { get; } = [];
+
+ public List Requests { get; } = [];
+
+ /// The client admin certificate every product hands out.
+ public byte[] AdminCertificate { get; } = TestCertificates.CreatePfx("admin");
+
+ /// How many status checks a product reports "Creating" or "DeployingChanges" before it becomes "Active".
+ public int BusyPolls { get; set; } = 2;
+
+ /// Answers the next requests with these statuses before handling them, as a busy or failing API does.
+ public ConcurrentQueue Failures { get; } = new();
+
+ public FakeProduct AddProduct(string name, string status = "Active", string tier = "Development", string instanceType = "Dev10")
+ {
+ var id = $"product-{Interlocked.Increment(ref _nextId)}";
+
+ // Host names without a scheme, as the real API reports them.
+ var product = new FakeProduct(id, name)
+ {
+ Status = status,
+ Tier = tier,
+ InstanceType = instanceType,
+ Subdomain = RavenDBCloudDeployment.DeriveSubdomain(name),
+ Dns = [$"a.{name}.development.run"],
+ };
+ Products[id] = product;
+ return product;
+ }
+
+ public RavenDBCloudApiClient Create(string endpoint, string apiKey) =>
+ new(new HttpClient(this, disposeHandler: false), endpoint, apiKey) { RetryDelay = TimeSpan.FromMilliseconds(1) };
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ // As the real API's gateway does.
+ if (request.Headers.UserAgent.Count == 0)
+ {
+ return new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("403 Forbidden") };
+ }
+
+ var path = request.RequestUri!.AbsolutePath;
+
+ lock (Requests)
+ {
+ Requests.Add($"{request.Method} {path}");
+ }
+
+ if (Failures.TryDequeue(out var failure))
+ {
+ return new HttpResponseMessage(failure);
+ }
+
+ if (request.Method == HttpMethod.Get && path == "/api/v1/products/list")
+ {
+ // Like the real API, the list leaves out the products hidden in the portal.
+ return Json(new { items = Products.Values.Where(p => !p.Hidden).Select(p => new { id = p.Id, name = p.Name }) });
+ }
+
+ if (request.Method == HttpMethod.Get && path.StartsWith("/api/v1/products/details/", StringComparison.Ordinal))
+ {
+ if (!Products.TryGetValue(path.Split('/').Last(), out var product))
+ {
+ return new HttpResponseMessage(HttpStatusCode.NotFound);
+ }
+
+ if (product.Status is "Creating" or "DeployingChanges" && ++product.Polls >= BusyPolls)
+ {
+ product.Status = "Active";
+ product.Polls = 0;
+ }
+
+ return Json(new
+ {
+ id = product.Id,
+ displayName = product.Name,
+ subdomainName = product.Subdomain,
+ status = product.Status,
+ tier = product.Tier,
+ cloudProvider = product.Provider,
+ region = product.Region,
+ instanceType = product.InstanceType,
+ releaseChannel = product.ReleaseChannel,
+ // A product being created has no URL yet.
+ dns = product.Status == "Creating" ? [] : product.Dns,
+ nodeTags = product.NodeTags,
+ hardwareInfo = product.HasDataDisk
+ ? new
+ {
+ storage = new { size = 30, iops = (int?)3000, throughput = (double?)125, type = "SsdStandard" },
+ additionalStorage = new { size = product.DiskSize, iops = product.Iops, throughput = product.Throughput, type = product.StorageType, availableDiskSizes = product.ResizableTo },
+ }
+ : (object)new { storage = new { size = product.DiskSize, iops = product.Iops, throughput = product.Throughput, type = product.StorageType, availableDiskSizes = product.ResizableTo } },
+ security = new { allowedIps = product.AllowedIps },
+ });
+ }
+
+ if (request.Method == HttpMethod.Post && path == "/api/v1/products/create")
+ {
+ var body = await ReadAsync(request, cancellationToken);
+
+ lock (CreateRequests)
+ {
+ CreateRequests.Add(body);
+ }
+
+ // As the real API validates it: no free products, a disk layout, and a subdomain unique in the account.
+ if (body["tier"]?.GetValue() == "Free")
+ {
+ return Json(new { tier = new[] { "Creating Free product via API is not allowed." } }, HttpStatusCode.BadRequest);
+ }
+
+ if (body["diskLayout"]?.GetValue() is not ("RootOnly" or "SingleDataDisk"))
+ {
+ return Json(new { diskLayout = new[] { "DiskLayout is required." } }, HttpStatusCode.BadRequest);
+ }
+
+ var subdomain = body["subdomainName"]?.GetValue();
+
+ if (string.IsNullOrEmpty(subdomain))
+ {
+ return Json(new { subdomainName = new[] { "Subdomain Name is required." } }, HttpStatusCode.BadRequest);
+ }
+
+ // Names are unique among the products the portal shows, terminated ones included.
+ var name = body["displayName"]!.GetValue();
+
+ if (Products.Values.Any(p => !p.Hidden && string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)))
+ {
+ return Json(new { displayName = new[] { "Provided Display Name is already taken." } }, HttpStatusCode.BadRequest);
+ }
+
+ var product = AddProduct(body["displayName"]!.GetValue(), "Creating", body["tier"]!.GetValue(), body["instanceTypeName"]!.GetValue());
+ product.Subdomain = subdomain;
+ product.HasDataDisk = body["diskLayout"]!.GetValue() == "SingleDataDisk";
+ product.Provider = body["cloudProvider"]!.GetValue();
+ product.Region = body["region"]!.GetValue();
+ product.ReleaseChannel = body["releaseChannel"]?.GetValue();
+ product.DiskSize = body["diskSize"]!.GetValue();
+ product.StorageType = body["storageTypeName"]!.GetValue();
+ product.AllowedIps = [.. body["allowedIps"]!.AsArray().Select(n => n!.GetValue())];
+ return Json(new { productId = product.Id }, HttpStatusCode.Accepted);
+ }
+
+ if (request.Method == HttpMethod.Post && path == "/api/v1/products/instance-type")
+ {
+ var body = await ReadAsync(request, cancellationToken);
+ ChangeRequests.Add(body);
+ var product = Products[body["productId"]!.GetValue()];
+ product.InstanceType = body["instanceType"]!.GetValue();
+ product.Status = "DeployingChanges";
+ return new HttpResponseMessage(HttpStatusCode.Accepted);
+ }
+
+ if (request.Method == HttpMethod.Post && path == "/api/v1/products/storage")
+ {
+ var body = await ReadAsync(request, cancellationToken);
+ ChangeRequests.Add(body);
+ var product = Products[body["productId"]!.GetValue()];
+ product.DiskSize = body["size"]!.GetValue();
+ product.StorageType = body["storageType"]!.GetValue();
+ product.Status = "DeployingChanges";
+ return new HttpResponseMessage(HttpStatusCode.Accepted);
+ }
+
+ if (request.Method == HttpMethod.Post && path.StartsWith("/api/v1/products/terminate/", StringComparison.Ordinal))
+ {
+ var id = path.Split('/').Last();
+
+ lock (TerminatedProductIds)
+ {
+ TerminatedProductIds.Add(id);
+ }
+
+ // Like the real API, a terminated product stays in the list unless it is hidden.
+ if (!Products.TryGetValue(id, out var terminated))
+ {
+ return new HttpResponseMessage(HttpStatusCode.NotFound);
+ }
+
+ terminated.Status = "Terminated";
+ terminated.Hidden = (await ReadAsync(request, cancellationToken))["hideInPortal"]?.GetValue() == true;
+ return new HttpResponseMessage(HttpStatusCode.Accepted);
+ }
+
+ if (request.Method == HttpMethod.Get && path.StartsWith("/api/v1/metadata/regions/", StringComparison.Ordinal))
+ {
+ return path.EndsWith("/Aws", StringComparison.Ordinal)
+ ? Json(new { names = new[] { "us-east-1", "eu-central-1" } })
+ : Json(new { names = new[] { "westeurope", "northeurope" } });
+ }
+
+ if (request.Method == HttpMethod.Get && path.StartsWith("/api/v1/metadata/instance-types/", StringComparison.Ordinal))
+ {
+ var standard = new { name = "SsdStandard", iopsRange = (object?)null };
+ var premium = new { name = "SsdPremium", iopsRange = (object?)new { min = 3000, max = 16000 } };
+
+ return Json(new
+ {
+ instanceTypes = new object[]
+ {
+ new { name = "Free", tier = "Free", parameters = new { virtualCpus = 2, ram = 0.5, numberOfNodes = 1, availableDiskSizes = new[] { 10 }, availableStorageTypes = new[] { standard } } },
+ new { name = "Dev10", tier = "Development", parameters = new { virtualCpus = 2, ram = 2, numberOfNodes = 1, availableDiskSizes = new[] { 10, 20, 32 }, availableStorageTypes = new object[] { standard, premium } } },
+ new { name = "Dev20", tier = "Development", parameters = new { virtualCpus = 2, ram = 4, numberOfNodes = 1, availableDiskSizes = new[] { 20, 32, 64 }, availableStorageTypes = new object[] { standard, premium } } },
+ new { name = "P20", tier = "Production", parameters = new { virtualCpus = 4, ram = 8, numberOfNodes = 3, availableDiskSizes = new[] { 64, 128 }, availableStorageTypes = new object[] { standard, premium } } },
+ },
+ });
+ }
+
+ if (request.Method == HttpMethod.Get && path.StartsWith("/api/v1/products/security/certificate/", StringComparison.Ordinal))
+ {
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(TestCertificates.Bundle("admin", AdminCertificate)) };
+ }
+
+ if (request.Method == HttpMethod.Get && path == "/api/v1/metadata/release-channels")
+ {
+ return Json(new { defaultReleaseChannel = "Stable72", releaseChannels = new[] { new { name = "Stable72", ravenVersion = "7.2.7" }, new { name = "Stable62", ravenVersion = "6.2.20" } } });
+ }
+
+ return new HttpResponseMessage(HttpStatusCode.NotFound);
+ }
+
+ private static async Task ReadAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
+ JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!.AsObject();
+
+ private static HttpResponseMessage Json(object value, HttpStatusCode status = HttpStatusCode.OK) =>
+ new(status) { Content = JsonContent.Create(value, options: new JsonSerializerOptions(JsonSerializerDefaults.Web)) };
+}
+
+internal sealed class FakeProduct(string id, string name)
+{
+ public string Id { get; } = id;
+
+ public string Name { get; } = name;
+
+ public string? Subdomain { get; set; }
+
+ public string Status { get; set; } = "Active";
+
+ public bool Hidden { get; set; }
+
+ public string Tier { get; set; } = "Development";
+
+ public string Provider { get; set; } = "Aws";
+
+ public string Region { get; set; } = "eu-central-1";
+
+ public string InstanceType { get; set; } = "Dev10";
+
+ public string? ReleaseChannel { get; set; } = "Stable72";
+
+ public int DiskSize { get; set; } = 20;
+
+ /// The sizes the data disk can grow to, as RavenDB Cloud lists them for an existing disk.
+ public int[]? ResizableTo { get; set; }
+
+ public int? Iops { get; set; }
+
+ public double? Throughput { get; set; }
+
+ public string StorageType { get; set; } = "SsdStandard";
+
+ ///
+ /// A separate data disk, as a product set up in the portal can have: the disk properties above are then the data
+ /// disk's, and the API reports a 30 GB system disk besides.
+ ///
+ public bool HasDataDisk { get; set; }
+
+ public string[] AllowedIps { get; set; } = ["203.0.113.0/24"];
+
+ public string[] Dns { get; set; } = [];
+
+ public string[] NodeTags { get; set; } = ["A"];
+
+ public int Polls { get; set; }
+}
+
+/// An in-memory RavenDB server with the certificate and database operations a deployment performs.
+internal sealed class FakeRavenDBServer : IRavenDBServerAdministrationFactory
+{
+ public HashSet Databases { get; } = new(StringComparer.OrdinalIgnoreCase);
+
+ public Dictionary Certificates { get; } = new(StringComparer.OrdinalIgnoreCase);
+
+ public List DeletedThumbprints { get; } = [];
+
+ /// Fails the next deletions with this many exceptions, as an unreachable server does.
+ public int FailingDeletes { get; set; }
+
+ /// Fails this many pings, as a server that does not answer yet; never answers.
+ public int UnreachableFor { get; set; }
+
+ /// Node URLs and admin certificate thumbprint of every connection.
+ public List<(IReadOnlyList Urls, string? CertificateThumbprint)> Connections { get; } = [];
+
+ /// The admin certificate instance every connection was given.
+ public List ConnectionCertificates { get; } = [];
+
+ /// Registers a certificate as if an earlier deployment or another client had issued it.
+ public string Register(string name, params string[] databases) =>
+ Register(name, SecurityClearance.ValidUser, databases.ToDictionary(d => d, _ => DatabaseAccess.Admin));
+
+ public string Register(string name, SecurityClearance clearance, Dictionary permissions)
+ {
+ var thumbprint = RavenDBCloudCertificates.GetThumbprint(TestCertificates.CreatePfx(name));
+ Certificates[thumbprint] = new FakeCertificate(name, permissions, clearance);
+ return thumbprint;
+ }
+
+ public IRavenDBServerAdministration Create(IReadOnlyList urls, X509Certificate2? certificate)
+ {
+ Connections.Add((urls, certificate?.Thumbprint));
+
+ if (certificate is not null)
+ {
+ ConnectionCertificates.Add(certificate);
+ }
+
+ return new Session(this);
+ }
+
+ private sealed class Session(FakeRavenDBServer server) : IRavenDBServerAdministration
+ {
+ public Task PingAsync(CancellationToken cancellationToken)
+ {
+ if (server.UnreachableFor > 0)
+ {
+ server.UnreachableFor -= server.UnreachableFor == int.MaxValue ? 0 : 1;
+ throw new HttpRequestException("A connection attempt failed.", new System.Net.Sockets.SocketException(10060));
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public Task DatabaseExistsAsync(string database, CancellationToken cancellationToken) =>
+ Task.FromResult(server.Databases.Contains(database));
+
+ public Task CreateDatabaseAsync(string database, int replicationFactor, CancellationToken cancellationToken) =>
+ Task.FromResult(server.Databases.Add(database));
+
+ public Task> GetCertificatesAsync(string namePrefix, CancellationToken cancellationToken) =>
+ Task.FromResult>([.. server.Certificates
+ .Where(c => c.Value.Name.StartsWith(namePrefix, StringComparison.OrdinalIgnoreCase))
+ .Select(c => new RegisteredCertificate(
+ c.Value.Name,
+ c.Key,
+ c.Value.Clearance,
+ new Dictionary(c.Value.Permissions, StringComparer.OrdinalIgnoreCase)))]);
+
+ public Task CreateClientCertificateAsync(string name, IReadOnlyDictionary permissions, CancellationToken cancellationToken)
+ {
+ var pfx = TestCertificates.CreatePfx(name);
+ server.Certificates[RavenDBCloudCertificates.GetThumbprint(pfx)] = new FakeCertificate(name, new Dictionary(permissions));
+
+ return Task.FromResult(TestCertificates.Bundle(name, pfx));
+ }
+
+ public Task DeleteCertificateAsync(string thumbprint, CancellationToken cancellationToken)
+ {
+ if (server.FailingDeletes > 0)
+ {
+ server.FailingDeletes--;
+ throw new HttpRequestException("The server is unreachable.");
+ }
+
+ server.DeletedThumbprints.Add(thumbprint);
+ server.Certificates.Remove(thumbprint);
+
+ return Task.CompletedTask;
+ }
+
+ public void Dispose()
+ {
+ }
+ }
+}
+
+/// Collects every log message, to assert on what the person who deploys reads.
+internal sealed class CollectingLoggerProvider : ILoggerProvider
+{
+ public ConcurrentQueue Messages { get; } = new();
+
+ public ILogger CreateLogger(string categoryName) => new Logger(this);
+
+ public void Dispose()
+ {
+ }
+
+ private sealed class Logger(CollectingLoggerProvider provider) : ILogger
+ {
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) =>
+ provider.Messages.Enqueue(formatter(state, exception) + (exception is null ? string.Empty : " " + exception));
+ }
+}
+
+internal sealed record FakeCertificate(
+ string Name,
+ Dictionary Permissions,
+ SecurityClearance Clearance = SecurityClearance.ValidUser);
+
+/// The process environment, as a deployment reads it.
+internal sealed class FakeEnvironment : IRavenDBCloudEnvironment
+{
+ public Dictionary Variables { get; } = [];
+
+ public string? Get(string variable) => Variables.GetValueOrDefault(variable);
+}
+
+internal static class TestCertificates
+{
+ public static byte[] CreatePfx(string name)
+ {
+ using var key = RSA.Create(2048);
+ var request = new CertificateRequest($"CN={name}", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
+ using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(30));
+
+ return certificate.Export(X509ContentType.Pfx);
+ }
+
+ /// The zip RavenDB and RavenDB Cloud return: the pfx next to the PEM files.
+ public static byte[] Bundle(string name, byte[] pfx)
+ {
+ using var zip = new MemoryStream();
+
+ using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
+ {
+ using (var pem = archive.CreateEntry($"{name}.crt").Open())
+ {
+ pem.Write("-----BEGIN CERTIFICATE-----"u8);
+ }
+
+ using var entry = archive.CreateEntry($"{name}.pfx").Open();
+ entry.Write(pfx);
+ }
+
+ return zip.ToArray();
+ }
+}
+
+internal sealed class InMemoryDeploymentStateManager : IDeploymentStateManager
+{
+ private readonly Dictionary _sections = new(StringComparer.Ordinal);
+
+ public string? StateFilePath => null;
+
+ public JsonObject? this[string sectionName] => _sections.TryGetValue(sectionName, out var section) ? section.Data : null;
+
+ public Task AcquireSectionAsync(string sectionName, CancellationToken cancellationToken = default) =>
+ Task.FromResult(_sections.TryGetValue(sectionName, out var section)
+ ? new DeploymentStateSection(sectionName, (JsonObject)section.Data.DeepClone(), section.Version)
+ : new DeploymentStateSection(sectionName, [], 0));
+
+ public Task SaveSectionAsync(DeploymentStateSection section, CancellationToken cancellationToken = default)
+ {
+ var current = _sections.TryGetValue(section.SectionName, out var existing) ? existing.Version : 0;
+
+ if (current != section.Version)
+ {
+ throw new InvalidOperationException($"Concurrency conflict on '{section.SectionName}'.");
+ }
+
+ _sections[section.SectionName] = ((JsonObject)section.Data.DeepClone(), current + 1);
+ section.Version = current + 1;
+
+ return Task.CompletedTask;
+ }
+
+ public Task DeleteSectionAsync(DeploymentStateSection section, CancellationToken cancellationToken = default)
+ {
+ _sections.Remove(section.SectionName);
+ return Task.CompletedTask;
+ }
+
+ public Task ClearAllStateAsync(CancellationToken cancellationToken = default)
+ {
+ _sections.Clear();
+ return Task.CompletedTask;
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPlanTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPlanTests.cs
new file mode 100644
index 000000000..aa4e72c9b
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPlanTests.cs
@@ -0,0 +1,463 @@
+using Aspire.Hosting;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Utils;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+public class RavenDBCloudPlanTests
+{
+ private static readonly RavenDBCloudSpec s_dev10 =
+ RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ private static readonly RavenDBCloudSpec s_dev10DataDisk =
+ RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.SingleDataDisk, "Stable72");
+
+ internal static RavenDBCloudDeployment Managed(RavenDBCloudSpec? spec = null, Action? configure = null, string name = "shop-prod")
+ {
+ var options = new RavenDBCloudOptions().WithAllowedIps("203.0.113.0/24");
+ configure?.Invoke(options);
+ return new RavenDBCloudDeployment(Server(), ApiKey(), RavenDBCloudMode.Managed, name, spec ?? s_dev10, null, options) { PollInterval = TimeSpan.Zero, ChangeGracePeriod = TimeSpan.Zero };
+ }
+
+ internal static RavenDBCloudDeployment Attached(string clientName = "billing", Action? configure = null)
+ {
+ var options = new RavenDBCloudOptions();
+ configure?.Invoke(options);
+ return new RavenDBCloudDeployment(Server(), ApiKey(), RavenDBCloudMode.Attached, "shared", null, clientName, options) { PollInterval = TimeSpan.Zero, ChangeGracePeriod = TimeSpan.Zero };
+ }
+
+ /// A server that declares the database orders, as the AppHost in most tests does.
+ internal static RavenDBServerResource Server()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var server = builder.AddRavenDB("ravendb");
+ server.AddDatabase("orders");
+ return server.Resource;
+ }
+
+ internal static ParameterResource ApiKey() => new("api-key", _ => "key", secret: true);
+
+ private static async Task PlanAsync(FakeRavenDBCloudApi api, RavenDBCloudDeployment deployment, bool approved = false, IReadOnlyList? consumers = null)
+ {
+ using var client = api.Create("https://api.test", "key");
+ return await RavenDBCloudPlanner.PlanAsync(client, deployment, consumers ?? [], approved, TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ public async Task MissingProductIsCreatedFromTheSpec()
+ {
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), Managed(configure: o => o.Subdomain = "shop"));
+
+ Assert.False(plan.Blocks);
+ Assert.Equal(
+ "create 'shop-prod': Development Dev10, Aws eu-central-1, 20 GB SsdStandard on RootOnly, channel Stable72, allowed IPs 203.0.113.0/24",
+ Assert.Single(plan.Lines).Text);
+
+ var create = plan.Create!;
+ Assert.Equal(("Aws", "eu-central-1", "Dev10", "Development", 20, "SsdStandard", "Stable72", "shop"),
+ (create.CloudProvider, create.Region, create.InstanceTypeName, create.Tier, create.DiskSize, create.StorageTypeName, create.ReleaseChannel, create.SubdomainName));
+ Assert.Equal(["203.0.113.0/24"], create.AllowedIps);
+ Assert.Equal("RootOnly", create.DiskLayout);
+ }
+
+ [Fact]
+ public async Task CreatingWithoutAllowedIpsStops()
+ {
+ var deployment = new RavenDBCloudDeployment(Server(), ApiKey(), RavenDBCloudMode.Managed, "shop-prod", s_dev10, null, new RavenDBCloudOptions());
+
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), deployment);
+
+ Assert.True(plan.Blocks);
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.Contains("at least one allowed IP range", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("eu-west-9", "Dev10", 20, "region 'eu-west-9' is not offered on Aws. Offered: us-east-1, eu-central-1.")]
+ [InlineData("eu-central-1", "Dev99", 20, "instance type 'Dev99' is not offered for the Development tier in Aws eu-central-1. Offered: Dev10 (2 vCPU, 2 GB RAM, 1 node, disks 10/20/32 GB), Dev20 (2 vCPU, 4 GB RAM, 1 node, disks 20/32/64 GB).")]
+ [InlineData("eu-central-1", "P20", 64, "instance type 'P20' is not offered for the Development tier in Aws eu-central-1. Offered: Dev10 (2 vCPU, 2 GB RAM, 1 node, disks 10/20/32 GB), Dev20 (2 vCPU, 4 GB RAM, 1 node, disks 20/32/64 GB).")]
+ [InlineData("eu-central-1", "Dev10", 25, "disk size 25 GB is not offered for instance type 'Dev10'. Offered: 10, 20, 32 GB.")]
+ public async Task SpecOutsideTheOfferStopsAndListsWhatIsOffered(string region, string instanceType, int disk, string expected)
+ {
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, region, instanceType, disk, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), Managed(spec));
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text == expected);
+ }
+
+ [Fact]
+ public async Task UnknownReleaseChannelAndIopsOutOfRangeStop()
+ {
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 20, RavenDBCloudStorageType.SsdPremium, RavenDBCloudDiskLayout.RootOnly, "Nightly", iops: 100);
+
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), Managed(spec));
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text == "100 IOPS is outside the range offered for SsdPremium: 3000 to 16000.");
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text == "release channel 'Nightly' does not exist. Available: Stable72 (RavenDB 7.2.7), Stable62 (RavenDB 6.2.20).");
+ }
+
+ [Fact]
+ public async Task UnknownReleaseChannelShowsNextToAnUnknownInstanceType()
+ {
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev99", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Nightly");
+
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), Managed(spec));
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("instance type 'Dev99' is not offered", StringComparison.Ordinal));
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("release channel 'Nightly' does not exist", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task ProductThatMatchesHasNoChanges()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+
+ var plan = await PlanAsync(api, Managed());
+
+ Assert.False(plan.Blocks);
+ Assert.False(plan.HasChanges);
+ Assert.StartsWith("no changes: 'shop-prod'", Assert.Single(plan.Lines).Text, StringComparison.Ordinal);
+ }
+
+ /// The spec describes the disk the data is on, not the system disk of a product with a data disk.
+ [Fact]
+ public async Task ProductWithADataDiskIsComparedByItsDataDisk()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod").HasDataDisk = true;
+
+ var plan = await PlanAsync(api, Managed(s_dev10DataDisk));
+
+ Assert.False(plan.Blocks);
+ Assert.False(plan.HasChanges);
+ Assert.StartsWith("no changes: 'shop-prod'", Assert.Single(plan.Lines).Text, StringComparison.Ordinal);
+ }
+
+ ///
+ /// RavenDB Cloud grows a disk that fills up, past the sizes a new product chooses from: Dev10 offers 10, 20 and
+ /// 32 GB, and its disk grew to 64 GB. Keeping that size is no change.
+ ///
+ [Fact]
+ public async Task DiskRavenDBCloudGrewIsNoChange()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod").DiskSize = 64;
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 64, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(spec));
+
+ Assert.False(plan.Blocks);
+ Assert.False(plan.HasChanges);
+ Assert.StartsWith("no changes: 'shop-prod'", Assert.Single(plan.Lines).Text, StringComparison.Ordinal);
+ }
+
+ /// An existing disk grows only to the sizes RavenDB Cloud lists for it, not to the ones a new product chooses from.
+ [Fact]
+ public async Task DiskGrowsOnlyToTheSizesRavenDBCloudListsForIt()
+ {
+ var api = new FakeRavenDBCloudApi();
+ var product = api.AddProduct("shop-prod");
+ product.ResizableTo = [20, 32];
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 25, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(spec), approved: true);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text == "impossible: disk 20 GB -> 25 GB. RavenDB Cloud grows this disk to 20, 32 GB only: set one of them in the AppHost.");
+ Assert.DoesNotContain(plan.Lines, l => l.Text.Contains("is not offered", StringComparison.Ordinal));
+ }
+
+ /// The Cloud API cannot move a product's data to another disk layout.
+ [Theory]
+ [InlineData(false, "disk layout RootOnly -> SingleDataDisk")]
+ [InlineData(true, "disk layout SingleDataDisk -> RootOnly")]
+ public async Task OtherDiskLayoutIsImpossible(bool productHasDataDisk, string expected)
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod").HasDataDisk = productHasDataDisk;
+
+ var plan = await PlanAsync(api, Managed(productHasDataDisk ? s_dev10 : s_dev10DataDisk), approved: true);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith($"impossible: {expected}.", StringComparison.Ordinal));
+ }
+
+ /// A product RavenDB Cloud could not set up stops the plan before any change is planned for it.
+ [Theory]
+ [InlineData("Error", "error: 'shop-prod' is in error in RavenDB Cloud.")]
+ [InlineData("AwaitingPayment", "awaiting payment: 'shop-prod' waits for a payment.")]
+ public async Task ProductRavenDBCloudCannotServeStops(string status, string expected)
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod", status: status);
+ var bigger = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(bigger), approved: true);
+
+ Assert.StartsWith(expected, Assert.Single(plan.Lines, l => l.Blocks).Text, StringComparison.Ordinal);
+ Assert.False(plan.HasChanges);
+ }
+
+ [Fact]
+ public async Task ChangesStopWithoutApproval()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(spec));
+
+ Assert.True(plan.Blocks);
+ Assert.False(plan.HasChanges);
+ Assert.Equal(
+ "change 'shop-prod': instance Dev10 -> Dev20, disk 20 GB -> 32 GB. Deploy with RavenDB__Cloud__ApproveChanges=true to apply it.",
+ Assert.Single(plan.Lines).Text);
+ }
+
+ [Fact]
+ public async Task ApprovedChangesArePlanned()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdPremium, RavenDBCloudDiskLayout.RootOnly, "Stable72", iops: 3000);
+
+ var plan = await PlanAsync(api, Managed(spec), approved: true);
+
+ Assert.False(plan.Blocks);
+ Assert.Equal(
+ "change 'shop-prod': instance Dev10 -> Dev20, disk 20 GB -> 32 GB, storage SsdStandard -> SsdPremium, IOPS default -> 3000 " +
+ "(approved by RavenDB__Cloud__ApproveChanges)",
+ Assert.Single(plan.Lines).Text);
+ Assert.Equal("Dev20", plan.InstanceTypeChange);
+ Assert.Equal((32, "SsdPremium", 3000), (plan.StorageChange!.Size, plan.StorageChange.StorageType, plan.StorageChange.Iops));
+ }
+
+ [Fact]
+ public async Task ImpossibleChangesStopEvenWhenApproved()
+ {
+ var api = new FakeRavenDBCloudApi();
+ var product = api.AddProduct("shop-prod");
+ product.DiskSize = 32;
+ product.ReleaseChannel = "Stable62";
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Azure, "westeurope", "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(spec), approved: true);
+
+ Assert.True(plan.Blocks);
+ var texts = plan.Lines.Where(l => l.Blocks).Select(l => l.Text).ToList();
+ Assert.Contains(texts, t => t.StartsWith("impossible: provider Aws -> Azure.", StringComparison.Ordinal));
+ Assert.Contains(texts, t => t.StartsWith("impossible: region eu-central-1 -> westeurope.", StringComparison.Ordinal));
+ Assert.Contains(texts, t => t.StartsWith("impossible: release channel Stable62 -> Stable72 (change it in the portal).", StringComparison.Ordinal));
+ Assert.Contains(texts, t => t == "impossible: disk 32 GB -> 20 GB. A disk cannot shrink, and RavenDB Cloud grows one that fills up: set the disk size in the AppHost to 32 GB.");
+ }
+
+ [Fact]
+ public async Task AnotherTierIsImpossible()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ var spec = RavenDBCloudSpec.Production(RavenDBCloudProvider.Aws, "eu-central-1", "P20", 64, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ var plan = await PlanAsync(api, Managed(spec), approved: true);
+
+ Assert.True(plan.Blocks);
+ Assert.Null(plan.InstanceTypeChange);
+ Assert.Contains(
+ plan.Lines,
+ l => l.Blocks && l.Text.StartsWith("impossible: tier Development -> Production (RavenDB Cloud cannot change the tier of a product).", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task TwoLiveProductsWithTheNameStop()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ api.AddProduct("SHOP-PROD");
+
+ var exception = await Assert.ThrowsAsync(() => PlanAsync(api, Managed()));
+
+ Assert.Contains("2 RavenDB Cloud products named 'shop-prod'", exception.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task TerminatedProductStillHoldsTheNameUntilItIsHidden()
+ {
+ var api = new FakeRavenDBCloudApi();
+ var terminated = api.AddProduct("shop-prod", status: "Terminated");
+
+ var plan = await PlanAsync(api, Managed());
+
+ Assert.Null(plan.Create);
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("name: 'shop-prod' is held by a terminated product", StringComparison.Ordinal));
+
+ terminated.Hidden = true;
+ Assert.NotNull((await PlanAsync(api, Managed())).Create);
+ }
+
+ [Fact]
+ public async Task ProductStillBeingTerminatedHoldsTheNameForAWhile()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod", status: "Terminating");
+
+ var plan = await PlanAsync(api, Managed());
+
+ Assert.Null(plan.Create);
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text == "name: 'shop-prod' is held by a product that is still being terminated. Deploy again once RavenDB Cloud has terminated it.");
+ }
+
+ [Fact]
+ public async Task AttachedProductThatIsMissingStops()
+ {
+ var plan = await PlanAsync(new FakeRavenDBCloudApi(), Attached());
+
+ Assert.True(plan.Blocks);
+ Assert.StartsWith("missing: there is no RavenDB Cloud product 'shared'.", Assert.Single(plan.Lines).Text, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task AttachedProductIsNeverChanged()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shared");
+
+ var plan = await PlanAsync(api, Attached(), approved: true);
+
+ Assert.False(plan.Blocks);
+ Assert.False(plan.HasChanges);
+ Assert.Null(plan.Create);
+ Assert.StartsWith("attach: 'shared'", Assert.Single(plan.Lines).Text, StringComparison.Ordinal);
+ }
+
+ [Theory]
+ [InlineData("203.0.113.0/24", "203.0.113.7/32", false)]
+ [InlineData("203.0.113.0/24", "203.0.113.0/25", false)]
+ [InlineData("203.0.113.0/24", "198.51.100.0/24", true)]
+ [InlineData("203.0.113.0/24", "203.0.112.0/23", true)]
+ [InlineData("0.0.0.0/0", "198.51.100.0/24", false)]
+ [InlineData("2001:db8::/32", "2001:db8:1::/48", false)]
+ [InlineData("2001:db8::/32", "10.0.0.1/32", true)]
+ public async Task AllowedIpsMustBeCoveredByTheProduct(string allowedOnProduct, string range, bool blocks)
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shared").AllowedIps = [allowedOnProduct];
+
+ var plan = await PlanAsync(api, Attached(configure: o => o.WithAllowedIps(range)));
+
+ Assert.Equal(blocks, plan.Blocks);
+
+ if (blocks)
+ {
+ Assert.Contains(plan.Lines, l => l.Text.StartsWith($"allowed IPs: {range} not allowed on 'shared'.", StringComparison.Ordinal));
+ }
+ }
+
+ [Fact]
+ public async Task ApplicationInAnUnsupportedEnvironmentStops()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ var application = new ContainerResource("api");
+ application.Annotations.Add(new DeploymentTargetAnnotation(application) { ComputeEnvironment = new UnsupportedEnvironment("k8s") });
+
+ var plan = await PlanAsync(api, Managed(), consumers: [new RavenDBConsumer(application, [], 1)]);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text ==
+ "no target: 'api' is deployed to 'k8s', where the RavenDB Cloud integration cannot deliver the URL and certificate of " +
+ "'ravendb'. Supported: Docker Compose, as an application's only compute environment.");
+ }
+
+ ///
+ /// Azure Container Apps would carry the certificate as a plain template parameter. Checked with the real environment,
+ /// whose type name contains no "DockerCompose".
+ ///
+ [Fact]
+ public async Task ApplicationInAzureContainerAppsStops()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var aca = builder.AddAzureContainerAppEnvironment("aca");
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+
+ var plan = await PlanAsync(api, Managed(), consumers: [Consumer(aca.Resource)]);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("no target: 'api' is deployed to 'aca'", StringComparison.Ordinal));
+ }
+
+ /// The environment is recognized by its full type name, not by a class that only shares the short name.
+ [Fact]
+ public async Task EnvironmentThatOnlySharesTheNameStops()
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+
+ var plan = await PlanAsync(api, Managed(), consumers: [Consumer(new DockerComposeEnvironmentResource("compose"))]);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("no target: 'api' is deployed to 'compose'", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task ApplicationWithoutOrWithTwoEnvironmentsStops()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var compose = builder.AddDockerComposeEnvironment("compose");
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shop-prod");
+ var nowhere = new ContainerResource("nowhere");
+ var twice = Consumer(compose.Resource, "twice").Resource;
+ twice.Annotations.Add(new DeploymentTargetAnnotation(twice) { ComputeEnvironment = new UnsupportedEnvironment("k8s") });
+
+ var plan = await PlanAsync(
+ api,
+ Managed(),
+ consumers: [new RavenDBConsumer(nowhere, [], 1), new RavenDBConsumer(twice, [], 1), Consumer(compose.Resource, "fine")]);
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("no target: 'nowhere' is deployed to no compute environment", StringComparison.Ordinal));
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith("no target: 'twice' is deployed to 2 compute environments", StringComparison.Ordinal));
+ Assert.DoesNotContain(plan.Lines, l => l.Text.StartsWith("no target: 'fine'", StringComparison.Ordinal));
+ }
+
+ private static RavenDBConsumer Consumer(IComputeEnvironmentResource environment, string name = "api")
+ {
+ var application = new ContainerResource(name);
+ application.Annotations.Add(new DeploymentTargetAnnotation(application) { ComputeEnvironment = environment });
+ return new RavenDBConsumer(application, [], 1);
+ }
+
+ [Theory]
+ [InlineData("0.0.0.0/0", true)]
+ [InlineData("10.0.0.0/8", true)]
+ [InlineData("10.1.0.0/16", false)]
+ [InlineData("2001:db8::/32", true)]
+ [InlineData("2001:db8:1::/48", false)]
+ public async Task WideAllowedIpRangeIsAWarning(string range, bool warns)
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shared").AllowedIps = ["0.0.0.0/0", "::/0"];
+
+ var plan = await PlanAsync(api, Attached(configure: o => o.WithAllowedIps(range)));
+
+ Assert.False(plan.Blocks);
+ Assert.Equal(warns, plan.Lines.Any(l => l.Text.StartsWith($"wide allowed IPs: {range} lets a large part of the internet reach 'shared'", StringComparison.Ordinal)));
+ }
+
+ /// The CIDR notation RavenDB Cloud takes; a bare address it refuses too.
+ [Theory]
+ [InlineData("203.0.113.7")]
+ [InlineData("not-an-ip")]
+ [InlineData("10.0.0.0/33")]
+ [InlineData("10.0.0.0/x")]
+ public async Task AllowedIpRangeThatIsNotCidrStops(string range)
+ {
+ var api = new FakeRavenDBCloudApi();
+ api.AddProduct("shared");
+
+ var plan = await PlanAsync(api, Attached(configure: o => o.WithAllowedIps(range)));
+
+ Assert.Contains(plan.Lines, l => l.Blocks && l.Text.StartsWith($"allowed IP range '{range}' is not a valid CIDR range", StringComparison.Ordinal));
+ Assert.DoesNotContain(plan.Lines, l => l.Text.StartsWith("allowed IPs:", StringComparison.Ordinal));
+ }
+
+ private sealed class UnsupportedEnvironment(string name) : Resource(name), IComputeEnvironmentResource;
+
+ private sealed class DockerComposeEnvironmentResource(string name) : Resource(name), IComputeEnvironmentResource;
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudProductsTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudProductsTests.cs
new file mode 100644
index 000000000..ebffd06e8
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudProductsTests.cs
@@ -0,0 +1,325 @@
+using Aspire.Hosting.ApplicationModel;
+using Microsoft.Extensions.Logging.Abstractions;
+using Raven.Client.ServerWide.Operations.Certificates;
+using static CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests.RavenDBCloudPlanTests;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+public class RavenDBCloudProductsTests
+{
+ private readonly FakeRavenDBCloudApi _api = new();
+
+ private async Task ProvisionAsync(RavenDBCloudDeployment deployment, bool approved = false)
+ {
+ using var client = _api.Create("https://api.test", "key");
+ var plan = await RavenDBCloudPlanner.PlanAsync(client, deployment, [], approved, TestContext.Current.CancellationToken);
+ await new RavenDBCloudProducts(client, NullLogger.Instance).ProvisionAsync(deployment, plan, TestContext.Current.CancellationToken);
+ return plan;
+ }
+
+ private async Task DestroyAsync(RavenDBCloudDeployment deployment)
+ {
+ using var client = _api.Create("https://api.test", "key");
+ return await new RavenDBCloudProducts(client, NullLogger.Instance).DestroyAsync(deployment, TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ public async Task CreatesTheProductWaitsUntilActiveAndResolvesItsUrl()
+ {
+ var deployment = Managed();
+
+ await ProvisionAsync(deployment);
+
+ var product = Assert.Single(_api.Products.Values);
+ Assert.Equal(("shop-prod", "Active"), (product.Name, product.Status));
+ Assert.Equal("https://a.shop-prod.development.run", deployment.Endpoint.Value);
+ Assert.Equal(product.Id, deployment.ProductId);
+ }
+
+ /// Every node, so that an application reaches the cluster while one node is down.
+ [Fact]
+ public async Task TheApplicationsGetEveryNodeOfTheCluster()
+ {
+ _api.AddProduct("shop-prod").Dns = ["a.shop-prod.development.run", "b.shop-prod.development.run", "c.shop-prod.development.run"];
+ var deployment = Managed();
+
+ await ProvisionAsync(deployment);
+
+ Assert.Equal("https://a.shop-prod.development.run,https://b.shop-prod.development.run,https://c.shop-prod.development.run", deployment.Endpoint.Value);
+ Assert.Equal(3, deployment.NodeUrls.Count);
+ }
+
+ [Fact]
+ public async Task BlockedPlanChangesNothing()
+ {
+ _api.AddProduct("shop-prod");
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ await Assert.ThrowsAsync(() => ProvisionAsync(Managed(spec)));
+
+ Assert.Empty(_api.ChangeRequests);
+ Assert.DoesNotContain(_api.Requests, r => r.StartsWith("POST", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task AppliesApprovedChangesAndWaitsForThem()
+ {
+ _api.AddProduct("shop-prod");
+ var spec = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ await ProvisionAsync(Managed(spec), approved: true);
+
+ Assert.Equal(2, _api.ChangeRequests.Count);
+ var product = Assert.Single(_api.Products.Values);
+ Assert.Equal(("Dev20", 32, "Active"), (product.InstanceType, product.DiskSize, product.Status));
+ }
+
+ [Fact]
+ public async Task ExistingProductIsFoundByName()
+ {
+ var existing = _api.AddProduct("shop-prod");
+ var deployment = Managed();
+
+ await ProvisionAsync(deployment);
+
+ Assert.Equal(existing.Id, deployment.ProductId);
+ Assert.Empty(_api.CreateRequests);
+ }
+
+ [Fact]
+ public async Task DestroyTerminatesTheProductWhenAsked()
+ {
+ var deployment = Managed(configure: o => o.TerminateOnDestroy = true);
+ await ProvisionAsync(deployment);
+
+ Assert.Null(await DestroyAsync(deployment));
+
+ Assert.Equal(_api.Products.Keys.Single(), Assert.Single(_api.TerminatedProductIds));
+
+ // Hidden as well, so the next deployment can create a product with the name again.
+ Assert.True(_api.Products.Values.Single().Hidden);
+ await ProvisionAsync(Managed(configure: o => o.TerminateOnDestroy = true));
+ Assert.Equal(2, _api.Products.Count);
+ }
+
+ /// The name is the identity: from a CI runner, or for a product made in the portal, destroy finds it too.
+ [Fact]
+ public async Task DestroyTerminatesAProductItFindsByName()
+ {
+ var product = _api.AddProduct("shop-prod");
+
+ Assert.Null(await DestroyAsync(Managed(configure: o => o.TerminateOnDestroy = true)));
+
+ Assert.Equal(product.Id, Assert.Single(_api.TerminatedProductIds));
+ }
+
+ /// One name in two environments: destroy must not terminate the product the other one describes.
+ [Theory]
+ [InlineData("tier")]
+ [InlineData("region")]
+ [InlineData("instance type")]
+ public async Task DestroyRefusesAProductTheAppHostDoesNotDescribe(string difference)
+ {
+ var product = _api.AddProduct("shop-prod");
+ _ = difference switch
+ {
+ "tier" => product.Tier = "Production",
+ "region" => product.Region = "us-east-1",
+ _ => product.InstanceType = "Dev20",
+ };
+
+ var exception = await Assert.ThrowsAsync(() => DestroyAsync(Managed(configure: o => o.TerminateOnDestroy = true)));
+
+ Assert.Contains("does not match the AppHost", exception.Message, StringComparison.Ordinal);
+ Assert.Contains(difference, exception.Message, StringComparison.Ordinal);
+ Assert.Empty(_api.TerminatedProductIds);
+ }
+
+ /// A disk that RavenDB Cloud grew, or a subdomain chosen in the portal, still describe the product the AppHost means.
+ [Fact]
+ public async Task DestroyIgnoresTheDiskAndTheSubdomain()
+ {
+ var product = _api.AddProduct("shop-prod");
+ product.DiskSize = 64;
+ product.Subdomain = "shop";
+
+ Assert.Null(await DestroyAsync(Managed(configure: o => o.TerminateOnDestroy = true)));
+ Assert.Single(_api.TerminatedProductIds);
+ }
+
+ [Fact]
+ public async Task DestroyLeavesItRunningWithoutTerminateOnDestroy()
+ {
+ var deployment = Managed();
+ await ProvisionAsync(deployment);
+
+ Assert.NotNull(await DestroyAsync(deployment));
+ Assert.Empty(_api.TerminatedProductIds);
+ }
+
+ [Fact]
+ public async Task DestroyTerminatesAProductThatIsStillBeingCreated()
+ {
+ var deployment = Managed(configure: o => o.TerminateOnDestroy = true);
+ _api.BusyPolls = int.MaxValue;
+ using (var client = _api.Create("https://api.test", "key"))
+ {
+ var plan = await RavenDBCloudPlanner.PlanAsync(client, deployment, [], false, TestContext.Current.CancellationToken);
+ deployment.ProvisioningTimeout = TimeSpan.Zero;
+ await Assert.ThrowsAsync(() =>
+ new RavenDBCloudProducts(client, NullLogger.Instance).ProvisionAsync(deployment, plan, TestContext.Current.CancellationToken));
+ }
+
+ Assert.Null(await DestroyAsync(deployment));
+ Assert.Single(_api.TerminatedProductIds);
+ }
+
+ [Fact]
+ public async Task AttachedProductIsNeverTerminated()
+ {
+ _api.AddProduct("shared");
+
+ Assert.NotNull(await DestroyAsync(Attached()));
+ Assert.Empty(_api.TerminatedProductIds);
+ }
+}
+
+public class RavenDBCloudCertificatesTests
+{
+ ///
+ /// The deployment reuses one admin certificate for every connection, and the RavenDB client keeps it in its HTTP
+ /// client cache: closing a connection must leave it usable (a disposed one fails with an invalid handle).
+ ///
+ [Fact]
+ public void ClosingAConnectionLeavesTheAdminCertificateUsable()
+ {
+ using var certificate = RavenDBCloudCertificates.Load(TestCertificates.CreatePfx("admin"));
+
+ new RavenDBServerAdministration(["https://127.0.0.1:1"], certificate).Dispose();
+
+ Assert.NotEmpty(certificate.Thumbprint);
+ }
+
+ private readonly FakeRavenDBServer _server = new();
+ private readonly RavenDBCloudCertificates _certificates = new(NullLogger.Instance) { RevokeRetryDelay = TimeSpan.Zero };
+
+ private static (RavenDBCloudDeployment Deployment, List Consumers) WithApplications(RavenDBCloudDeployment deployment, params string[] applications)
+ {
+ var consumers = new List();
+
+ foreach (var name in applications)
+ {
+ var application = new ContainerResource(name);
+ deployment.Certificates.Add(new RavenDBCloudCertificate(deployment.Server, application));
+ consumers.Add(new RavenDBConsumer(application, ["orders"], 1));
+ }
+
+ return (deployment, consumers);
+ }
+
+ private IRavenDBServerAdministration Session() => _server.Create(["https://a.test"], null);
+
+ [Fact]
+ public async Task IssuesEachApplicationANewCertificateWithAdminOnItsDatabases()
+ {
+ var (deployment, consumers) = WithApplications(Managed(), "api", "worker");
+
+ await _certificates.IssueAsync(Session(), deployment, consumers, TestContext.Current.CancellationToken);
+
+ Assert.All(deployment.Certificates, c =>
+ {
+ var pfx = Convert.FromBase64String(c.Value!);
+ Assert.Equal(c.Thumbprint, RavenDBCloudCertificates.GetThumbprint(pfx));
+
+ var registered = _server.Certificates[c.Thumbprint!];
+ Assert.Equal($"aspire.{c.Consumer.Name}", registered.Name);
+ Assert.Equal(DatabaseAccess.Admin, Assert.Single(registered.Permissions, p => p.Key == "orders").Value);
+ });
+ }
+
+ [Fact]
+ public async Task RevokesReplacedCertificatesButNotOtherClients()
+ {
+ var previous = _server.Register("aspire.api", "orders");
+ var removedApplication = _server.Register("aspire.reports", "orders");
+ var otherClient = _server.Register("aspire.billing.api", "orders");
+ var unrelated = _server.Register("john", "orders");
+ var (deployment, consumers) = WithApplications(Managed(), "api");
+
+ await _certificates.IssueAsync(Session(), deployment, consumers, TestContext.Current.CancellationToken);
+ await _certificates.RevokeReplacedAsync(Session(), deployment, TestContext.Current.CancellationToken);
+
+ Assert.Equal(new[] { previous, removedApplication }.Order(), _server.DeletedThumbprints.Order());
+ Assert.Contains(otherClient, _server.Certificates.Keys);
+ Assert.Contains(unrelated, _server.Certificates.Keys);
+ Assert.Contains(deployment.Certificates.Single().Thumbprint, _server.Certificates.Keys);
+ }
+
+ [Fact]
+ public async Task AttachedClientRevokesOnlyItsOwnCertificates()
+ {
+ var own = _server.Register("aspire.billing.old-api", "orders");
+ var managedOwner = _server.Register("aspire.api", "orders");
+ var otherClient = _server.Register("aspire.shop.api", "orders");
+ var (deployment, consumers) = WithApplications(Attached("billing"), "api");
+
+ await _certificates.IssueAsync(Session(), deployment, consumers, TestContext.Current.CancellationToken);
+ await _certificates.RevokeReplacedAsync(Session(), deployment, TestContext.Current.CancellationToken);
+
+ Assert.Equal("aspire.billing.api", _server.Certificates[deployment.Certificates.Single().Thumbprint!].Name);
+ Assert.Equal([own], _server.DeletedThumbprints);
+ Assert.Contains(managedOwner, _server.Certificates.Keys);
+ Assert.Contains(otherClient, _server.Certificates.Keys);
+ }
+
+ ///
+ /// Only what this AppHost issues is revoked: a certificate that shares the name but has more clearance, or access to a
+ /// database the AppHost does not declare, was made by someone else.
+ ///
+ [Fact]
+ public async Task CertificatesThatOnlyShareTheNameAreNotRevoked()
+ {
+ var issued = _server.Register("aspire.api", "orders");
+ var operatorOne = _server.Register("aspire.ops", SecurityClearance.Operator, new());
+ var otherDatabase = _server.Register("aspire.reports", "invoices");
+ var readOnly = _server.Register("aspire.worker", SecurityClearance.ValidUser, new() { ["orders"] = DatabaseAccess.Read });
+ var deployment = Managed();
+
+ await _certificates.RevokeAllAsync(Session(), deployment, TestContext.Current.CancellationToken);
+
+ Assert.Equal([issued], _server.DeletedThumbprints);
+ Assert.Equal(new[] { operatorOne, otherDatabase, readOnly }.Order(), _server.Certificates.Keys.Order());
+
+ var others = await RavenDBCloudCertificates.GetOtherClientsAsync(Session(), deployment, TestContext.Current.CancellationToken);
+ Assert.Equal(["aspire.ops", "aspire.reports", "aspire.worker"], others);
+ }
+
+ [Fact]
+ public async Task OtherClientsAreListed()
+ {
+ _server.Register("aspire.api", "orders");
+ _server.Register("aspire.billing.api", "orders");
+ _server.Register("john");
+
+ var others = await RavenDBCloudCertificates.GetOtherClientsAsync(Session(), Managed(), TestContext.Current.CancellationToken);
+
+ Assert.Equal(["aspire.billing.api"], others);
+ }
+
+ [Fact]
+ public async Task RevokingRetriesThenFailsTheDeployment()
+ {
+ _server.Register("aspire.api", "orders");
+ var deployment = Managed();
+
+ _server.FailingDeletes = 1;
+ await _certificates.RevokeAllAsync(Session(), deployment, TestContext.Current.CancellationToken);
+ Assert.Empty(_server.Certificates);
+
+ _server.Register("aspire.api", "orders");
+ _server.FailingDeletes = RavenDBCloudCertificates.RevokeAttempts;
+ var exception = await Assert.ThrowsAsync(() => _certificates.RevokeAllAsync(Session(), deployment, TestContext.Current.CancellationToken));
+
+ Assert.Contains("Could not revoke client certificate 'aspire.api'", exception.Message, StringComparison.Ordinal);
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPublishTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPublishTests.cs
new file mode 100644
index 000000000..141db6ad6
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBCloudPublishTests.cs
@@ -0,0 +1,406 @@
+using Aspire.Hosting;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Pipelines;
+using Aspire.Hosting.Utils;
+using System.Net.Sockets;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Raven.Client.Exceptions;
+using Raven.Client.Exceptions.Security;
+using Raven.Client.ServerWide.Operations.Certificates;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+public class RavenDBCloudPublishTests
+{
+ private static readonly RavenDBCloudSpec s_spec =
+ RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+
+ private sealed class AppHost : IDisposable
+ {
+ public AppHost(string step)
+ {
+ Output = Directory.CreateTempSubdirectory(".ravendb-cloud-test");
+ Builder = TestDistributedApplicationBuilder.Create(
+ ["AppHost:Operation=publish", $"Pipeline:OutputPath={Output.FullName}", $"Pipeline:Step={step}"]);
+
+ Builder.Configuration["Parameters:ravendb-cloud-api-key"] = "test-api-key";
+ Builder.Services.AddSingleton(Api);
+ Builder.Services.AddSingleton(Server);
+ Builder.Services.AddSingleton(State);
+ Builder.Services.AddSingleton(Environment);
+ Builder.Services.AddLogging(logging => logging.AddProvider(Logs));
+ Builder.AddDockerComposeEnvironment("compose");
+ ApiKey = Builder.AddParameter("ravendb-cloud-api-key", secret: true);
+ }
+
+ public DirectoryInfo Output { get; }
+
+ public IDistributedApplicationTestingBuilder Builder { get; }
+
+ public IResourceBuilder ApiKey { get; }
+
+ public FakeRavenDBCloudApi Api { get; } = new() { BusyPolls = 1 };
+
+ public FakeRavenDBServer Server { get; } = new();
+
+ public InMemoryDeploymentStateManager State { get; } = new();
+
+ /// The process environment the deployment sees.
+ public FakeEnvironment Environment { get; } = new();
+
+ public CollectingLoggerProvider Logs { get; } = new();
+
+ public TimeSpan ReachableTimeout { get; set; } = TimeSpan.FromMinutes(1);
+
+ public string Log => string.Join("\n", Logs.Messages);
+
+ public string Compose => File.ReadAllText(Path.Combine(Output.FullName, "docker-compose.yaml")).ReplaceLineEndings("\n");
+
+ public string EnvFile => string.Join("\n", Output.GetFiles(".env*").Select(f => File.ReadAllText(f.FullName)));
+
+ public async Task RunAsync()
+ {
+ foreach (var deployment in Builder.Resources.SelectMany(r => r.Annotations.OfType()))
+ {
+ deployment.PollInterval = TimeSpan.Zero;
+ deployment.ChangeGracePeriod = TimeSpan.Zero;
+ deployment.ReachableTimeout = ReachableTimeout;
+ }
+
+ using var app = Builder.Build();
+ await app.RunAsync(TestContext.Current.CancellationToken);
+ }
+
+ public void Dispose()
+ {
+ Builder.Dispose();
+ Output.Delete(recursive: true);
+ }
+ }
+
+ [Fact]
+ public async Task ComposePublishLeavesTheServerOutAndReferencesTheDeployTimeValues()
+ {
+ using var host = new AppHost("publish");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders", ensureCreated: true);
+ host.Builder.AddContainer("api", "busybox").WithReference(orders).WaitFor(orders);
+
+ await host.RunAsync();
+
+ var compose = host.Compose;
+ Assert.DoesNotContain("ravendb/ravendb", compose);
+ Assert.DoesNotContain("depends_on", compose);
+ Assert.Contains("ConnectionStrings__orders: \"URL=${RAVENDB_URL};Database=orders\"", compose);
+ Assert.Contains("Aspire__RavenDB__Client__orders__CertificateBase64: \"${RAVENDB_API_CERTIFICATE}\"", compose);
+ Assert.Contains("Aspire__RavenDB__Client__CertificateBase64: \"${RAVENDB_API_CERTIFICATE}\"", compose);
+
+ // aspire publish never calls the Cloud API: the values are placeholders.
+ Assert.Contains("RAVENDB_URL=", host.EnvFile);
+ Assert.Empty(host.Api.Requests);
+ }
+
+ [Fact]
+ public async Task DeployFillsTheUrlAndEachApplicationsCertificateIntoTheEnvironment()
+ {
+ using var host = new AppHost("prepare-compose");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders", ensureCreated: true);
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ var product = Assert.Single(host.Api.Products.Values);
+ Assert.Equal("shop-prod", product.Name);
+ Assert.Contains("orders", host.Server.Databases);
+
+ var certificate = Assert.Single(host.Server.Certificates);
+ Assert.Equal("aspire.api", certificate.Value.Name);
+ Assert.Equal(DatabaseAccess.Admin, certificate.Value.Permissions["orders"]);
+
+ var env = host.EnvFile;
+ Assert.Contains("RAVENDB_URL=https://a.shop-prod.development.run", env);
+ // The environment's own .env file carries the value; the published .env only names the variable.
+ var value = env.Split('\n')
+ .Where(l => l.StartsWith("RAVENDB_API_CERTIFICATE=", StringComparison.Ordinal))
+ .Select(l => l["RAVENDB_API_CERTIFICATE=".Length..].Trim())
+ .Single(v => v.Length > 0);
+ Assert.Equal(certificate.Key, RavenDBCloudCertificates.GetThumbprint(Convert.FromBase64String(value)));
+ }
+
+ [Fact]
+ public async Task BlockedPlanStopsTheDeploymentBeforeAnythingChanges()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Api.AddProduct("shop-prod");
+ var bigger = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", bigger, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Empty(host.Api.ChangeRequests);
+ Assert.Empty(host.Server.Certificates);
+ Assert.DoesNotContain("RAVENDB_URL=https", host.EnvFile, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task ApprovedChangesAreApplied()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Environment.Variables["RavenDB__Cloud__ApproveChanges"] = "true";
+ host.Api.AddProduct("shop-prod");
+ var bigger = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", bigger, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ var product = Assert.Single(host.Api.Products.Values);
+ Assert.Equal(("Dev20", 32), (product.InstanceType, product.DiskSize));
+ }
+
+ /// A committed file must not approve every future change: only the process environment does.
+ [Fact]
+ public async Task ApprovalInConfigurationIsIgnored()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Builder.Configuration["RavenDB:Cloud:ApproveChanges"] = "true";
+ host.Api.AddProduct("shop-prod");
+ var bigger = RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev20", 32, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", bigger, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Empty(host.Api.ChangeRequests);
+ }
+
+ [Fact]
+ public async Task DeployWaitsUntilTheServerAcceptsConnections()
+ {
+ using var host = new AppHost("prepare-compose");
+ // Right after a change the product reports Active a little before its node answers.
+ host.Server.UnreachableFor = 2;
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders", ensureCreated: true);
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Contains("orders", host.Server.Databases);
+ Assert.Single(host.Server.Certificates);
+ Assert.Contains("Waiting for RavenDB Cloud product 'shop-prod' at https://a.shop-prod.development.run to accept connections.", host.Log, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task ServerThatNeverAnswersStopsTheDeploymentAndPointsAtTheAllowedIps()
+ {
+ using var host = new AppHost("prepare-compose") { ReachableTimeout = TimeSpan.Zero };
+ host.Server.UnreachableFor = int.MaxValue;
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders", ensureCreated: true);
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Empty(host.Server.Databases);
+ Assert.Empty(host.Server.Certificates);
+ Assert.Contains("did not answer for 00:00:00. Check that the address of this machine is among the product's allowed IPs.", host.Log, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task PlanStopsWhenAnExistingProductDoesNotAnswer()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Api.AddProduct("shop-prod");
+ host.Server.UnreachableFor = int.MaxValue;
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Empty(host.Server.Certificates);
+ Assert.Contains(
+ "unreachable: 'shop-prod' at https://a.shop-prod.development.run does not answer this machine. Add its address to the " +
+ "product's allowed IPs in the RavenDB Cloud portal and deploy again.",
+ host.Log,
+ StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task EveryConnectionUsesOneLiveAdminCertificate()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Api.AddProduct("shop-prod");
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders", ensureCreated: true);
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ // The RavenDB client caches its HTTP clients per certificate thumbprint with the first instance it saw: a second
+ // instance, or a disposed one, breaks the next TLS handshake once the product moves to another address.
+ Assert.True(host.Server.ConnectionCertificates.Count >= 3);
+ var certificate = Assert.Single(host.Server.ConnectionCertificates.Distinct());
+ Assert.NotEmpty(certificate.Thumbprint);
+ }
+
+ [Fact]
+ public void OnlyAServerThatDoesNotAnswerIsWaitedFor()
+ {
+ var timeout = new HttpRequestException("A connection attempt failed.", new SocketException(10060));
+ var tlsRejected = new HttpRequestException("The SSL connection could not be established.", new System.Security.Authentication.AuthenticationException("The remote certificate was rejected."));
+
+ Assert.True(RavenDBServerAdministration.IsUnreachable(timeout));
+ Assert.True(RavenDBServerAdministration.IsUnreachable(new RavenException("An exception occurred while contacting the server.", timeout)));
+ Assert.True(RavenDBServerAdministration.IsUnreachable(new AllTopologyNodesDownException("Failed to retrieve cluster topology.", new AggregateException(timeout))));
+
+ Assert.False(RavenDBServerAdministration.IsUnreachable(new AllTopologyNodesDownException("Failed to retrieve cluster topology.", new AggregateException(tlsRejected))));
+ Assert.False(RavenDBServerAdministration.IsUnreachable(new AuthorizationException("Could not authorize access to the server.")));
+ Assert.False(RavenDBServerAdministration.IsUnreachable(new RavenException(
+ "An exception occurred while contacting the server.",
+ new HttpRequestException("The SSL connection could not be established.", new System.Security.Cryptography.CryptographicException("m_safeCertContext is an invalid handle.")))));
+ Assert.False(RavenDBServerAdministration.IsUnreachable(new InvalidOperationException("Something else.")));
+ }
+
+ [Fact]
+ public void RunModeKeepsTheLocalContainer()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+
+ var server = builder.AddRavenDB("ravendb").PublishAsRavenDBCloud(apiKey, "shop-prod", s_spec);
+
+ Assert.Empty(server.Resource.Annotations.OfType());
+ Assert.Null(server.Resource.PublishStrategy);
+ }
+
+ [Fact]
+ public void SecondPublishStrategyIsAnError()
+ {
+ using var host = new AppHost("publish");
+ var server = host.Builder.AddRavenDB("ravendb").PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec);
+
+ var exception = Assert.Throws(() => server.PublishAsExistingRavenDBCloud(host.ApiKey, "shared", "shop"));
+
+ Assert.Contains("already published with PublishAsRavenDBCloud, so it cannot also be published with PublishAsExistingRavenDBCloud", exception.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task OneProductForTwoServersIsAnError()
+ {
+ using var host = new AppHost("publish");
+ host.Builder.AddRavenDB("a").PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec);
+ host.Builder.AddRavenDB("b").PublishAsRavenDBCloud(host.ApiKey, "Shop-Prod", s_spec);
+
+ var exception = await Assert.ThrowsAnyAsync(host.RunAsync);
+
+ Assert.Contains("are published to the same RavenDB Cloud product", exception.ToString(), StringComparison.Ordinal);
+ }
+
+ ///
+ /// Docker Compose names a variable after each value with everything but letters and digits turned into '_': these
+ /// two certificates would share one, and an application would get the other product's certificate.
+ ///
+ [Fact]
+ public async Task ValuesThatWouldShareAComposeVariableAreAnError()
+ {
+ using var host = new AppHost("publish");
+ var a = host.Builder.AddRavenDB("a").PublishAsRavenDBCloud(host.ApiKey, "product-a", s_spec);
+ var ab = host.Builder.AddRavenDB("a-b").PublishAsRavenDBCloud(host.ApiKey, "product-b", s_spec);
+ host.Builder.AddContainer("b-c", "busybox").WithReference(a);
+ host.Builder.AddContainer("c", "busybox").WithReference(ab);
+
+ var exception = await Assert.ThrowsAnyAsync(host.RunAsync);
+
+ Assert.Contains("would share the Docker Compose variable A_B_C_CERTIFICATE", exception.ToString(), StringComparison.Ordinal);
+ }
+
+ [Theory]
+ [InlineData("-billing")]
+ [InlineData("billing.eu")]
+ [InlineData("billing team")]
+ public void InvalidClientNameIsRejected(string clientName)
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+
+ Assert.Throws(() => builder.AddRavenDB("ravendb").PublishAsExistingRavenDBCloud(apiKey, "shared", clientName));
+ }
+
+ [Fact]
+ public void ProductNameLongerThanRavenDBCloudAcceptsIsRejected()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+ var name = new string('a', 101);
+
+ Assert.Throws(() => builder.AddRavenDB("a").PublishAsRavenDBCloud(apiKey, name, s_spec));
+ Assert.Throws(() => builder.AddRavenDB("b").PublishAsExistingRavenDBCloud(apiKey, name, "billing"));
+ }
+
+ [Fact]
+ public void AttachedProductCannotBeTerminated()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var apiKey = builder.AddParameter("ravendb-cloud-api-key", secret: true);
+
+ Assert.Throws(() => builder.AddRavenDB("ravendb").PublishAsExistingRavenDBCloud(apiKey, "shared", "billing", o => o.TerminateOnDestroy = true));
+ }
+
+ [Fact]
+ public async Task ApiEndpointMustBeHttps()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Environment.Variables["RAVENDB_CLOUD_ENDPOINT"] = "http://api.example.com";
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ // The API key never leaves for a plain HTTP endpoint.
+ Assert.Empty(host.Api.Requests);
+ Assert.Contains("The RavenDB Cloud API endpoint 'http://api.example.com' in RAVENDB_CLOUD_ENDPOINT must be an https URL", host.Log, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task OtherApiEndpointIsShownInThePlan()
+ {
+ using var host = new AppHost("prepare-compose");
+ host.Environment.Variables["RAVENDB_CLOUD_ENDPOINT"] = "https://api.example.com";
+ var orders = host.Builder.AddRavenDB("ravendb")
+ .PublishAsRavenDBCloud(host.ApiKey, "shop-prod", s_spec, o => o.WithAllowedIps("203.0.113.0/24"))
+ .AddDatabase("orders");
+ host.Builder.AddContainer("api", "busybox").WithReference(orders);
+
+ await host.RunAsync();
+
+ Assert.Contains("endpoint: the RavenDB Cloud API at https://api.example.com, from RAVENDB_CLOUD_ENDPOINT, not the production one", host.Log, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void SpecFactoriesRejectWhatCannotBeAProduct()
+ {
+ Assert.Throws(() => RavenDBCloudSpec.Production(RavenDBCloudProvider.Aws, "eu-central-1", "P20", 0, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72"));
+ Assert.Throws(() => RavenDBCloudSpec.Production(RavenDBCloudProvider.Aws, " ", "P20", 64, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72"));
+ Assert.Throws(() => RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, "eu-central-1", "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, ""));
+ Assert.Throws(() => RavenDBCloudSpec.Development(RavenDBCloudProvider.Aws, null!, "Dev10", 20, RavenDBCloudStorageType.SsdStandard, RavenDBCloudDiskLayout.RootOnly, "Stable72"));
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBConsumersTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBConsumersTests.cs
new file mode 100644
index 000000000..6a582c6c2
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/RavenDBConsumersTests.cs
@@ -0,0 +1,96 @@
+using Aspire.Hosting;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Utils;
+using CommunityToolkit.Aspire.Hosting.RavenDB;
+using CommunityToolkit.Aspire.Testing;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+/// The applications that use a server, and the settings a deployment gives them (shared with other deployment packages).
+public class RavenDBConsumersTests
+{
+ [Fact]
+ public void ConsumersAreFoundWithTheirDatabases()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var ravendb = builder.AddRavenDB("ravendb");
+ var orders = ravendb.AddDatabase("orders");
+ ravendb.AddDatabase("reports");
+ var other = builder.AddRavenDB("other");
+
+ builder.AddContainer("api", "busybox").WithReference(orders);
+ builder.AddContainer("admin", "busybox").WithReference(ravendb).WithReference(other);
+ builder.AddContainer("unrelated", "busybox").WithReference(other);
+
+ var consumers = RavenDBConsumers.Find(new DistributedApplicationModel(builder.Resources), ravendb.Resource).ToDictionary(c => c.Resource.Name);
+
+ Assert.Equal(["admin", "api"], consumers.Keys.Order());
+ Assert.Equal(["orders"], consumers["api"].Databases);
+ Assert.Equal(1, consumers["api"].ServersReferenced);
+
+ // A reference to the server reaches every database declared on it.
+ Assert.Equal(["orders", "reports"], consumers["admin"].Databases);
+ Assert.Equal(2, consumers["admin"].ServersReferenced);
+ }
+
+ /// A resource that is not published, such as a tool for local development, gets nothing and needs no target.
+ [Fact]
+ public void ResourceExcludedFromPublishIsNoConsumer()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var ravendb = builder.AddRavenDB("ravendb");
+ var orders = ravendb.AddDatabase("orders");
+
+ builder.AddContainer("api", "busybox").WithReference(orders);
+ builder.AddContainer("seed", "busybox").WithReference(orders).ExcludeFromManifest();
+
+ var consumers = RavenDBConsumers.Find(new DistributedApplicationModel(builder.Resources), ravendb.Resource);
+
+ Assert.Equal("api", Assert.Single(consumers).Resource.Name);
+ }
+
+ [Fact]
+ public async Task CertificateGoesUnderEachConnectionNameAndTheDefaultSection()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var ravendb = builder.AddRavenDB("ravendb");
+ var api = builder.AddContainer("api", "busybox").WithReference(ravendb.AddDatabase("orders"));
+
+ Deliver(builder, ravendb.Resource);
+
+ var variables = await api.Resource.GetEnvironmentVariablesAsync(DistributedApplicationOperation.Publish);
+ Assert.Equal("certificate-content", variables["Aspire__RavenDB__Client__orders__CertificateBase64"]);
+ Assert.Equal("certificate-content", variables["Aspire__RavenDB__Client__CertificateBase64"]);
+ }
+
+ ///
+ /// With two servers there is no default section to fall back on: a connection renamed with
+ /// WithReference(db, connectionName: ...) gets the certificate under its new name.
+ ///
+ [Fact]
+ public async Task WithSeveralServersTheCertificateGoesUnderTheConnectionNamesOnly()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var ravendb = builder.AddRavenDB("ravendb");
+ var other = builder.AddRavenDB("other");
+ var api = builder.AddContainer("api", "busybox")
+ .WithReference(ravendb.AddDatabase("orders"), connectionName: "primary")
+ .WithReference(other);
+
+ Deliver(builder, ravendb.Resource);
+
+ var variables = await api.Resource.GetEnvironmentVariablesAsync(DistributedApplicationOperation.Publish);
+ Assert.Equal("certificate-content", variables["Aspire__RavenDB__Client__primary__CertificateBase64"]);
+ Assert.False(variables.ContainsKey("Aspire__RavenDB__Client__orders__CertificateBase64"));
+ Assert.False(variables.ContainsKey("Aspire__RavenDB__Client__other__CertificateBase64"));
+ Assert.False(variables.ContainsKey("Aspire__RavenDB__Client__CertificateBase64"));
+ }
+
+ private static void Deliver(IDistributedApplicationTestingBuilder builder, RavenDBServerResource server)
+ {
+ foreach (var consumer in RavenDBConsumers.Find(new DistributedApplicationModel(builder.Resources), server))
+ {
+ RavenDBClientConfiguration.DeliverCertificate(consumer, server, "certificate-content");
+ }
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/TypeScriptAppHostTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/TypeScriptAppHostTests.cs
new file mode 100644
index 000000000..c8a348609
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests/TypeScriptAppHostTests.cs
@@ -0,0 +1,178 @@
+using System.Diagnostics;
+using System.Text;
+using System.Text.RegularExpressions;
+using CommunityToolkit.Aspire.Testing;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Hosting.Server;
+using Microsoft.AspNetCore.Hosting.Server.Features;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.Tests;
+
+///
+/// The TypeScript example AppHost through the Aspire CLI, which must match the Aspire version of the repository.
+///
+public class TypeScriptAppHostTests
+{
+ private static readonly string s_appHost = Path.GetFullPath(Path.Combine(
+ "..", "..", "..", "..", "..", "examples", "ravendb", "CommunityToolkit.Aspire.Hosting.RavenDB.Cloud.AppHost.TypeScript"));
+
+ [Fact]
+ public async Task PublishReferencesTheDeployTimeValues()
+ {
+ var output = Directory.CreateTempSubdirectory(".ravendb-cloud-ts-publish");
+
+ try
+ {
+ var result = await RunAspireAsync(["publish", "--apphost", "apphost.mts", "-o", output.FullName, "--non-interactive", "--nologo"], new Dictionary());
+ Assert.True(result.ExitCode == 0, result.Output);
+
+ var compose = File.ReadAllText(Path.Combine(output.FullName, "docker-compose.yaml"));
+ Assert.DoesNotContain("ravendb/ravendb", compose, StringComparison.Ordinal);
+ Assert.Contains("ConnectionStrings__ravendb: \"URL=${RAVENDB_URL}\"", compose, StringComparison.Ordinal);
+ Assert.Contains("Aspire__RavenDB__Client__ravendb__CertificateBase64: \"${RAVENDB_APISERVICE_CERTIFICATE}\"", compose, StringComparison.Ordinal);
+ }
+ finally
+ {
+ output.Delete(recursive: true);
+ }
+ }
+
+ ///
+ /// The spec and the options travel from TypeScript callbacks: a lost callback would fall back to defaults without a
+ /// word, so the plan, computed against a local stand-in of the Cloud API, has to show exactly what the AppHost set.
+ ///
+ [Fact]
+ public async Task PlanShowsWhatTheTypeScriptCallbacksSet()
+ {
+ var api = new FakeRavenDBCloudApi();
+ await using var server = await ServeAsync(api);
+
+ var result = await RunAspireAsync(
+ ["do", "ravendb-cloud-plan-ravendb", "--apphost", "apphost.mts", "--non-interactive", "--nologo"],
+ new Dictionary
+ {
+ ["RAVENDB_CLOUD_ENDPOINT"] = server.Url,
+ ["Parameters__ravendb-cloud-api-key"] = "test-api-key",
+ });
+
+ Assert.True(result.ExitCode == 0, result.Output);
+ Assert.True(
+ // The CLI wraps long lines to the console width.
+ Regex.Replace(result.Output, @"\s+", " ").Contains("create 'aspire-ravendb-example': Development Dev10, Aws eu-central-1, 10 GB SsdStandard on SingleDataDisk, channel Stable72, allowed IPs 203.0.113.0/24", StringComparison.Ordinal),
+ result.Output);
+
+ // A plan never changes anything.
+ Assert.DoesNotContain(api.Requests, r => r.StartsWith("POST", StringComparison.Ordinal));
+ }
+
+ ///
+ /// The same plan against the real Cloud API, so a change of the API or of what RavenDB Cloud offers shows up here
+ /// rather than in a deployment. Needs a key in RAVENDB_CLOUD_API_KEY. The plan only reads.
+ ///
+ [Fact]
+ [RequiresAuthenticatedTool("ravendb-cloud", "Calls the RavenDB Cloud API with a real key.")]
+ public async Task PlanAgainstTheCloudApi()
+ {
+ var apiKey = Environment.GetEnvironmentVariable("RAVENDB_CLOUD_API_KEY");
+ Assert.SkipWhen(string.IsNullOrEmpty(apiKey), "Set RAVENDB_CLOUD_API_KEY to plan against RavenDB Cloud.");
+
+ var result = await RunAspireAsync(
+ ["do", "ravendb-cloud-plan-ravendb", "--apphost", "apphost.mts", "--non-interactive", "--nologo"],
+ new Dictionary { ["Parameters__ravendb-cloud-api-key"] = apiKey! });
+
+ // RavenDB Cloud offers the example's spec: the plan creates the product, or finds it as specified.
+ Assert.True(result.ExitCode == 0, result.Output);
+ Assert.Contains("'aspire-ravendb-example'", Regex.Replace(result.Output, @"\s+", " "), StringComparison.Ordinal);
+ }
+
+ private static async Task<(int ExitCode, string Output)> RunAspireAsync(IEnumerable arguments, IReadOnlyDictionary environment)
+ {
+ // On Windows the Aspire CLI installed as a .NET tool is an aspire.cmd shim, which only cmd.exe starts.
+ var start = new ProcessStartInfo(OperatingSystem.IsWindows() ? "cmd.exe" : "aspire")
+ {
+ RedirectStandardError = true,
+ RedirectStandardOutput = true,
+ UseShellExecute = false,
+ WorkingDirectory = s_appHost,
+ };
+
+ if (OperatingSystem.IsWindows())
+ {
+ start.ArgumentList.Add("/c");
+ start.ArgumentList.Add("aspire");
+ }
+
+ foreach (var argument in arguments)
+ {
+ start.ArgumentList.Add(argument);
+ }
+
+ // Aspire saves parameter values in the deployment state of the AppHost, and a saved value wins over the
+ // environment: without this, one run's API key would be used by every later run on the machine.
+ start.Environment["Pipeline__ClearCache"] = "true";
+
+ foreach (var (key, value) in environment)
+ {
+ start.Environment[key] = value;
+ }
+
+ using var process = new Process { StartInfo = start };
+ var output = new StringBuilder();
+ process.OutputDataReceived += (_, e) => { if (e.Data is not null) { lock (output) { output.AppendLine(e.Data); } } };
+ process.ErrorDataReceived += (_, e) => { if (e.Data is not null) { lock (output) { output.AppendLine(e.Data); } } };
+
+ process.Start();
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ await process.WaitForExitAsync(TestContext.Current.CancellationToken);
+ process.WaitForExit();
+
+ return (process.ExitCode, output.ToString());
+ }
+
+ /// Serves over HTTP on a free loopback port.
+ private static async Task ServeAsync(FakeRavenDBCloudApi api)
+ {
+ var builder = WebApplication.CreateSlimBuilder();
+ builder.WebHost.UseUrls("http://127.0.0.1:0");
+
+ var app = builder.Build();
+ var invoker = new HttpMessageInvoker(api, disposeHandler: false);
+
+ app.Run(async context =>
+ {
+ using var request = new HttpRequestMessage(new HttpMethod(context.Request.Method), $"http://fake{context.Request.Path}{context.Request.QueryString}");
+
+ foreach (var header in context.Request.Headers)
+ {
+ request.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
+ }
+
+ if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding"))
+ {
+ using var body = new MemoryStream();
+ await context.Request.Body.CopyToAsync(body);
+ request.Content = new ByteArrayContent(body.ToArray());
+ }
+
+ using var response = await invoker.SendAsync(request, context.RequestAborted);
+ context.Response.StatusCode = (int)response.StatusCode;
+ await response.Content.CopyToAsync(context.Response.Body);
+ });
+
+ await app.StartAsync(TestContext.Current.CancellationToken);
+
+ var url = app.Services.GetRequiredService().Features.Get()!.Addresses.First();
+ return new FakeApiServer(app, url);
+ }
+
+ private sealed class FakeApiServer(WebApplication app, string url) : IAsyncDisposable
+ {
+ public string Url { get; } = url;
+
+ public ValueTask DisposeAsync() => app.DisposeAsync();
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Tests/RavenDBPublishStrategyTests.cs b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Tests/RavenDBPublishStrategyTests.cs
new file mode 100644
index 000000000..e7f2c386d
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.Hosting.RavenDB.Tests/RavenDBPublishStrategyTests.cs
@@ -0,0 +1,76 @@
+#pragma warning disable CTASPIRERAVENDB001 // The API for deployment packages, under test
+
+using Aspire.Hosting;
+using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Utils;
+using CommunityToolkit.Aspire.Hosting.RavenDB;
+using CommunityToolkit.Aspire.Testing;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace CommunityToolkit.Aspire.Hosting.RavenDB.Tests;
+
+public class RavenDBPublishStrategyTests
+{
+ private static RavenDBPublishStrategy Strategy(string name = "PublishAsSomewhere") =>
+ new(name, ReferenceExpression.Create($"https://a.example.ravendb.cloud"));
+
+ [Fact]
+ public void SecondStrategyIsAnErrorNamingBoth()
+ {
+ var server = new RavenDBServerResource("ravendb", isSecured: false);
+ server.UsePublishStrategy(Strategy("PublishAsFirst"));
+
+ var exception = Assert.Throws(() => server.UsePublishStrategy(Strategy("PublishAsSecond")));
+
+ Assert.Equal(
+ "RavenDB server 'ravendb' is already published with PublishAsFirst, so it cannot also be published with PublishAsSecond. " +
+ "A server has one publish strategy; to use a different one per environment, choose it with an if in the AppHost.",
+ exception.Message);
+ }
+
+ [Fact]
+ public async Task ConnectionStringPointsAtTheStrategysUrl()
+ {
+ var server = new RavenDBServerResource("ravendb", isSecured: true);
+ var database = new RavenDBDatabaseResource("orders", "orders", server);
+
+ server.UsePublishStrategy(Strategy());
+
+ Assert.Equal("URL=https://a.example.ravendb.cloud", await server.ConnectionStringExpression.GetValueAsync(TestContext.Current.CancellationToken));
+ Assert.Equal("URL=https://a.example.ravendb.cloud;Database=orders", await database.ConnectionStringExpression.GetValueAsync(TestContext.Current.CancellationToken));
+ Assert.Equal("https://a.example.ravendb.cloud", await server.UriExpression.GetValueAsync(TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public void EnsureCreatedDatabasesAreRemembered()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create();
+ var ravendb = builder.AddRavenDB("ravendb");
+
+ ravendb.AddDatabase("orders", ensureCreated: true);
+ ravendb.AddDatabase("reports");
+
+ Assert.Equal(["orders"], ravendb.Resource.DatabasesToCreate);
+ }
+
+ [Fact]
+ public async Task PublishedElsewhereTheServerIsNotWaitedForNorPublished()
+ {
+ using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish);
+ var ravendb = builder.AddRavenDB("ravendb");
+ var orders = ravendb.AddDatabase("orders");
+ var other = builder.AddContainer("other", "busybox");
+ var api = builder.AddContainer("api", "busybox").WithReference(orders).WaitFor(ravendb).WaitFor(orders).WaitFor(other);
+
+ ravendb.WithPublishStrategy(Strategy());
+
+ await using var app = await builder.BuildAsync(TestContext.Current.CancellationToken);
+ await builder.Eventing.PublishAsync(
+ new BeforeStartEvent(app.Services, app.Services.GetRequiredService()),
+ TestContext.Current.CancellationToken);
+
+ var waits = api.Resource.Annotations.OfType().Select(w => w.Resource.Name).ToList();
+ Assert.Equal(["other"], waits);
+ Assert.Contains(ravendb.Resource.Annotations, a => a is ManifestPublishingCallbackAnnotation { Callback: null });
+ }
+}
diff --git a/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/AspireRavenDBExtensionsTests.cs b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/AspireRavenDBExtensionsTests.cs
index dedebb757..b742a26a4 100644
--- a/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/AspireRavenDBExtensionsTests.cs
+++ b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/AspireRavenDBExtensionsTests.cs
@@ -4,6 +4,9 @@
using Raven.Client.Documents;
using Raven.Client.Documents.Session;
using Raven.Client.Http;
+using Raven.Client.ServerWide;
+using Raven.Client.ServerWide.Operations;
+using Raven.Client.ServerWide.Sharding;
namespace CommunityToolkit.Aspire.RavenDB.Client.Tests;
@@ -352,6 +355,65 @@ public void AddKeyedRavenDbClient_ModifyDocumentStore()
Assert.Equal(99, documentStore.Conventions.MaxNumberOfRequestsPerSession);
}
+ [Fact]
+ public void AddRavenDbClient_CreateDatabaseUsesAnExistingDatabase()
+ {
+ var databaseName = Guid.NewGuid().ToString("N");
+
+ using (var store = new DocumentStore { Urls = [DefaultConnectionString] }.Initialize())
+ {
+ store.Maintenance.Server.Send(new CreateDatabaseOperation(new DatabaseRecord(databaseName)));
+ }
+
+ var builder = CreateBuilder();
+
+ // Database names are case insensitive: the existing database is used, not created a second time.
+ builder.AddRavenDBClient(connectionName: DefaultConnectionName, configureSettings: clientSettings =>
+ {
+ clientSettings.CreateDatabase = true;
+ clientSettings.DatabaseName = databaseName.ToUpperInvariant();
+ });
+
+ using var host = builder.Build();
+
+ var documentStore = host.Services.GetRequiredService();
+ Assert.Equal(databaseName.ToUpperInvariant(), documentStore.Database);
+ }
+
+ ///
+ /// The server lists a sharded database by its shards (name$0, name$1), so it is asked about by its own
+ /// name: CreateDatabase uses it instead of trying to create it a second time.
+ ///
+ [Fact]
+ public void AddRavenDbClient_CreateDatabaseUsesAnExistingShardedDatabase()
+ {
+ var databaseName = Guid.NewGuid().ToString("N");
+
+ using (var store = new DocumentStore { Urls = [DefaultConnectionString] }.Initialize())
+ {
+ var record = new DatabaseRecord(databaseName)
+ {
+ Sharding = new ShardingConfiguration
+ {
+ Shards = new Dictionary { [0] = new(), [1] = new() },
+ },
+ };
+ store.Maintenance.Server.Send(new CreateDatabaseOperation(record));
+ }
+
+ var builder = CreateBuilder();
+ builder.AddRavenDBClient(connectionName: DefaultConnectionName, configureSettings: clientSettings =>
+ {
+ clientSettings.CreateDatabase = true;
+ clientSettings.DatabaseName = databaseName;
+ });
+
+ using var host = builder.Build();
+
+ var documentStore = host.Services.GetRequiredService();
+ Assert.Equal(databaseName, documentStore.Database);
+ }
+
private HostApplicationBuilder CreateBuilder(IEnumerable>? config = null)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
diff --git a/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientCertificateTests.cs b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientCertificateTests.cs
new file mode 100644
index 000000000..38415b7d5
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientCertificateTests.cs
@@ -0,0 +1,86 @@
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Raven.Client.Documents;
+
+namespace CommunityToolkit.Aspire.RavenDB.Client.Tests;
+
+/// A certificate delivered as a value, as the RavenDB Cloud hosting integration does, instead of a file.
+public class RavenDBClientCertificateTests
+{
+ private static (string Base64, string Thumbprint) CreateCertificate()
+ {
+ using var key = RSA.Create(2048);
+ var request = new CertificateRequest("CN=aspire.api", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
+ using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(30));
+
+ return (Convert.ToBase64String(certificate.Export(X509ContentType.Pfx)), certificate.Thumbprint);
+ }
+
+ private static IDocumentStore Resolve(params (string Key, string Value)[] settings)
+ {
+ var builder = Host.CreateEmptyApplicationBuilder(null);
+ builder.Configuration.AddInMemoryCollection(
+ [
+ new("ConnectionStrings:db", "URL=https://a.example.ravendb.cloud;Database=orders"),
+ new("Aspire:RavenDB:Client:DisableHealthChecks", "true"),
+ .. settings.Select(s => new KeyValuePair(s.Key, s.Value)),
+ ]);
+
+ builder.AddRavenDBClient("db");
+
+ var host = builder.Build();
+ return host.Services.GetRequiredService();
+ }
+
+ [Fact]
+ public void CertificateComesFromTheConnectionsSection()
+ {
+ var (base64, thumbprint) = CreateCertificate();
+
+ using var store = Resolve(("Aspire:RavenDB:Client:db:CertificateBase64", base64));
+
+ Assert.Equal(thumbprint, store.Certificate.Thumbprint);
+ }
+
+ [Fact]
+ public void CertificateComesFromTheDefaultSection()
+ {
+ var (base64, thumbprint) = CreateCertificate();
+
+ using var store = Resolve(("Aspire:RavenDB:Client:CertificateBase64", base64));
+
+ Assert.Equal(thumbprint, store.Certificate.Thumbprint);
+ }
+
+ [Fact]
+ public void InvalidBase64IsReportedWithoutTheValue()
+ {
+ var exception = Assert.ThrowsAny(() => Resolve(("Aspire:RavenDB:Client:db:CertificateBase64", "not base64!")));
+
+ var invalid = Assert.IsType(Unwrap(exception));
+ Assert.Contains("'CertificateBase64' is not valid base64", invalid.Message, StringComparison.Ordinal);
+ Assert.DoesNotContain("not base64!", invalid.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ContentThatIsNotAPfxIsReported()
+ {
+ var exception = Assert.ThrowsAny(() => Resolve(("Aspire:RavenDB:Client:db:CertificateBase64", Convert.ToBase64String("not a pfx"u8.ToArray()))));
+
+ Assert.Contains("cannot be loaded", Assert.IsType(Unwrap(exception)).Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void HttpsWithoutACertificateNamesEveryWayToGiveOne()
+ {
+ var exception = Assert.ThrowsAny(() => Resolve());
+
+ Assert.Contains("'RavenDBClientSettings.CertificateBase64'", Unwrap(exception).Message, StringComparison.Ordinal);
+ }
+
+ private static Exception Unwrap(Exception exception) =>
+ exception is System.Reflection.TargetInvocationException or AggregateException && exception.InnerException is { } inner ? Unwrap(inner) : exception;
+}
diff --git a/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientConnectionStringTests.cs b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientConnectionStringTests.cs
new file mode 100644
index 000000000..152fb823b
--- /dev/null
+++ b/tests/CommunityToolkit.Aspire.RavenDB.Client.Tests/RavenDBClientConnectionStringTests.cs
@@ -0,0 +1,29 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Raven.Client.Documents;
+
+namespace CommunityToolkit.Aspire.RavenDB.Client.Tests;
+
+public class RavenDBClientConnectionStringTests
+{
+ /// The URL lists every node of a cluster, as the RavenDB Cloud hosting integration writes it.
+ [Fact]
+ public void UrlListsTheNodesOfACluster()
+ {
+ var builder = Host.CreateEmptyApplicationBuilder(null);
+ builder.Configuration.AddInMemoryCollection(
+ [
+ new("ConnectionStrings:db", "URL=http://a.example:8080, http://b.example:8080,http://c.example:8080;Database=orders"),
+ new("Aspire:RavenDB:Client:DisableHealthChecks", "true"),
+ ]);
+
+ builder.AddRavenDBClient("db");
+
+ using var host = builder.Build();
+ var store = host.Services.GetRequiredService();
+
+ Assert.Equal(["http://a.example:8080", "http://b.example:8080", "http://c.example:8080"], store.Urls);
+ Assert.Equal("orders", store.Database);
+ }
+}