From 2aad6d65a474569688085b4f2285f9d1faeaff7e Mon Sep 17 00:00:00 2001 From: hydralerne Date: Sat, 14 Nov 2026 20:38:47 +0100 Subject: [PATCH 1/6] feat(cloud): migrate Oblien integration to SDK 3 and versioned VM API --- .env.example | 3 +- apps/api/.env.saas.example | 3 +- .../modules/billing/billing-checkout.test.ts | 2 +- .../billing/oblien-billing-api.test.ts | 55 +++---- .../billing/oblien-managed-transfer.test.ts | 5 +- .../billing/oblien-webhook-crypto.test.ts | 2 +- .../src/modules/cloud/cloud-pages.service.ts | 2 +- .../cloud/cloud-resource.controller.ts | 4 +- .../modules/cloud/cloud-saas.controller.ts | 12 +- .../domains/routing-apply.service.test.ts | 24 +-- apps/api/src/modules/images/images.service.ts | 2 +- .../project-cleanup.ref-shape.test.ts | 2 +- .../e2e/cloud-shared-workspace.e2e.test.ts | 8 +- .../e2e/platform-import-project.e2e.test.ts | 2 +- .../fixtures/oblien-capacity-catalog.json | 16 +- apps/api/test/helpers/monthly-cloud-offer.ts | 2 +- apps/api/test/helpers/oblien-vm-billing.ts | 40 +++++ apps/api/test/lib/cloud-capacity.test.ts | 2 +- .../test/lib/cloud-docker-workspace.test.ts | 18 +-- .../lib/cloud-namespace-token-reuse.test.ts | 10 +- apps/api/test/lib/cloud-preflight.test.ts | 2 +- .../test/lib/cloud-resource-limits.test.ts | 31 ++-- .../api/test/lib/cloud-resource-proxy.test.ts | 10 +- apps/api/test/lib/cloud-tenant-admin.test.ts | 12 +- .../modules/actions/billing-webhook.test.ts | 2 +- .../cloud-install-cleanup.integration.test.ts | 16 +- .../billing/billing-sdk-parity.test.ts | 11 +- .../modules/cloud-execution-access.test.ts | 2 +- .../lifecycle.integration.test.ts | 60 +++---- .../compose-host-channel-notice.test.ts | 6 +- .../projects/cloud-routing-regression.test.ts | 12 +- .../system/server-managed-controls.test.ts | 8 +- bun.lock | 8 +- docs/openship-cloud-launch.md | 15 +- packages/adapters/package.json | 2 +- .../adapters/scripts/verify-cloud-docker.ts | 37 ++--- .../scripts/verify-cloud-isolation.ts | 107 ++++++------- packages/adapters/src/index.ts | 2 + .../src/infra/cloud-routing-sdk.test.ts | 16 +- .../adapters/src/infra/cloud-routing.test.ts | 12 +- packages/adapters/src/infra/cloud.test.ts | 2 +- packages/adapters/src/infra/cloud.ts | 50 +++--- packages/adapters/src/oblien-contract.test.ts | 150 ++++++++++++++++++ packages/adapters/src/oblien-contract.ts | 108 +++++++++++++ packages/adapters/src/oblien-metrics.test.ts | 2 +- packages/adapters/src/oblien.test.ts | 44 ++--- packages/adapters/src/oblien.ts | 33 ++-- .../src/runtime/cloud-deploy-static.test.ts | 6 +- .../runtime/cloud-host-build-refusal.test.ts | 10 +- .../adapters/src/runtime/cloud/docker.test.ts | 22 +-- packages/adapters/src/runtime/cloud/docker.ts | 6 +- .../src/runtime/cloud/server-connection.ts | 12 +- .../src/runtime/cloud/workspace-delete.ts | 4 +- .../src/runtime/cloud/workspace-ready.test.ts | 12 +- .../src/runtime/cloud/workspace-ready.ts | 12 +- .../src/runtime/cloud/workspace-resources.ts | 8 +- .../adapters/src/runtime/oblien-routing.ts | 24 +-- packages/adapters/src/runtime/transfer.ts | 4 +- packages/adapters/test/cloud-infra.test.ts | 2 +- .../test/cloud-project-route-cleanup.test.ts | 6 +- .../adapters/test/managed-routing-fixture.ts | 6 +- packages/adapters/test/oblien-routing.test.ts | 28 ++-- packages/platform/src/engine/config/env.ts | 2 +- .../platform/src/engine/lib/cloud-capacity.ts | 2 +- .../src/engine/lib/cloud-docker-workspace.ts | 18 +-- .../src/engine/lib/cloud-preflight.ts | 3 +- .../src/engine/lib/cloud-resource-limits.ts | 18 ++- .../src/engine/lib/cloud-tenant-admin.ts | 12 +- .../src/engine/lib/cloud-workspace-host.ts | 6 +- .../platform/src/engine/lib/cloud/types.ts | 2 +- .../src/engine/lib/oblien-billing-api.ts | 26 ++- .../src/engine/lib/oblien-namespace.ts | 5 +- .../platform/src/engine/lib/openship-cloud.ts | 8 +- .../modules/actions/billing-namespace.ts | 4 +- .../modules/actions/cloud-runner.test.ts | 2 +- .../engine/modules/actions/cloud-runner.ts | 16 +- .../engine/modules/assistant/remote-target.ts | 4 +- .../billing/billing-resources.service.ts | 6 +- .../modules/billing/management.service.ts | 2 +- .../modules/billing/oblien-webhook-crypto.ts | 2 +- .../modules/billing/oblien-webhook.service.ts | 2 +- .../cloud-workspace.service.ts | 2 +- .../modules/domains/routing-apply.service.ts | 2 +- .../modules/system/managed-server-access.ts | 2 +- .../system/server-managed.operations.ts | 4 +- .../deployment-container-info-schema.test.ts | 2 +- 86 files changed, 805 insertions(+), 483 deletions(-) create mode 100644 apps/api/test/helpers/oblien-vm-billing.ts create mode 100644 packages/adapters/src/oblien-contract.test.ts create mode 100644 packages/adapters/src/oblien-contract.ts diff --git a/.env.example b/.env.example index e0073b4fb..fb8123bc7 100644 --- a/.env.example +++ b/.env.example @@ -251,7 +251,8 @@ GITHUB_APP_SLUG=openship-io # Set these in the deployed API environment. Both Compose stacks load this # root .env; they do NOT load apps/api/.env.saas (used by dev:saas). # Use the production account's credentials for the production SaaS. -# OBLIEN_API_URL=https://api.oblien.com +# Optional complete API mount override. Unset uses the Oblien SDK default. +# OBLIEN_API_URL=https://your-proxy.example/api/v1 # OBLIEN_CLIENT_ID= # OBLIEN_CLIENT_SECRET= # Optional public base-image pack for NEW managed Cloud spaces only. diff --git a/apps/api/.env.saas.example b/apps/api/.env.saas.example index a4f391f91..0c1556ce6 100644 --- a/apps/api/.env.saas.example +++ b/apps/api/.env.saas.example @@ -31,7 +31,8 @@ BETTER_AUTH_SECRET=change-me-in-production INTERNAL_TOKEN=change-me-32-byte-random-hex # Required for cloud deployments. -OBLIEN_API_URL=https://api.oblien.com +# Leave unset to use the installed SDK's default API version. +# OBLIEN_API_URL=https://your-proxy.example/api/v1 OBLIEN_CLIENT_ID= OBLIEN_CLIENT_SECRET= # Optional: enable only after this software preset is published on your provider. diff --git a/apps/api/src/modules/billing/billing-checkout.test.ts b/apps/api/src/modules/billing/billing-checkout.test.ts index 9bfae4ea9..58bfb2d97 100644 --- a/apps/api/src/modules/billing/billing-checkout.test.ts +++ b/apps/api/src/modules/billing/billing-checkout.test.ts @@ -37,7 +37,7 @@ vi.mock("@repo/platform/engine/lib/cloud-workspace-host", () => ({ readCloudWorkspaceHost: async () => ({ provider: null }), })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ - getOblienClient: () => ({ workspaces: { getQuota: h.quota } }), + getOblienClient: () => ({ vms: { getQuota: h.quota } }), getOblienBillingApi: () => ({ createCheckout: h.checkout, createPortal: h.portal, diff --git a/apps/api/src/modules/billing/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts index 16fd45c0e..5c991d871 100644 --- a/apps/api/src/modules/billing/oblien-billing-api.test.ts +++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; import { OblienBillingApi, oblienOfferSchema, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; import { BillingOperationSchemas } from "@repo/contracts"; import { Value } from "@sinclair/typebox/value"; +import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing"; import capacityCatalog from "../../../test/fixtures/oblien-capacity-catalog.json"; import { monthlyCloudBilling, unpaidMonthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer"; @@ -25,7 +26,7 @@ const subscription = { success: true, namespace: "os-one", subscription: { cancelAtPeriodEnd: true, canceledAt: "2026-09-15T00:00:00Z", } }; function setup(body: unknown, status = 200) { - const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(body, { status })); + const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(providerBillingFixture(body), { status })); const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", fetch: fetcher as unknown as typeof fetch }); return { api, fetcher }; } @@ -47,7 +48,7 @@ describe("Oblien billing SDK and transport contract", () => { await api.createCheckout({ namespace: "os-one", kind: "subscription", billingInterval: "yearly", offer: { ...monthlyCloudBilling().subscription.offer!, unitAmount: 12000 }, metadata, affiliateBuyer, affiliateCode: "AF-0123456789", successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "referral-transport" }); - expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST", redirect: "error", signal: expect.any(AbortSignal), headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), })); @@ -59,7 +60,7 @@ describe("Oblien billing SDK and transport contract", () => { const live = { success: true, credits_per_dollar: 100, rate_card_id: "live", rates: { cpu_per_min: 1.5, memory_per_gb_min: 0.2, disk_per_gb: 0, network_per_gb: 0.15 } }; const { api, fetcher } = setup({ ...live, compute_rate_cards: [{ chargeEnabled: false, cpu_per_min: 0.001 }] }); expect(await api.getMeteredPricing()).toEqual(live); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } })); }); it.each([ { credits_per_dollar: 50, rate_card_id: "new", rates: { cpu_per_min: 1, memory_per_gb_min: 1, disk_per_gb: 0, network_per_gb: 0 } }, @@ -74,14 +75,14 @@ describe("Oblien billing SDK and transport contract", () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout, wallet: { balance: 12000 } }); expect(await api.getPendingCapacityCheckout("os-one")).toEqual({ success: true, namespace: "os-one", pendingCheckout: { ...pendingCheckout, quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" } } }); - expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/billing/capacity?namespace=os-one"); + expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/v1/billing/capacity?namespace=os-one"); await expect(api.getPendingCapacityCheckout("os-other")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("cancels a capacity payment with the saved provider quote and retry identity", async () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout: null }); const input = { quoteId: "quote_pending", idempotencyKey: "cancel-once" }; await expect(api.cancelCapacityCheckout("os-one", input)).resolves.toMatchObject({ pendingCheckout: null }); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/capacity/change/cancel", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/capacity/change/cancel", expect.objectContaining({ method: "POST", })); expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ namespace: "os-one", ...input }); @@ -101,7 +102,7 @@ describe("Oblien billing SDK and transport contract", () => { (await api.cancelCheckout("os-one", checkout.id, { idempotencyKey: "cancel-once" })).checkout, ).toEqual(checkout); expect(fetcher).toHaveBeenCalledWith( - "https://api.oblien.com/billing/checkout/bco_original/cancel", + "https://api.oblien.com/v1/billing/checkout/bco_original/cancel", expect.objectContaining({ method: "POST", body: JSON.stringify({ namespace: "os-one", idempotencyKey: "cancel-once" }), @@ -123,7 +124,7 @@ describe("Oblien billing SDK and transport contract", () => { it.each([ { quote: { id: "quote_pending", namespace: "os-other", paymentSource: "stripe" }, checkoutId: "cs_requested", url: null }, { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://evil.example/pay" }, - { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/not-a-payment#secret" }, + { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/v1/not-a-payment#secret" }, ])("rejects foreign capacity scope and untrusted resume URLs", async pendingCheckout => { await expect(setup({ success: true, namespace: "os-one", pendingCheckout }).api.getPendingCapacityCheckout("os-one")).rejects.toThrow(); }); @@ -135,16 +136,16 @@ describe("Oblien billing SDK and transport contract", () => { }); it("scopes complimentary policy writes to the requested namespace and validates the response", async () => { const policy = { quotaLimit: 3000, overdraft: 60, suspendThreshold: 60, onOverdraftAction: "stop_workspaces" as const }; - const result = { success: true, namespace: "os-one", service: "workspace_vm", ...policy }; + const result = { success: true, namespace: "os-one", service: "vm_compute", ...policy }; const { api, fetcher } = setup(result); expect(await api.setPolicy("os-one", policy)).toEqual(result); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(policy) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(providerBillingFixture(policy)) })); await expect(api.setPolicy("os-two", policy)).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("keeps the same provider reset key on retry and rejects an unscoped reset response", async () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", applied: false }); expect(await api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")).toMatchObject({ applied: false }); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) })); await expect(setup({ success: true, applied: true }).api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")) .rejects.toMatchObject({ code: "OBLIEN_BILLING_INVALID_RESPONSE" }); }); @@ -215,7 +216,7 @@ describe("Oblien billing SDK and transport contract", () => { expect(state.checkout).not.toHaveProperty("walletCredits"); expect(state.checkout).not.toHaveProperty("paymentId"); expect(fetcher.mock.calls[0]![0]).toBe( - "https://api.oblien.com/billing/checkout/cs_requested?namespace=os-one", + "https://api.oblien.com/v1/billing/checkout/cs_requested?namespace=os-one", ); await expect(api.getCheckout("os-other", "cs_requested")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH", @@ -251,7 +252,7 @@ describe("Oblien billing SDK and transport contract", () => { it("authenticates server requests and validates the returned customer namespace", async () => { const { api, fetcher } = setup(entitlement); expect((await api.getEntitlement("os-one")).quota.used).toBe(-50); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/entitlement?namespace=os-one", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/entitlement?namespace=os-one", expect.objectContaining({ headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), redirect: "error", })); await expect(api.getEntitlement("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); @@ -275,12 +276,12 @@ describe("Oblien billing SDK and transport contract", () => { idempotencyKey: "checkout-123", }; await api.createCheckout(input); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST" })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true }); }); it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => { const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee"; - const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`; + const url = `https://api.oblien.com/v1/billing/pay#${"a".repeat(43)}`; const { api } = setup({ success: true, url, checkoutId }); await expect(api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata, successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "promotion-checkout" })) @@ -288,11 +289,11 @@ describe("Oblien billing SDK and transport contract", () => { }); it.each([ "http://api.oblien.com/billing/pay", "https://api.oblien.com.evil.example/billing/pay", - "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/other", - "https://api.oblien.com/billing/pay", "https://user@api.oblien.com/billing/pay", - "https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/billing/pay/", + "https://api.oblien.com/v1/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other", + "https://api.oblien.com/v1/billing/pay", "https://user@api.oblien.com/billing/pay", + "https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/v1/billing/pay/", ])("rejects an invalid promotion checkout URL: %s", async (value) => { - const url = value + (value === "https://api.oblien.com/billing/pay" ? "#short" : `#${"a".repeat(43)}`); + const url = value + (value === "https://api.oblien.com/v1/billing/pay" ? "#short" : `#${"a".repeat(43)}`); await expect(setup({ success: true, url, checkoutId: "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee" }).api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata, successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "bad-promotion-checkout" })) @@ -553,7 +554,7 @@ describe("Oblien billing SDK and transport contract", () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", url: "https://billing.stripe.com/p/session/test" }); const input = { namespace: "os-one", returnUrl: "https://app.openship.io/billing/overview" }; expect((await api.createPortal(input)).url).toBe("https://billing.stripe.com/p/session/test"); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) })); await expect(api.createPortal({ ...input, namespace: "os-two" })).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("rejects a legacy owner portal even when its hosted URL is otherwise valid", async () => { @@ -572,7 +573,7 @@ describe("Oblien billing SDK and transport contract", () => { ] as const)("uses the SDK %s method and checks the response namespace", async (method, verb, path) => { const { api, fetcher } = setup(subscription); expect(await api[method]("os-one")).toEqual(subscription); - expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com${path}`, expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com/v1${path}`, expect.objectContaining({ method: verb, ...(verb === "POST" ? { body: JSON.stringify({ namespace: "os-one" }) } : {}), })); await expect(api[method]("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); @@ -612,7 +613,7 @@ describe("Oblien monthly capacity contract", () => { const catalog = await api.assertMonthlyCapacitySupport(); expect(catalog.tariff.usage).toEqual({ activeVcpuHourCents: 3, reservedGiBHourCents: 0.8, retainedGiBMonthCents: 5, monthHours: 720 }); const [url, request] = fetcher.mock.calls[0]!; - expect(String(url)).toBe("https://api.oblien.com/billing/capacity/catalog"); + expect(String(url)).toBe("https://api.oblien.com/v1/billing/capacity/catalog"); expect(request?.headers).not.toHaveProperty("X-Client-Secret"); expect(request?.headers).not.toHaveProperty("X-Client-ID"); }); @@ -692,9 +693,9 @@ describe("Oblien monthly capacity contract", () => { offer: subscription.offer!, metadata: subscription.metadata!, idempotencyKey: "saved-monthly-order", successUrl: "https://app.openship.io/billing/overview", cancelUrl: "https://app.openship.io/billing/plans" }); const [url, request] = fetcher.mock.calls[0]!; - expect(String(url)).toBe("https://api.oblien.com/billing/checkout"); + expect(String(url)).toBe("https://api.oblien.com/v1/billing/checkout"); const sent = JSON.parse(String(request?.body)); - expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 1 } }); + expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 1 } }); expect(sent.offer).not.toHaveProperty("policy"); expect(sent.idempotencyKey).toBe("saved-monthly-order"); expect(sent.allowPromotionCodes).toBe(unitAmount > 0); @@ -763,18 +764,18 @@ describe("Oblien subscription changes", () => { it("delegates all four methods to the official SDK and preserves provider cents and fractional credits", async () => { const preview = setup({ success: true, namespace: "os-one", quote }); expect((await preview.api.previewPlanChange("os-one", input)).quote).toEqual(quote); - expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/subscription/changes/preview", + expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/subscription/changes/preview", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(preview.fetcher.mock.calls[0]![1]!.body))).toEqual({ namespace: "os-one", ...input }); const accept = setup({ success: true, namespace: "os-one", change }, 202); expect((await accept.api.changePlan("os-one", { quoteId: quote.id, idempotencyKey: "confirm-request" })).change.status).toBe("payment_pending"); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", quoteId: quote.id, idempotencyKey: "confirm-request" }); await accept.api.getPlanChange("os-one", change.id); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" })); + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" })); await accept.api.cancelPlanChange("os-one", change.id, "cancel-request"); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one/cancel", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one/cancel", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", idempotencyKey: "cancel-request" }); }); diff --git a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts index fb2ed26a8..c43a1504f 100644 --- a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts +++ b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; import { Value } from "@sinclair/typebox/value"; import { BillingComputeSchema } from "@repo/contracts"; +import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing"; import { OblienBillingApi, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; import { monthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer"; import transfer from "../../../test/fixtures/oblien-managed-transfer.json"; -// SDK 2.10's live response shape, with synthetic counters and no customer data. +// Native provider transfer counters with synthetic data. const unlimited = { ...transfer, unlimited: true, includedBytes: null, includedAvailableBytes: null, availableBytes: null }; async function readTransfer(network: unknown, covered = true) { @@ -14,7 +15,7 @@ async function readTransfer(network: unknown, covered = true) { ...entitlement.capacity, computeCovered: covered, network, } }; const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", - fetch: (async () => Response.json(payload)) as typeof fetch }); + fetch: (async () => Response.json(providerBillingFixture(payload))) as typeof fetch }); const result = await api.getEntitlement("os-one"); assertOblienEntitlementMatchesSubscription(result, subscription); return result.capacity!; diff --git a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts index d92cc82fe..25c707895 100644 --- a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts +++ b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts @@ -64,7 +64,7 @@ describe("deriveOblienEventId", () => { const base: OblienEventEnvelope = { event: "credits.usage", timestamp: "2026-07-21T10:00:00Z", - data: { namespace: "os-abc", workspace_id: "ws_1", period_end: "2026-08-01T00:00:00Z" }, + data: { namespace: "os-abc", vm_id: "ws_1", period_end: "2026-08-01T00:00:00Z" }, }; it("is deterministic for the same payload", () => { diff --git a/apps/api/src/modules/cloud/cloud-pages.service.ts b/apps/api/src/modules/cloud/cloud-pages.service.ts index 9530a4f99..f2b18387a 100644 --- a/apps/api/src/modules/cloud/cloud-pages.service.ts +++ b/apps/api/src/modules/cloud/cloud-pages.service.ts @@ -5,7 +5,7 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access"; export async function createCloudPage( ctx: RequestContext, - input: { workspace_id: string; path: string; name: string; slug: string; domain?: string }, + input: { vm_id: string; path: string; name: string; slug: string; domain?: string }, ): Promise { const workspaceId = await authorizeCloudRelayWorkspace(ctx); const namespace = await ensureNamespace(ctx.organizationId, workspaceId); diff --git a/apps/api/src/modules/cloud/cloud-resource.controller.ts b/apps/api/src/modules/cloud/cloud-resource.controller.ts index db9cd5e26..34ac7305e 100644 --- a/apps/api/src/modules/cloud/cloud-resource.controller.ts +++ b/apps/api/src/modules/cloud/cloud-resource.controller.ts @@ -10,9 +10,9 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access"; const id = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/); const path = z.string().min(1).max(2048); const domain = z.string().min(1).max(253); -const source = z.object({ workspace_id: id, path }).strict(); +const source = z.object({ vm_id: id, path }).strict(); const action = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("proxy"), workspace: id, port: z.number().int().min(1).max(65535), + z.object({ kind: z.literal("proxy"), vm: id, port: z.number().int().min(1).max(65535), stripPrefix: z.boolean().optional(), path: path.optional() }).strict(), z.object({ kind: z.literal("rewrite"), to: path }).strict(), z.object({ kind: z.literal("redirect"), to: path, status: z.union([z.literal(301), z.literal(302), z.literal(307), z.literal(308)]).optional() }).strict(), diff --git a/apps/api/src/modules/cloud/cloud-saas.controller.ts b/apps/api/src/modules/cloud/cloud-saas.controller.ts index 03810ef70..10adfda66 100644 --- a/apps/api/src/modules/cloud/cloud-saas.controller.ts +++ b/apps/api/src/modules/cloud/cloud-saas.controller.ts @@ -635,11 +635,11 @@ export async function checkEdgeVerification(c: Context) { // ─── Pages proxy ──────────────────────────────────────────────────────────── /** - * POST /api/cloud/pages { workspace_id, path, name, slug, domain? } + * POST /api/cloud/pages { vm_id, path, name, slug, domain? } * * Forwards to Oblien with the caller's namespace token. Oblien * enforces: - * - `workspace_id` must belong to the caller's namespace (or 404) + * - `vm_id` must belong to the caller's namespace (or 404) * - `slug` must be free on the shared zone (or 409 SLUG_TAKEN) * * Returns the raw Oblien SDK shape so the caller's infrastructure adapter @@ -648,18 +648,18 @@ export async function checkEdgeVerification(c: Context) { export async function pagesProxy(c: Context) { const ctx = getRequestContext(c); const body = await c.req.json<{ - workspace_id?: string; + vm_id?: string; path?: string; name?: string; slug?: string; domain?: string; }>(); - if (!body.workspace_id || !body.path || !body.name || !body.slug) { - return c.json({ error: "workspace_id, path, name and slug are required" }, 400); + if (!body.vm_id || !body.path || !body.name || !body.slug) { + return c.json({ error: "vm_id, path, name and slug are required" }, 400); } try { const result = await createCloudPage(ctx, { - workspace_id: body.workspace_id, + vm_id: body.vm_id, path: body.path, name: body.name, slug: body.slug, diff --git a/apps/api/src/modules/domains/routing-apply.service.test.ts b/apps/api/src/modules/domains/routing-apply.service.test.ts index c3a3b8933..c63228aff 100644 --- a/apps/api/src/modules/domains/routing-apply.service.test.ts +++ b/apps/api/src/modules/domains/routing-apply.service.test.ts @@ -132,7 +132,7 @@ describe("Cloud Docker route tables", () => { } as Record )[`${container}:${port}`]; if (!published) throw new Error("service port is not published"); - return { workspace: "shared-vm", port: published }; + return { vm: "shared-vm", port: published }; }); }); it("repairs an existing single static container route without rebuilding", async () => { @@ -149,7 +149,7 @@ describe("Cloud Docker route tables", () => { }; domainRepo.listByProject.mockResolvedValue([savedDomain]); domainRepo.findByHostname.mockResolvedValue(savedDomain); - target.mockResolvedValue({ workspace: "shared-vm", port: 30000 }); + target.mockResolvedValue({ vm: "shared-vm", port: 30000 }); await applyCloudRouting({ project: { ...base, workloadType: "static", hasServer: false, port: 3000 } as never, deployment: { @@ -186,9 +186,9 @@ describe("Cloud Docker route tables", () => { ["stack-api.opsh.io", 30003, false], ]); expect(publish.mock.calls.map((call) => call[3].routes[0].action)).toEqual([ - { kind: "proxy", workspace: "shared-vm", port: 30001 }, - { kind: "proxy", workspace: "shared-vm", port: 30002 }, - { kind: "proxy", workspace: "shared-vm", port: 30003 }, + { kind: "proxy", vm: "shared-vm", port: 30001 }, + { kind: "proxy", vm: "shared-vm", port: 30002 }, + { kind: "proxy", vm: "shared-vm", port: 30003 }, ]); }); it("resolves project-level domains to their service's exact published port", async () => { @@ -209,7 +209,7 @@ describe("Cloud Docker route tables", () => { expect.objectContaining({ routes: [ expect.objectContaining({ - action: { kind: "proxy", workspace: "shared-vm", port: 30002 }, + action: { kind: "proxy", vm: "shared-vm", port: 30002 }, }), ], }), @@ -235,15 +235,15 @@ describe("Cloud Docker route tables", () => { expect(writes[0]![3].routes).toEqual([ { match: { path: "/api/status", type: "exact" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "shared-vm", port: 30001 }, }, { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30003 }, + action: { kind: "proxy", vm: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "shared-vm", port: 30001 }, }, ]); }); @@ -259,7 +259,7 @@ describe("Cloud Docker route tables", () => { }], }); expect(publish).toHaveBeenCalledWith("api.onvo.me", undefined, true, { - routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }], + routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }], }); }); it("keeps the old composite table if any path target is missing, while updating other hosts", async () => { @@ -296,11 +296,11 @@ describe("Cloud Docker route tables", () => { expect(rules).toEqual([ { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30003 }, + action: { kind: "proxy", vm: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "shared-vm", port: 30001 }, }, ]); }); diff --git a/apps/api/src/modules/images/images.service.ts b/apps/api/src/modules/images/images.service.ts index b62749d95..6b24ab6c9 100644 --- a/apps/api/src/modules/images/images.service.ts +++ b/apps/api/src/modules/images/images.service.ts @@ -91,7 +91,7 @@ export async function listImages( if (hit) return hit; const client = await getClientForOrg(organizationId); - const response = await client.workspaces.images.list(params); + const response = await client.vms.images.list(params); const images = normalizeImages(response); await store.set(key, images, CACHE_TTL_S); return images; diff --git a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts index f66e072ba..ef4088610 100644 --- a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts +++ b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts @@ -225,7 +225,7 @@ describe("Cloud Docker project teardown", () => { slug, domain: "opsh.io", namespace: fixture.namespace, - source_workspace_id: fixture.scope.workspaceId, + source_vm_id: fixture.scope.workspaceId, exported_path: `${cloudDockerProjectPaths(owner).routes}/${slug}`, }); return { ...fixture, addPage }; diff --git a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts index e7c29259f..15bc3624e 100644 --- a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts +++ b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts @@ -152,13 +152,13 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => }; const vm = { id: providerVm, namespace, status: "running" }; const provider = { - workspaces: { + vms: { get: async () => vm, create: () => { throw new Error("Project operation attempted to create a second host"); }, }, - workspace: () => ({ + vm: () => ({ get: async () => vm, runtime: async () => providerRuntime, workloads: { list: async () => [] }, @@ -185,7 +185,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace, - source_workspace_id: input.workspace_id, + source_vm_id: input.vm_id, exported_path: input.path, }; pages.set(input.slug, page); @@ -359,7 +359,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => ); expect((await a.listAllContainers()).map((row) => row.id)).toEqual([aId]); expect(routes.get(`${ids[0]}.opsh.io`).routes[0].action).toMatchObject({ - workspace: providerVm, + vm: providerVm, port: first.hostPortByContainerPort?.[8080], }); }); diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts index e90c76343..a486e13c3 100644 --- a/apps/api/test/e2e/platform-import-project.e2e.test.ts +++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts @@ -227,7 +227,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ? await openRuntime() : await CloudDockerRuntime.forWorkspace( { - workspaces: { + vms: { get: async () => ({ id: serverId, namespace: owner.organizationId, diff --git a/apps/api/test/fixtures/oblien-capacity-catalog.json b/apps/api/test/fixtures/oblien-capacity-catalog.json index 1e937f0cf..78cf91b65 100644 --- a/apps/api/test/fixtures/oblien-capacity-catalog.json +++ b/apps/api/test/fixtures/oblien-capacity-catalog.json @@ -56,12 +56,12 @@ "vcpus": 0.5, "memoryMb": 512, "diskGb": 10, - "workspaces": 4 + "vms": 4 }, "monthlyAmount": 500, "paygCapAmount": 625, "resourceLimits": { - "max_workspaces": 4, + "max_vms": 4, "max_vcpus": 1, "max_ram_mb": 512, "max_disk_gb": 10, @@ -76,12 +76,12 @@ "vcpus": 1, "memoryMb": 1024, "diskGb": 20, - "workspaces": 8 + "vms": 8 }, "monthlyAmount": 800, "paygCapAmount": 1000, "resourceLimits": { - "max_workspaces": 8, + "max_vms": 8, "max_vcpus": 1, "max_ram_mb": 1024, "max_disk_gb": 20, @@ -96,12 +96,12 @@ "vcpus": 2, "memoryMb": 4096, "diskGb": 40, - "workspaces": 12 + "vms": 12 }, "monthlyAmount": 1800, "paygCapAmount": 2250, "resourceLimits": { - "max_workspaces": 12, + "max_vms": 12, "max_vcpus": 2, "max_ram_mb": 4096, "max_disk_gb": 40, @@ -116,12 +116,12 @@ "vcpus": 4, "memoryMb": 8192, "diskGb": 80, - "workspaces": 24 + "vms": 24 }, "monthlyAmount": 3600, "paygCapAmount": 4500, "resourceLimits": { - "max_workspaces": 24, + "max_vms": 24, "max_vcpus": 4, "max_ram_mb": 8192, "max_disk_gb": 80, diff --git a/apps/api/test/helpers/monthly-cloud-offer.ts b/apps/api/test/helpers/monthly-cloud-offer.ts index b95c4cb7c..e55e44596 100644 --- a/apps/api/test/helpers/monthly-cloud-offer.ts +++ b/apps/api/test/helpers/monthly-cloud-offer.ts @@ -1,6 +1,6 @@ import type { OblienEntitlement, OblienSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; -/** Saved v9 terms and the SDK 2.8 capacity shape, independent of today's catalog. */ +/** OpenShip saved v9 terms, independent of today's catalog and provider wire names. */ export function monthlyCloudBilling(organizationId = "org_1", namespace = "os-customer") { const periodStart = "2026-10-01T00:00:00Z"; const periodEnd = "2026-11-01T00:00:00Z"; diff --git a/apps/api/test/helpers/oblien-vm-billing.ts b/apps/api/test/helpers/oblien-vm-billing.ts new file mode 100644 index 000000000..9f8ea75f9 --- /dev/null +++ b/apps/api/test/helpers/oblien-vm-billing.ts @@ -0,0 +1,40 @@ +/** Build provider HTTP fixtures from OpenShip's saved billing model. This helper + * is only for fixture construction; production must read native SDK 3 payloads. + * Customer metadata and other opaque dictionaries are deliberately untouched. */ +export function providerBillingFixture(value: unknown): unknown { + if (!value || typeof value !== "object" || Array.isArray(value)) return value; + const source = value as Record; + const native = { ...source }; + if ("vcpus" in source && "memoryMb" in source && "diskGb" in source && "workspaces" in source) { + native.vms = source.workspaces; + delete native.workspaces; + } + if (source.resourceLimits && typeof source.resourceLimits === "object") { + const limits = { ...(source.resourceLimits as Record) }; + if ("max_workspaces" in limits) { + limits.max_vms = limits.max_workspaces; + delete limits.max_workspaces; + } + native.resourceLimits = limits; + } + if (source.onOverdraftAction === "stop_workspaces") native.onOverdraftAction = "stop_vms"; + if (source.service === "workspace_vm") native.service = "vm_compute"; + for (const key of [ + "data", + "capacity", + "quote", + "current", + "next", + "subscription", + "offer", + "policy", + "pendingChange", + "change", + "pendingCheckout", + "checkout", + ]) + if (source[key] && typeof source[key] === "object") + native[key] = providerBillingFixture(source[key]); + if (Array.isArray(source.presets)) native.presets = source.presets.map(providerBillingFixture); + return native; +} diff --git a/apps/api/test/lib/cloud-capacity.test.ts b/apps/api/test/lib/cloud-capacity.test.ts index 4be698883..621c3145c 100644 --- a/apps/api/test/lib/cloud-capacity.test.ts +++ b/apps/api/test/lib/cloud-capacity.test.ts @@ -20,7 +20,7 @@ vi.mock("@repo/db", () => ({ })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - workspaces: { get: h.workspace }, + vms: { get: h.workspace }, namespaces: { get: h.namespace }, }), })); diff --git a/apps/api/test/lib/cloud-docker-workspace.test.ts b/apps/api/test/lib/cloud-docker-workspace.test.ts index b2c2cf0cf..9e4d1f18b 100644 --- a/apps/api/test/lib/cloud-docker-workspace.test.ts +++ b/apps/api/test/lib/cloud-docker-workspace.test.ts @@ -30,8 +30,8 @@ vi.mock("@repo/adapters", async (original) => ({ ...await original(), Oblien: class { constructor(credentials: unknown) { h.credentials.push(credentials); } - workspaces = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; - workspace = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, + vms = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; + vm = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, lifecycle: { makePermanent: h.permanent }, resources: { update: h.resize }, runtime: async () => ({ exec: { run: h.exec } }), invalidateRuntime: h.invalidate }); }, @@ -86,7 +86,7 @@ beforeEach(() => { return { success: true, relaunched: true }; }); h.inFlight.mockResolvedValue([]); - h.list.mockResolvedValue({ workspaces: [], total: 0, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [], total: 0, limit: 100, page: 1 }); h.discard.mockImplementation(async () => { binding = undefined; }); @@ -190,7 +190,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { it("adopts an earlier workspace discovered after a quota refusal instead of creating another", async () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); - h.list.mockResolvedValue({ workspaces: [await h.get()], total: 1, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [await h.get()], total: 1, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toEqual({ projectId: project.id, workspaceId: "workspace-a", ownerWorkspaceId: "owner-a" }); expect(h.create).toHaveBeenCalledOnce(); expect(h.discard).not.toHaveBeenCalled(); @@ -209,8 +209,8 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValueOnce({ workspaces: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); - h.list.mockResolvedValueOnce({ workspaces: [workspace], total: 2, limit: 1, page: 2 }); + h.list.mockResolvedValueOnce({ vms: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); + h.list.mockResolvedValueOnce({ vms: [workspace], total: 2, limit: 1, page: 2 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toMatchObject({ workspaceId: "workspace-a" }); expect(h.list).toHaveBeenNthCalledWith(2, { page: 2, limit: 100 }); expect(h.attach).toHaveBeenCalledExactlyOnceWith(ownerRef, project.organizationId, "namespace-a", "workspace-a"); @@ -219,7 +219,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValue({ workspaces: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).rejects.toThrow("Multiple Cloud servers"); expect(h.attach).not.toHaveBeenCalled(); expect(h.discard).not.toHaveBeenCalled(); @@ -288,7 +288,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { const error = Object.assign(new Error("initial provisioning failed"), { status: 422, code: "CREATE_FAILED", - details: { workspace_id: "workspace-a" }, + details: { vm_id: "workspace-a" }, }); h.create.mockRejectedValueOnce(error); await expect(ensureCloudDockerWorkspace(input)).rejects.toBe(error); @@ -328,7 +328,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { h.create.mockRejectedValueOnce( Object.assign(new Error("creation failed"), { status: 422, - details: { workspace_id: "workspace-a" }, + details: { vm_id: "workspace-a" }, }), ); const created = await h.get(); diff --git a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts index c27c36e3b..f5623dd04 100644 --- a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts +++ b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts @@ -98,7 +98,7 @@ it("renews expiring credentials once across concurrent clients", async () => { ]); vi.setSystemTime(Date.now() + 1741_000); await Promise.all( - clients.map(({ client }) => client._http.request({ method: "GET", path: "/workspace" })), + clients.map(({ client }) => client._http.request({ method: "GET", path: "/vms" })), ); expect(h.mint).toHaveBeenCalledTimes(2); expect(fetcher.mock.calls).toHaveLength(2); @@ -111,12 +111,12 @@ it("evicts rejected credentials without replaying a mutation", async () => { .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - await expect(client._http.request({ method: "POST", path: "/workspace" })).rejects.toMatchObject({ + await expect(client._http.request({ method: "POST", path: "/vms" })).rejects.toMatchObject({ status: 401, }); expect(fetcher).toHaveBeenCalledTimes(1); const next = await getNamespaceClient("org", "space"); - await next.client._http.request({ method: "GET", path: "/workspace" }); + await next.client._http.request({ method: "GET", path: "/vms" }); expect(h.mint).toHaveBeenCalledTimes(2); expect(new Headers(fetcher.mock.calls[1]![1].headers).get("authorization")).toBe( "Bearer token-2", @@ -171,9 +171,9 @@ it("does not evict a renewed token when an older request returns a late 401", as .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - const old = client._http.request({ method: "POST", path: "/workspace" }).catch((error) => error); + const old = client._http.request({ method: "POST", path: "/vms" }).catch((error) => error); vi.setSystemTime(Date.now() + 1741_000); - await client._http.request({ method: "GET", path: "/workspace" }); + await client._http.request({ method: "GET", path: "/vms" }); rejectOld(Response.json({ code: "token_revoked" }, { status: 401 })); expect(await old).toMatchObject({ status: 401 }); await getNamespaceClient("org", "space"); diff --git a/apps/api/test/lib/cloud-preflight.test.ts b/apps/api/test/lib/cloud-preflight.test.ts index e419c3712..2051f666a 100644 --- a/apps/api/test/lib/cloud-preflight.test.ts +++ b/apps/api/test/lib/cloud-preflight.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ token: vi.fn(), routes: vi.fn(), checkSlug: vi.fn(), verify: vi.fn(), scopedVerify: vi.fn(), spend: vi.fn(), createPlatform: vi.fn(), quota: vi.fn() })); -vi.mock("@repo/adapters", () => ({ createPlatform: h.createPlatform })); +vi.mock("@repo/adapters", async original => ({ ...await original(), createPlatform: h.createPlatform })); vi.mock("@repo/platform/engine/config/env", () => ({ env: { OBLIEN_API_URL: "https://api.oblien.com" } })); vi.mock("@repo/platform/engine/lib/routing-domains", () => ({ getRoutingBaseDomain: () => "opsh.io" })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ diff --git a/apps/api/test/lib/cloud-resource-limits.test.ts b/apps/api/test/lib/cloud-resource-limits.test.ts index a25adc3c9..69433a654 100644 --- a/apps/api/test/lib/cloud-resource-limits.test.ts +++ b/apps/api/test/lib/cloud-resource-limits.test.ts @@ -2,8 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ quota: vi.fn(), get: vi.fn(), update: vi.fn() })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ - getOblienClient: () => ({ workspaces: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), + getOblienClient: () => ({ vms: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), })); +import { toOblienVmLimits } from "@repo/adapters"; import { cloudNamespaceLimits, initialCloudNamespaceLimits, readCloudCapacity, readCloudCapacityPool, syncCloudResourceLimits } from "@repo/platform/engine/lib/cloud-resource-limits"; beforeEach(() => { @@ -11,15 +12,15 @@ beforeEach(() => { h.quota.mockImplementation(() => { throw new Error("Openship must not calculate provider capacity"); }); h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: null } }); h.update.mockImplementation(async (_id, input) => ({ data: { id: "ns-a", slug: "tenant-a", ...input, - effective_resource_limits: { max_workspaces: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, + effective_resource_limits: { max_vms: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, } })); }); describe("Oblien-owned namespace capacity", () => { it("displays provider allocations in their real units without using credit balances or owner limits", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: cloudNamespaceLimits("pro"), - allocated_resource_usage: { workspaces: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, + effective_resource_limits: toOblienVmLimits(cloudNamespaceLimits("pro")), + allocated_resource_usage: { vms: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, } }); expect(await readCloudCapacity("tenant-a")).toEqual({ workspaces: { used: 3, max: 1 }, vcpus: { used: 2.5, max: 4 }, ramMb: { used: 4096, max: 16384 }, diskGb: { used: 48.5, max: 250 } }); @@ -36,8 +37,8 @@ describe("Oblien-owned namespace capacity", () => { }); it("converts disk to MB for admission without confusing zero and unlimited", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: { max_workspaces: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, - allocated_resource_usage: { workspaces: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, + effective_resource_limits: { max_vms: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, + allocated_resource_usage: { vms: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, } }); expect(await readCloudCapacityPool("tenant-a")).toEqual({ workspaces: { used: 0, max: null }, cpuCores: { used: 0, max: 0 }, memoryMb: { used: 0, max: 8192 }, diskMb: { used: 1280, max: 16384 } }); @@ -50,37 +51,37 @@ describe("Oblien-owned namespace capacity", () => { }); it("declares finite retail VM and aggregate caps without reading enterprise owner capacity", async () => { expect(cloudNamespaceLimits("team")).toEqual({ max_workspaces: 1, max_vcpus: 8, max_ram_mb: 32768, max_disk_gb: 600, max_total_vcpus: 8, max_total_ram_mb: 32768, max_total_disk_gb: 600 }); - await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_workspaces: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); + await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_vms: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); await syncCloudResourceLimits("tenant-a", "team"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: cloudNamespaceLimits("team") }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(cloudNamespaceLimits("team")) }); expect(h.quota).not.toHaveBeenCalled(); }); - it("sends an older saved offer unchanged and accepts Oblien's lower effective ceiling", async () => { + it("preserves an older saved offer when sending VM limits and accepts Oblien's lower effective ceiling", async () => { const saved = Object.freeze({ max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); expect(saved.max_vcpus).toBe(200); expect(h.quota).not.toHaveBeenCalled(); }); it("preserves explicit customer restrictions even when the owner's capacity is unlimited", async () => { const saved = Object.freeze({ max_workspaces: 7, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 12, max_total_vcpus: 3, max_total_ram_mb: 6144, max_total_disk_gb: 24 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); expect(h.quota).not.toHaveBeenCalled(); }); it("does not rewrite declared policy when effective capacity differs", async () => { const declared = { max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }; - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: declared, - effective_resource_limits: { ...declared, max_vcpus: 32, max_ram_mb: 65536 }, + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: toOblienVmLimits(declared), + effective_resource_limits: { ...toOblienVmLimits(declared), max_vcpus: 32, max_ram_mb: 65536 }, } }); await syncCloudResourceLimits("tenant-a", "team", declared); expect(h.update).not.toHaveBeenCalled(); expect(h.quota).not.toHaveBeenCalled(); }); it("clears old declared caps only after a verified enterprise entitlement", async () => { - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_workspaces: 5 } } }); + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_vms: 5 } } }); await syncCloudResourceLimits("tenant-a", "enterprise"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_workspaces: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_vms: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); }); it("cannot change policy when the provider returns another namespace", async () => { h.get.mockResolvedValue({ data: { id: "ns-b", slug: "tenant-b" } }); diff --git a/apps/api/test/lib/cloud-resource-proxy.test.ts b/apps/api/test/lib/cloud-resource-proxy.test.ts index f41b50777..0c6168e0a 100644 --- a/apps/api/test/lib/cloud-resource-proxy.test.ts +++ b/apps/api/test/lib/cloud-resource-proxy.test.ts @@ -12,7 +12,7 @@ vi.mock("../../src/lib/request-context", () => ({ getRequestContext: () => ({ or vi.mock("../../src/modules/cloud/cloud-relay-access", () => ({ authorizeCloudRelayWorkspace: async () => null })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ ensureNamespace: async () => "ns-a" })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - workspaces: { get: h.workspaceGet }, + vms: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, deploy: h.pageDeploy, delete: h.pageDelete }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -46,18 +46,18 @@ describe("desktop-to-SaaS Cloud resource delegation", () => { it("round-trips page reads and redeploys through the SaaS ownership checks", async () => { const proxy = createRemoteCloudAdmin("org-a"); expect(await proxy.pages!.get("site-a")).toMatchObject({ page: { namespace: "ns-a" } }); - await proxy.pages!.deploy("site-a", { workspace_id: "ws-a", path: "/app/dist" }); - expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { workspace_id: "ws-a", path: "/app/dist" }); + await proxy.pages!.deploy("site-a", { vm_id: "ws-a", path: "/app/dist" }); + expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { vm_id: "ws-a", path: "/app/dist" }); expect(h.spend).toHaveBeenCalledWith("org-a", null); }); it("ignores the client's namespace and pins a create to its server identity", async () => { - await createRemoteCloudAdmin("org-a").pages!.create({ workspace_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); + await createRemoteCloudAdmin("org-a").pages!.create({ vm_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-a" })); }); it("refuses both foreign page reads and foreign source exports", async () => { const pages = createRemoteCloudAdmin("org-a").pages!; await expect(pages.get("site-b")).rejects.toMatchObject({ status: 404 }); - await expect(pages.create({ workspace_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); + await expect(pages.create({ vm_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("preserves provider 404 so the runtime can create a missing page", async () => { diff --git a/apps/api/test/lib/cloud-tenant-admin.test.ts b/apps/api/test/lib/cloud-tenant-admin.test.ts index fe6313b97..b6e113560 100644 --- a/apps/api/test/lib/cloud-tenant-admin.test.ts +++ b/apps/api/test/lib/cloud-tenant-admin.test.ts @@ -5,7 +5,7 @@ const h = vi.hoisted(() => ({ workspaceGet: vi.fn(), routes: vi.fn(), setRoutes: vi.fn(), spend: vi.fn(), pageList: vi.fn(), })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - workspaces: { get: h.workspaceGet }, + vms: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, delete: h.pageDelete, disable: h.pageDisable, deploy: h.pageDeploy }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -32,12 +32,12 @@ describe("admin-only cloud delegation", () => { }); it("rejects another customer's workspace before exporting a page", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await expect(proxy.pages!.create({ workspace_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(proxy.pages!.create({ vm_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("pins page creation to the authenticated namespace", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await proxy.pages!.create({ workspace_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); + await proxy.pages!.create({ vm_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-own" })); expect(h.spend).toHaveBeenCalledWith("org-one", undefined); }); @@ -45,7 +45,7 @@ describe("admin-only cloud delegation", () => { const pages = createTenantCloudAdmin("org-one", "ns-own").pages!; await expect(pages.get("other-page")).rejects.toMatchObject({ statusCode: 404 }); await expect(pages.delete("other-page")).rejects.toMatchObject({ statusCode: 404 }); - await expect(pages.deploy("other-page", { workspace_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(pages.deploy("other-page", { vm_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageDelete).not.toHaveBeenCalled(); expect(h.pageDeploy).not.toHaveBeenCalled(); }); @@ -59,11 +59,11 @@ describe("admin-only cloud delegation", () => { }); it("validates both hostname and every route target before an admin mutation", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, workspace: "ws-other", port: 8080 } }]; + const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, vm: "ws-other", port: 8080 } }]; await expect(proxy.setRoutes!("own.opsh.io", { routes })).rejects.toMatchObject({ statusCode: 404 }); await expect(proxy.setRoutes!("other.opsh.io", { routes: [] })).rejects.toMatchObject({ statusCode: 404 }); expect(h.setRoutes).not.toHaveBeenCalled(); - await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", workspace: "ws-own", port: 8080 } }] }); + await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", vm: "ws-own", port: 8080 } }] }); expect(h.setRoutes).toHaveBeenCalledOnce(); }); it("does not use reseller authority for unverified external proxy origins", async () => { diff --git a/apps/api/test/modules/actions/billing-webhook.test.ts b/apps/api/test/modules/actions/billing-webhook.test.ts index 8e547c7b2..1eb01e4dc 100644 --- a/apps/api/test/modules/actions/billing-webhook.test.ts +++ b/apps/api/test/modules/actions/billing-webhook.test.ts @@ -450,7 +450,7 @@ describe("Actions namespace preparation before checkout", () => { name: "Openship Actions", slug: f.namespace, resource_limits: { - max_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, diff --git a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts index f92314c2a..383127280 100644 --- a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts +++ b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts @@ -105,7 +105,7 @@ beforeEach(async () => { } const method = init?.method ?? "GET"; requests.push(`${method} ${url.pathname}`); - if (url.pathname === "/workspace" && method === "POST") { + if (url.pathname === "/vms" && method === "POST") { if (createMode === "quota" || createMode === "legacy-quota") { return Response.json( { success: false, code: "NAMESPACE_LIMIT_REACHED" }, @@ -133,27 +133,27 @@ beforeEach(async () => { return Response.json( { code: "CREATE_FAILED", - details: { workspace_id: workspace.id }, + details: { vm_id: workspace.id }, }, { status: 422 }, ); } - if (url.pathname === "/workspace" && method === "GET") { + if (url.pathname === "/vms" && method === "GET") { return Response.json({ success: true, - workspaces: [...workspaces.values()], + vms: [...workspaces.values()], total: workspaces.size, limit: 100, page: 1, }); } - const workspaceId = url.pathname.match(/^\/workspace\/([^/]+)$/)?.[1]; - const retryId = url.pathname.match(/^\/workspace\/([^/]+)\/provisioning\/retry$/)?.[1]; + const workspaceId = url.pathname.match(/^\/vms\/([^/]+)$/)?.[1]; + const retryId = url.pathname.match(/^\/vms\/([^/]+)\/provisioning\/retry$/)?.[1]; if (retryId && method === "POST") { const workspace = workspaces.get(retryId)!; workspace.status = "running"; workspace.provisioning.state = "ready"; - return Response.json({ success: true, workspace }); + return Response.json({ success: true, vm: workspace }); } if (url.pathname.endsWith("/lifecycle/permanent") && method === "POST") return Response.json({ success: true }); @@ -162,7 +162,7 @@ beforeEach(async () => { if (deleting.has(workspaceId)) workspaces.delete(workspaceId); const workspace = workspaces.get(workspaceId); return workspace - ? Response.json({ success: true, workspace }) + ? Response.json({ success: true, vm: workspace }) : Response.json({ code: "NOT_FOUND" }, { status: 404 }); } if (workspaceId && method === "DELETE") { diff --git a/apps/api/test/modules/billing/billing-sdk-parity.test.ts b/apps/api/test/modules/billing/billing-sdk-parity.test.ts index 4dea70ffd..e7de42cd1 100644 --- a/apps/api/test/modules/billing/billing-sdk-parity.test.ts +++ b/apps/api/test/modules/billing/billing-sdk-parity.test.ts @@ -1,4 +1,5 @@ import { savedOffer as subscriptionOffer, savedMetadata as subscriptionMetadata } from "../../helpers/saved-cloud-offer"; +import { providerBillingFixture } from "../../helpers/oblien-vm-billing"; import capacityCatalog from "../../fixtures/oblien-capacity-catalog.json"; import { monthlyCloudBilling } from "../../helpers/monthly-cloud-offer"; import managedTransfer from "../../fixtures/oblien-managed-transfer.json"; @@ -60,7 +61,7 @@ vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ }), }), getOblienClient: () => ({ - workspaces: { getQuota: provider.quota, get: provider.workspace }, + vms: { getQuota: provider.quota, get: provider.workspace }, namespaces: { ensure: provider.namespaces, get: provider.resourceRead, @@ -192,8 +193,8 @@ describe("billing through the same SDK and HTTP application operations", () => { // Exercise the actual SDK/validator before the shared application operation; // a mock entitlement alone missed the provider's newly included transfer. const billing = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", - fetch: (async url => Response.json(new URL(String(url)).pathname === "/billing/balance" - ? monthly.balance : monthly.entitlement)) as typeof fetch }); + fetch: (async url => Response.json(providerBillingFixture(new URL(String(url)).pathname === "/v1/billing/balance" + ? monthly.balance : monthly.entitlement))) as typeof fetch }); provider.subscriptions.set(selected.namespace!, monthly.subscription); provider.entitlement.mockImplementation(async namespace => namespace === selected.namespace ? billing.getEntitlement(namespace) : { success: true, namespace, tierId: null, status: "credit_exhausted", @@ -267,13 +268,13 @@ describe("billing through the same SDK and HTTP application operations", () => { data: { slug, effective_resource_limits: { - max_workspaces: 12, + max_vms: 12, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256, }, allocated_resource_usage: { - workspaces: 0, + vms: 0, vcpus: 0, ram_mb: 0, disk_gb: 0, diff --git a/apps/api/test/modules/cloud-execution-access.test.ts b/apps/api/test/modules/cloud-execution-access.test.ts index 3402dfe1e..973417ce7 100644 --- a/apps/api/test/modules/cloud-execution-access.test.ts +++ b/apps/api/test/modules/cloud-execution-access.test.ts @@ -211,7 +211,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr it.each([ ["preflight", {}], - ["pages", { workspace_id: "vm-own", path: "/private", name: "export", slug: "export" }], + ["pages", { vm_id: "vm-own", path: "/private", name: "export", slug: "export" }], ["pages/enable", { slug: "own-page" }], ["pages/disable", { slug: "own-page" }], ["pages/delete", { slug: "own-page" }], diff --git a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts index 44dfb01c6..34e133682 100644 --- a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts +++ b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts @@ -218,7 +218,7 @@ beforeEach(async () => { expiresAt: "2030-01-01T00:00:00Z", })), }, - workspaces: { + vms: { create: vi.fn(async (input: any) => { const existing = [...vms.values()].find((vm) => vm.slug === input.slug); if (existing) return existing; @@ -242,7 +242,7 @@ beforeEach(async () => { return vm; }), list: vi.fn(async () => ({ - workspaces: [...vms.values()], + vms: [...vms.values()], total: vms.size, page: 1, limit: 100, @@ -260,9 +260,9 @@ beforeEach(async () => { vms.delete(id); return { success: true }; }), - workspace: (id: string) => ({ + vm: (id: string) => ({ id, - get: () => h.client.workspaces.get(id), + get: () => h.client.vms.get(id), lifecycle: { makePermanent: async () => {} }, resources: { update: (input: any) => h.client.resize(id, input) }, delete: () => h.client.delete(id), @@ -433,7 +433,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`, undefined, stranger)).status).toBe( 404, ); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); const invalid = await request("POST", "", { name: "Broken", mode: "shared", @@ -468,7 +468,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }); expect(observed.isError).toBe(false); expect(JSON.parse(observed.content[0].text).managed.operation.status).toBe("succeeded"); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.create).toHaveBeenCalledTimes(1); const outsider = await seedOwner(); expect( @@ -492,7 +492,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }) ).isError, ).toBe(true); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.create).toHaveBeenCalledTimes(1); }); it("provisions on paid reconciliation and reuses one host across simultaneous project deployments", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); @@ -512,7 +512,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(targets[0]?.workspaceId).toBe(targets[1]?.workspaceId); expect(targets.map((target) => target.ownerWorkspaceId)).toEqual([workspace.id, workspace.id]); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.create).toHaveBeenCalledTimes(1); expect(h.client.resize).not.toHaveBeenCalled(); expect(vms.get(targets[0]!.workspaceId).resources).toMatchObject({ cpus: 1, @@ -544,7 +544,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( resolveSnapshotTarget(saved, { serverId: otherServer.id, deployTarget: "server" }), ).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_TARGET_CONFLICT" }); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("places bare and Docker projects on managed servers without provisioning a second host", async () => { const sdk = await nativeShip(); @@ -557,7 +557,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const docker = await sdk.projects.create({ name: "Docker app", serverId: selected.serverId }); for (const project of [bare, docker]) expect(await repos.project.findById(project.id)).toMatchObject({ serverId: selected.serverId, workspaceId: selected.id }); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("installs and previews catalog apps on the selected managed server without creating a project VM", async () => { subscribe("starter"); @@ -583,7 +583,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( stranger.apps.install({ templateId: "redis", serverId: server.id }), ).rejects.toMatchObject({ statusCode: 404 }); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("carries one managed server through source staging, scan and project creation", async () => { const sdk = await nativeShip(); @@ -614,15 +614,15 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(stranger.sources.scan(staged.sessionId)).rejects.toMatchObject({ statusCode: 404, }); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); } finally { const session = deleteFolderSession(staged.sessionId); if (session?.stagingDir) await rm(session.stagingDir, { recursive: true, force: true }); } }); it("recovers a lost provider create response with the same request and disk", async () => { - const create = h.client.workspaces.create.getMockImplementation()!; - h.client.workspaces.create.mockImplementationOnce(async (input: any) => { + const create = h.client.vms.create.getMockImplementation()!; + h.client.vms.create.mockImplementationOnce(async (input: any) => { await create(input); throw new Error("create response lost"); }); @@ -642,7 +642,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(vms.size).toBe(1); expect( - new Set(h.client.workspaces.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) + new Set(h.client.vms.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) .size, ).toBe(1); expect( @@ -651,7 +651,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ).toBe([...vms.keys()][0]); }); it("stops after three provisioning failures and durably escalates once without retrying the host", async () => { - h.client.workspaces.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); + h.client.vms.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); expect((await request("POST", `/${workspace.id}/ensure`)).status).toBe(202); await drainBackgroundWork(); const createTicket = vi.spyOn(repos.cloudSupport, "create").mockRejectedValueOnce(new Error("support database temporarily unavailable")); @@ -673,7 +673,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect(await repos.cloudSupport.find(ticketId)).toMatchObject({ status: "open", ownerUserId: owner.userId }); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); await processWorkspaceOperation(workspace.id); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(3); + expect(h.client.vms.create).toHaveBeenCalledTimes(3); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); expect((await repos.cloudWorkspace.listPendingOperations()).map(row => row.id)).not.toContain(workspace.id); createTicket.mockRestore(); @@ -707,7 +707,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }, }); expect((await deliver("bad-signature")).status).toBe(401); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); expect(await db.select().from(schema.cloudCustomerEmail).where(eq(schema.cloudCustomerEmail.organizationId, owner.orgId))).toEqual([]); h.billing.getCheckout.mockImplementation(async () => ({ checkout: { @@ -731,7 +731,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { .map(mail => mail.kind).sort()).toEqual(["invoice", "purchase"]); expect(result[2]).toMatchObject({ fulfilled: true, creditsGranted: 0 }); await drainBackgroundWork(); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.create).toHaveBeenCalledTimes(1); expect((await repos.cloudWorkspace.findById(workspace.id))?.operation?.status).toBe( "succeeded", ); @@ -764,7 +764,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(client.resize(server.id, { revision: "a".repeat(64), confirmRestart: true, idempotencyKey: randomUUID() })) .rejects.toMatchObject({ code: "TOKEN_READ_ONLY" }); } - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("recovers one draft and its server across concurrent native/HTTP creates and scopes retries by organization", async () => { @@ -779,7 +779,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const stranger = await seedOwner(); const other = await (await clients(stranger))[0]!.createManaged(input); expect(other.id).not.toBe(created[0]!.id); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("never recreates a deleted purchase identity or its old provider namespace", async () => { @@ -791,14 +791,14 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(native!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); await expect(remote!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); expect(await repos.cloudWorkspace.findById(created.id)).toBeUndefined(); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("does not provision, stop or change the entitlement mirror when provider billing is unavailable", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); h.billing.getEntitlement.mockRejectedValue(new Error("Billing temporarily unavailable")); const response = await request("POST", `/${workspace.id}/ensure`); expect(response.status).toBe(500); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); expect(h.client.delete).not.toHaveBeenCalled(); expect((await repos.cloudWorkspace.findById(workspace.id))?.subscriptionStatus).toBe("active"); }); @@ -917,7 +917,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`)).body.code).toBe( "CLOUD_SERVER_LINK_REQUIRED", ); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); }); @@ -1757,7 +1757,7 @@ describe("managed server free-domain scope", () => { expect((await repos.domain.listByProject(id)).map(domain => domain.hostname)).toContain(`routed-${entry}.opsh.io`); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("uses the selected metered server's entitlement and allowance", async () => { subscribe("starter"); @@ -1780,7 +1780,7 @@ describe("managed server free-domain scope", () => { expect((await repos.service.listByProject(project.id))[0]?.domain).toBe("metered-service"); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it.each(["ensure", "update"] as const)("refuses excess free domains before %s changes an existing project's fields", async entry => { const sdk = await nativeShip(); @@ -1823,7 +1823,7 @@ describe("managed server free-domain scope", () => { envVars: {}, })).rejects.toMatchObject({ code: "PLAN_UPGRADE_REQUIRED", reason: "free-subdomain-limit" }); expect((await repos.deployment.listByProject(project.id)).rows).toEqual([]); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("does not count dormant routes outside an exclusive service deployment", async () => { const project = await addProject("Exclusive routes"); @@ -1839,7 +1839,7 @@ describe("managed server free-domain scope", () => { envVars: {}, serviceIds: [selected.id], strictServiceScope: true, }); expect(queued).toMatchObject({ status: "queued" }); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("keeps existing free routes editable when the server's allowance is full", async () => { const sdk = await nativeShip(); @@ -1875,7 +1875,7 @@ describe("managed server free-domain scope", () => { expect(await repos.service.findById(service.id)).toMatchObject({ domain: "routed-console-updated" }); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); it("does not use a paid sibling's allowance or write a project for an unauthorized server", async () => { const sdk = await nativeShip(); @@ -1890,6 +1890,6 @@ describe("managed server free-domain scope", () => { await expect(sdk.projects.create({ ...input, serverId: foreignServer.id })).rejects.toMatchObject({ statusCode: 404 }); expect((await repos.projectGroup.listByOrganization(owner.orgId, { page: 1, perPage: 1 })).total).toBe(0); expect(h.billing.getEntitlement).not.toHaveBeenCalled(); - expect(h.client.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts index 7ef67833d..83322bdd5 100644 --- a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts +++ b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts @@ -250,7 +250,7 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain const configurations: Array> = []; const publishRoute = vi.fn(async () => undefined); const pullImage = vi.fn(async () => undefined); - const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ workspace: "shared-vm", + const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ vm: "shared-vm", port: id === "web-container" ? (port === 8080 ? 30001 : 30002) : 30003 })); const runtime = Object.assign(Object.create(CloudDockerRuntime.prototype), { name: "docker", workspaceId: "shared-vm", projectId: "p1", unsupportedComposeKeys: new Set(), @@ -314,8 +314,8 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain serviceId: "svc-api", allocatedResources: { containerId: "api-container", cpuCores: 2, memoryMb: 2048 }, })); expect(publishRoute).toHaveBeenCalledWith("app.opsh.io", 30001, false, expect.objectContaining({ routes: [ - { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30001 } }, + { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30001 } }, ] })); }); diff --git a/apps/api/test/modules/projects/cloud-routing-regression.test.ts b/apps/api/test/modules/projects/cloud-routing-regression.test.ts index a08e2a3ed..a047ea544 100644 --- a/apps/api/test/modules/projects/cloud-routing-regression.test.ts +++ b/apps/api/test/modules/projects/cloud-routing-regression.test.ts @@ -113,7 +113,7 @@ describe("managed Cloud route port edits and repair", () => { await editRoutes(["app.opsh.io"]); expect(h.fixture.pages.create).toHaveBeenCalledOnce(); expect(h.fixture.routes.set).toHaveBeenLastCalledWith("app.opsh.io", expect.objectContaining({ - routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 } }], })); expect(h.syncManagedEdge).not.toHaveBeenCalled(); }); @@ -124,7 +124,7 @@ describe("managed Cloud route port edits and repair", () => { expect(h.fixture.pages.connectDomain).toHaveBeenCalledWith(expect.any(String), { domain: "app.example.com" }); expect(h.fixture.workspace.network.update).toHaveBeenCalledWith(expect.objectContaining({ ingress_ports: [443, 32000] })); expect(h.fixture.routes.set).toHaveBeenCalledWith("app.example.com", expect.objectContaining({ - routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 } })]), + routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 } })]), })); }); @@ -165,8 +165,8 @@ describe("managed Cloud route port edits and repair", () => { h.domains.push({ ...h.domains[0]!, id: "domain-b", hostname: "console.opsh.io", targetPort: 9000, isPrimary: false }); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], - ["console.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 }], + ["app.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["console.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 }], ]); }); @@ -196,8 +196,8 @@ describe("managed Cloud route port edits and repair", () => { })); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], - ["alias.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["app.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["alias.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], ]); expect(h.fixture.pages.delete).not.toHaveBeenCalled(); }); diff --git a/apps/api/test/modules/system/server-managed-controls.test.ts b/apps/api/test/modules/system/server-managed-controls.test.ts index aeea020f2..6eaeeffb6 100644 --- a/apps/api/test/modules/system/server-managed-controls.test.ts +++ b/apps/api/test/modules/system/server-managed-controls.test.ts @@ -261,8 +261,8 @@ beforeEach(async () => { { ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: "AU" }, ]), - workspaces: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, - workspace: vi.fn(() => handle), + vms: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, + vm: vi.fn(() => handle), }; h.namespaceClient.mockImplementation(async () => ({ client: h.client, namespace })); h.canWork.mockResolvedValue(undefined); @@ -414,7 +414,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); handle.apiAccess.getToken.mockResolvedValue({ token: jwt("another-vm") }); expect( (await request("managed/runtime-api/credential", "POST", { confirm: true })).status, @@ -482,7 +482,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); const recovered = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(recovered.status).toBe(200); expect(recovered.body.revision).not.toBe(input.expectedRevision); diff --git a/bun.lock b/bun.lock index 38011b2f5..abd3f92cd 100644 --- a/bun.lock +++ b/bun.lock @@ -221,7 +221,7 @@ "ignore": "^7.0.5", "ioredis": "^5.10.0", "ipaddr.js": "^2.4.0", - "oblien": "2.10.0", + "oblien": "3.0.2", "ssh2": "^1.17.0", "tar-fs": "^2.1.4", "undici": "^7.30.2", @@ -2732,7 +2732,7 @@ "object.assign": ["object.assign@4.1.7", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="], - "oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "oblien": ["oblien@3.0.2", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-f2hP0e9ujrL/H7eCP7mwAlnpmVa7OSDEgQGFEjwEXaSZUYJlBUwcZx+MPsTU3RNjlRj1tVpCRSa9PT3qi8zkNA=="], "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], @@ -3892,6 +3892,8 @@ "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "minipass-collect/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], "minipass-fetch/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], @@ -4216,6 +4218,8 @@ "bytesmap/better-auth/jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="], + "bytesmap/mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "cacache/glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], "cacache/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], diff --git a/docs/openship-cloud-launch.md b/docs/openship-cloud-launch.md index 033bf2aa8..cc7f378c6 100644 --- a/docs/openship-cloud-launch.md +++ b/docs/openship-cloud-launch.md @@ -582,7 +582,6 @@ assuming the `.env.saas` filename indicates production provider credentials. ```dotenv CLOUD_MODE=true OPENSHIP_TARGET=cloud-saas - OBLIEN_API_URL=https://api.oblien.com OBLIEN_CLIENT_ID= OBLIEN_CLIENT_SECRET= OBLIEN_WEBHOOK_SECRET= @@ -805,3 +804,17 @@ and database migration `0153_durable_credit_alerts` before rolling out the API a [Namespace credit alerts](namespace-credit-alerts.md) is the reference for delivery guarantees, provider requirements, organization isolation, and verification. + +## Oblien SDK 3 and versioned API activation + +Cloud uses the native VM contract from Oblien SDK 3.0.2. The SDK owns its default +control-plane base URL and API version; leave `OBLIEN_API_URL` unset. If an +operator needs a proxy, the override must be the complete API mount including +its version. Remove a previously configured unversioned provider origin during +the coordinated cutover. + +Activate the matching Oblien `/v1` API and migrated database before deploying +this integration. Older SDK routes are not probed and failed writes are not +replayed. OpenShip's organization/workspace records, managed-server IDs, paid +offer snapshots and customer metadata retain their existing identities. The +provider boundary maps those saved workspace counts to native VM capacity. diff --git a/packages/adapters/package.json b/packages/adapters/package.json index 858f55356..4077f40fe 100644 --- a/packages/adapters/package.json +++ b/packages/adapters/package.json @@ -46,7 +46,7 @@ "ignore": "^7.0.5", "ioredis": "^5.10.0", "ipaddr.js": "^2.4.0", - "oblien": "2.10.0", + "oblien": "3.0.2", "ssh2": "^1.17.0", "tar-fs": "^2.1.4", "undici": "^7.30.2", diff --git a/packages/adapters/scripts/verify-cloud-docker.ts b/packages/adapters/scripts/verify-cloud-docker.ts index 04b06e02d..0a78c00de 100644 --- a/packages/adapters/scripts/verify-cloud-docker.ts +++ b/packages/adapters/scripts/verify-cloud-docker.ts @@ -10,6 +10,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { Oblien } from "../src/oblien"; +import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract"; import { CloudDockerRuntime } from "../src/runtime/cloud/docker"; import { CloudProcessSupervisor } from "../src/runtime/cloud/process-supervisor"; import { cloudDockerProjectPaths } from "../src/runtime/cloud/docker-paths"; @@ -33,7 +34,7 @@ const domainFlag = process.argv.indexOf("--public-domain"); const publicDomain = domainFlag >= 0 ? process.argv[domainFlag + 1]! : "opsh.io"; if (!publicDomain || !/^[a-z0-9.-]+$/.test(publicDomain)) throw new Error("Invalid public test domain"); -const baseUrl = configuration.OBLIEN_API_URL || "https://api.oblien.com"; +const baseUrl = oblienApiBaseUrl(configuration.OBLIEN_API_URL).toString(); const presetFlag = process.argv.indexOf("--preset"); const softwarePreset = presetFlag >= 0 ? process.argv[presetFlag + 1] : undefined; if (presetFlag >= 0 && (!softwarePreset || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(softwarePreset))) @@ -93,7 +94,7 @@ try { name: tag, slug: tag, type: "testing", - resource_limits: { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }, + resource_limits: { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }, }); namespaceId = created.data.id; await save(); @@ -103,7 +104,7 @@ try { quotaLimit: 100, overdraft: 0, suspendThreshold: 0, - onOverdraftAction: "stop_workspaces", + onOverdraftAction: "stop_vms", }); const token = await admin.tokens.create({ scope: "namespace", namespace: tag, ttl: 1800 }); const client = new Oblien({ token: token.token, baseUrl }); @@ -127,11 +128,11 @@ try { network_config: { allow_internet: true, public_ingress: false }, }, }; - const workspace = await client.workspaces.create(createOptions); + const workspace = await client.vms.create(createOptions); workspaceId = workspace.id; await save(); check("workspace created in test namespace", workspace.namespace === tag && workspaceId); - const replay = await client.workspaces.create(createOptions); + const replay = await client.vms.create(createOptions); check("provider idempotency reuses workspace", replay.id === workspaceId); const progress = setInterval(() => log("waiting for Docker workspace"), 20_000); try { @@ -140,10 +141,10 @@ try { clearInterval(progress); } log("Docker workspace ready"); - await client.workspace(workspaceId).lifecycle.makePermanent(); + await client.vm(workspaceId).lifecycle.makePermanent(); check( "managed server can be made permanent", - (await client.workspaces.get(workspaceId)).mode === "permanent", + (await client.vms.get(workspaceId)).mode === "permanent", ); await client .workspace(workspaceId) @@ -170,7 +171,7 @@ try { return { ...result, pages: result.pages.filter((page) => page.namespace === tag) }; }; adminPages.create = async (input) => { - if (input.workspace_id !== workspaceId || !input.slug?.startsWith(tag)) + if (input.vm_id !== workspaceId || !input.slug?.startsWith(tag)) throw new Error("Smoke route escaped its workspace"); pages.add(input.slug); await save(); @@ -473,7 +474,7 @@ try { await runtime.stop(second.containerId); check( "service stop preserves workspace and sibling", - isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)) && + isDockerWorkspaceRunning(await client.vms.get(workspaceId)) && (await runtime.getContainerInfo(internal.containerId)).status === "running", ); const stoppedPorts = second.hostPortByContainerPort; @@ -536,7 +537,7 @@ try { env: { OPENSHIP_SMOKE_PROCESS: "saved" }, }; await processSupervisor.deploy(processOptions); - const workload = () => client.workspace(workspaceId!).workloads.get(`openship-${processId}`); + const workload = () => client.vm(workspaceId!).workloads.get(`openship-${processId}`); const savedProcess = await workload(); check( "provider returns saved process configuration", @@ -565,10 +566,10 @@ try { ); await processSupervisor.stop(processId); - check("provider accepts server stop", (await client.workspace(workspaceId).stop()).success); + check("provider accepts server stop", (await client.vm(workspaceId).stop()).success); await waitForCloudWorkspaceStopped(client, workspaceId, tag); log("workspace stopped for recovery check", { - status: (await client.workspaces.get(workspaceId)).status, + status: (await client.vms.get(workspaceId)).status, }); check( "stopped workspace reads do not start compute", @@ -590,7 +591,7 @@ try { "bare deletion retains the Docker application and server", (await processSupervisor.getInfo(processId)).status === "missing" && (await runtime.getContainerInfo(second.containerId)).status === "running" && - isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)), + isDockerWorkspaceRunning(await client.vms.get(workspaceId)), ); check( "workspace restart preserves the volume", @@ -599,7 +600,7 @@ try { ); check( "bridge recovery reuses its workload", - (await client.workspace(workspaceId).workloads.list({ name: "openship-docker-api-v1" })) + (await client.vm(workspaceId).workloads.list({ name: "openship-docker-api-v1" })) .length === 1, ); const hostnames = await infra.listProjectRouteHostnames(); @@ -630,11 +631,11 @@ try { } check( "one workspace for the whole stack", - (await client.workspaces.list()).workspaces.length === 1, + (await client.vms.list()).vms.length === 1, ); } catch (error) { if (workspaceId) { - const workspace = await admin.workspaces.get(workspaceId).catch(() => null); + const workspace = await admin.vms.get(workspaceId).catch(() => null); if (workspace) { const provisioning = workspace.provisioning as | { state?: string; error?: unknown } @@ -662,7 +663,7 @@ try { for (const slug of pages) { try { const page = (await admin.pages.get(slug)).page; - if (page.namespace !== tag || page.source_workspace_id !== workspaceId) + if (page.namespace !== tag || page.source_vm_id !== workspaceId) throw new Error("Unexpected smoke page owner"); await admin.pages.delete(slug); pages.delete(slug); @@ -676,7 +677,7 @@ try { } if (workspaceId) { try { - await deleteCloudWorkspace(admin.workspace(workspaceId)); + await deleteCloudWorkspace(admin.vm(workspaceId)); workspaceId = undefined; } catch (error) { if ((error as { status?: number }).status === 404) workspaceId = undefined; diff --git a/packages/adapters/scripts/verify-cloud-isolation.ts b/packages/adapters/scripts/verify-cloud-isolation.ts index 1095a25ba..ba0453d47 100644 --- a/packages/adapters/scripts/verify-cloud-isolation.ts +++ b/packages/adapters/scripts/verify-cloud-isolation.ts @@ -9,13 +9,14 @@ import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import { Oblien } from "../src/oblien"; +import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract"; import { cloudWorkspaceStatus, waitForCloudDockerWorkspace } from "../src/runtime/cloud/workspace-ready"; import { CloudWorkspaceExecutor } from "../src/runtime/cloud/workspace-executor"; import { deleteCloudWorkspace } from "../src/runtime/cloud/workspace-delete"; if (process.argv[2] !== "--staging-env" || !process.argv[3]) throw new Error("Provide a confirmed staging credential file with --staging-env"); const config = parseEnv(await readFile(process.argv[3], "utf8")); -const baseUrl = config.OBLIEN_API_URL || "https://api.oblien.com"; +const baseUrl = oblienApiBaseUrl(config.OBLIEN_API_URL).toString(); if (!config.OBLIEN_CLIENT_ID || !config.OBLIEN_CLIENT_SECRET || new URL(baseUrl).protocol !== "https:") throw new Error("Staging credentials and HTTPS are required"); const admin = new Oblien({ clientId: config.OBLIEN_CLIENT_ID, clientSecret: config.OBLIEN_CLIENT_SECRET, baseUrl }); const tag = `os-cycle-${randomUUID().replaceAll("-", "").slice(0, 14)}`; @@ -61,7 +62,7 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name let observedState: string | undefined; try { await until(name, async () => { - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); const state = cloudWorkspaceStatus(workspace); if (state !== observedState) { const info = workspace.info as { status?: string; is_running?: boolean } | undefined; @@ -81,13 +82,13 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name message: error instanceof Error ? error.message : "Unknown failure" }); // Preserve the failed automatic-stop result, then exercise the independent // customer cleanup and explicit-reactivation contract on the same fixture. - await client.workspace(workspaceId).stop(); - await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.workspaces.get(workspaceId)) === "stopped"); + await client.vm(workspaceId).stop(); + await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.vms.get(workspaceId)) === "stopped"); } } const a = `${tag}-a`, b = `${tag}-b`; -const resources = { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }; -const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_workspaces" as const }); +const resources = { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }; +const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_vms" as const }); const create = (namespace: string, suffix: string) => ({ namespace, name: `${namespace}-${suffix}`, slug: `${namespace}-${suffix}`, image: "oblien/docker:29", mode: "temporary" as const, wait_ready: false, idempotency_key: `${namespace}-${suffix}`, config: { cpus: 2, memory_mb: 4096, disk_size_mb: 32768, ttl: "15m", ttl_action: "remove" as const, @@ -96,7 +97,7 @@ const create = (namespace: string, suffix: string) => ({ namespace, name: `${nam try { log("starting isolated quota test", { directory }); const defaults = await admin.billing.defaults(); - check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_workspaces"); + check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_vms"); for (const namespace of [a, b]) { const input = { name: namespace, slug: namespace, resource_limits: resources }; const { data } = namespace === a ? await admin.namespaces.ensure(input) : await admin.namespaces.create(input); @@ -108,7 +109,7 @@ try { log("new namespace billing", { customer: namespace === a ? "A" : "B", method: namespace === a ? "ensure" : "create", entitlement, balance, policy: inheritedPolicy, subscription: await admin.billing.subscription(namespace) }); check(`${namespace === a ? "A" : "B"}: zero credit inherited without a grant`, entitlement.namespace === namespace && entitlement.quota.limit === 0 && balance.blocking && - inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_workspaces", false); + inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_vms", false); const subscription = (await admin.billing.subscription(namespace)).subscription; check(`${namespace === a ? "A" : "B"}: unpaid namespace cannot inherit the owner's plan`, subscription === null && (entitlement.tierId === null || entitlement.tierId === "free") && entitlement.periodStart === null && entitlement.periodEnd === null, false); // Continue the independent enforcement checks with an explicit fixture @@ -125,7 +126,7 @@ try { const request = client._http.request.bind(client._http); client._http.request = async (input: Parameters[0]): Promise => { const result = await request(input); - if (input.method === "POST" && input.path === "/workspace") { + if (input.method === "POST" && input.path === "/vms") { const data = result as Record; log("workspace creation response shape", { keys: Object.keys(data), success: data.success, code: data.code, error: typeof data.error === "string" ? data.error : undefined, @@ -134,15 +135,15 @@ try { return result; }; } - check("exhausted customers retain scoped inspection access", (await clientA.workspaces.list()).workspaces.length === 0); - await denied("unpaid namespace cannot create compute", () => clientA.workspaces.create(create(a, "unpaid")), [402, 403]); + check("exhausted customers retain scoped inspection access", (await clientA.vms.list()).vms.length === 0); + await denied("unpaid namespace cannot create compute", () => clientA.vms.create(create(a, "unpaid")), [402, 403]); for (const namespace of [a, b]) await admin.billing.setPolicy(namespace, policy(100)); check("isolated test allowance activates only its namespace", (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(b)).blocking); const repeated = await admin.namespaces.ensure({ name: a, slug: a, resource_limits: resources }); check("ensure preserves an existing namespace's allowance", repeated.data.id === namespaceIds.get(a) && (await admin.billing.policy(a)).quotaLimit === 100); - const raced = await Promise.allSettled([clientA.workspaces.create(create(a, "race-1")), clientA.workspaces.create(create(a, "race-2"))]); - const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled"); + const raced = await Promise.allSettled([clientA.vms.create(create(a, "race-1")), clientA.vms.create(create(a, "race-2"))]); + const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled"); const losers = raced.filter(item => item.status === "rejected"); log("concurrent create outcomes", { results: raced.map(item => item.status === "fulfilled" ? { state: item.status, workspaceId: item.value?.id, namespace: item.value?.namespace } @@ -151,19 +152,19 @@ try { const workspaceA = winners[0]!.value; // Inspect the actual wire status, independently of Openship's compatibility // normalization for the provider's former HTTP-200 limit failures. - const limited = await fetch(new URL("/workspace", baseUrl), { + const limited = await fetch(oblienApiUrl(new URL(baseUrl), "/vms"), { method: "POST", headers: { Authorization: `Bearer ${tokenA}`, "Content-Type": "application/json" }, body: JSON.stringify(create(a, "raw-limit")), redirect: "error", signal: AbortSignal.timeout(30_000), }); log("workspace cap wire response", { status: limited.status }); check("workspace cap returns HTTP 409", limited.status === 409); await limited.arrayBuffer(); - const workspaceB = await clientB.workspaces.create(create(b, "main")); + const workspaceB = await clientB.vms.create(create(b, "main")); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); await waitForCloudDockerWorkspace(clientB, workspaceB.id, b, { signal: abort.signal }); check("two customers own different workspaces", workspaceA.id !== workspaceB.id && workspaceA.namespace === a && workspaceB.namespace === b); for (const [client, workspace, namespace] of [[clientA, workspaceA, a], [clientB, workspaceB, b]] as const) { - const executor = new CloudWorkspaceExecutor(() => client.workspace(workspace.id).runtime()); + const executor = new CloudWorkspaceExecutor(() => client.vm(workspace.id).runtime()); const path = `/opt/openship/cloud-docker/routes/${namespace}`; try { await executor.mkdir(path); await executor.writeFile(`${path}/index.html`, `Isolated customer ${namespace}`); @@ -175,16 +176,16 @@ try { finally { await executor.dispose(); } pages.set(namespace, namespace); await save(); - await admin.pages.create({ slug: namespace, namespace, workspace_id: workspace.id, path, domain: "preview.oblien.com" }); + await admin.pages.create({ slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" }); } - const visibleA = (await clientA.workspaces.list()).workspaces; - const visibleB = (await clientB.workspaces.list()).workspaces; + const visibleA = (await clientA.vms.list()).vms; + const visibleB = (await clientB.vms.list()).vms; check("workspace lists are isolated", visibleA.length === 1 && visibleA[0]!.namespace === a && visibleB.length === 1 && visibleB[0]!.namespace === b); - await denied("customer cannot read another customer's VM", () => clientA.workspaces.get(workspaceB.id), [403, 404]); - await denied("customer cannot stop another customer's VM", () => clientA.workspace(workspaceB.id).stop(), [403, 404]); - await denied("customer cannot delete another customer's VM", () => clientA.workspaces.delete(workspaceB.id), [403, 404]); - await denied("customer cannot escape its namespace on creation", () => clientA.workspaces.create(create(b, "escape")), [400, 403, 409, 422]); - check("foreign namespace still owns exactly its original workspace", (await clientB.workspaces.list()).workspaces.length === 1); + await denied("customer cannot read another customer's VM", () => clientA.vms.get(workspaceB.id), [403, 404]); + await denied("customer cannot stop another customer's VM", () => clientA.vm(workspaceB.id).stop(), [403, 404]); + await denied("customer cannot delete another customer's VM", () => clientA.vms.delete(workspaceB.id), [403, 404]); + await denied("customer cannot escape its namespace on creation", () => clientA.vms.create(create(b, "escape")), [400, 403, 409, 422]); + check("foreign namespace still owns exactly its original workspace", (await clientB.vms.list()).vms.length === 1); await denied("customer cannot access account billing", () => clientA.billing.entitlement(b), [403]); await denied("customer cannot grant itself credit", () => clientA.billing.setPolicy(a, policy(500)), [403]); await denied("customer cannot mint a more privileged token", () => clientA.tokens.create({ scope: "namespace", namespace: b }), [403]); @@ -194,10 +195,10 @@ try { check("Page listing cannot expose another namespace", visible.every(page => page.namespace === a), false); } catch (error) { check("Page listing requires privileged proxy", (error as { status?: number }).status === 403); } await denied("customer cannot read another customer's Page", () => clientA.pages.get(b), [403, 404]); - await denied("namespace CPU ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]); - await denied("namespace RAM ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]); - await denied("namespace disk ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]); - check("rejected resize keeps the original allocation", (await clientA.workspaces.get(workspaceA.id)).resources?.cpus === 2); + await denied("namespace CPU ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]); + await denied("namespace RAM ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]); + await denied("namespace disk ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]); + check("rejected resize keeps the original allocation", (await clientA.vms.get(workspaceA.id)).resources?.cpus === 2); try { await until("provider records compute usage", async () => (await admin.billing.entitlement(a)).quota.used > 0, 300_000); @@ -228,25 +229,25 @@ try { check("exhaustion is visible in entitlement and balance", true); check("new usage crossed the configured credit allowance", effectiveAllowance !== null && (await admin.billing.entitlement(a)).quota.used >= effectiveAllowance); try { - await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped", 90_000); + await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped", 90_000); check("provider stops A on exhaustion", true); } catch { check("provider stops A on exhaustion", false, false); log("explicitly stopping A to continue independent management checks"); - await clientA.workspace(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); } - check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking); - await denied("exhausted customer cannot restart compute", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]); - await denied("exhausted customer cannot create replacement compute", () => clientA.workspaces.create(create(a, "blocked")), [402, 403, 409]); - check("exhausted customer can still inspect its stopped VM", (await clientA.workspaces.get(workspaceA.id)).id === workspaceA.id); - await clientA.workspace(workspaceA.id).stop(); - await clientA.workspace(workspaceA.id).stop(); + check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking); + await denied("exhausted customer cannot restart compute", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]); + await denied("exhausted customer cannot create replacement compute", () => clientA.vms.create(create(a, "blocked")), [402, 403, 409]); + check("exhausted customer can still inspect its stopped VM", (await clientA.vms.get(workspaceA.id)).id === workspaceA.id); + await clientA.vm(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); check("billing-suspended customer can repeat Stop", true); await admin.billing.setPolicy(a, policy(100)); await until("billing restoration", async () => (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(a)).blocking); - check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped"); - await clientA.workspace(workspaceA.id).start(); + check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped"); + await clientA.vm(workspaceA.id).start(); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); check("restored customer explicitly resumes the same VM", true); @@ -254,28 +255,28 @@ try { await suspendedWorkspaceStops(clientA, workspaceA.id, a, "manual suspension stops A"); await admin.billing.setPolicy(a, policy(200)); check("credit increase cannot undo a manual suspension", (await admin.namespaces.get(a)).data.status === "suspended" && (await admin.billing.balance(a)).blocking); - await denied("manual suspension blocks Start despite positive credit", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]); + await denied("manual suspension blocks Start despite positive credit", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]); await admin.namespaces.activate(namespaceIds.get(a)!); - check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped"); - await clientA.workspace(workspaceA.id).start(); + check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped"); + await clientA.vm(workspaceA.id).start(); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); check("manually suspended VM starts only after reactivation", true); log("second manual suspension response", { namespace: a, response: await admin.namespaces.suspend(namespaceIds.get(a)!) }); await suspendedWorkspaceStops(clientA, workspaceA.id, a, "second manual suspension stops A"); - await clientA.workspace(workspaceA.id).stop(); - await clientA.workspace(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); check("manually suspended customer can repeat Stop", true); - await deleteCloudWorkspace(clientA.workspace(workspaceA.id)); - await until("A disappears from the scoped workspace list", async () => (await clientA.workspaces.list()).workspaces.length === 0, 60_000); - check("suspended customer can delete resources", (await clientA.workspaces.list()).workspaces.length === 0); - check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running"); + await deleteCloudWorkspace(clientA.vm(workspaceA.id)); + await until("A disappears from the scoped workspace list", async () => (await clientA.vms.list()).vms.length === 0, 60_000); + check("suspended customer can delete resources", (await clientA.vms.list()).vms.length === 0); + check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running"); await admin.billing.setPolicy(b, policy(0)); - await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "stopped"); - await clientB.workspace(workspaceB.id).stop(); - await clientB.workspace(workspaceB.id).stop(); - await deleteCloudWorkspace(clientB.workspace(workspaceB.id)); - await until("B disappears from the scoped workspace list", async () => (await clientB.workspaces.list()).workspaces.length === 0, 60_000); - check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.workspaces.list()).workspaces.length === 0); + await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "stopped"); + await clientB.vm(workspaceB.id).stop(); + await clientB.vm(workspaceB.id).stop(); + await deleteCloudWorkspace(clientB.vm(workspaceB.id)); + await until("B disappears from the scoped workspace list", async () => (await clientB.vms.list()).vms.length === 0, 60_000); + check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.vms.list()).vms.length === 0); } catch (error) { check("all lifecycle checks completed", false, false); log("test failed", { message: error instanceof Error ? error.message.replace(/([?&](?:token|access_token)=)[^&\s]+/gi, "$1[redacted]") : "Unknown failure", status: (error as { status?: number }).status }); diff --git a/packages/adapters/src/index.ts b/packages/adapters/src/index.ts index 233833643..619c8b966 100644 --- a/packages/adapters/src/index.ts +++ b/packages/adapters/src/index.ts @@ -606,7 +606,9 @@ export { // ─── Oblien SDK (re-export for single source of truth) ─────────────────────── export { Oblien, OblienError, cloudWorkspaceCreationFailure } from "./oblien"; +export { oblienApiBaseUrl, oblienApiUrl, toOblienVmLimits, toOblienVmCapacity, toOblienVmPolicy, toOblienVmOffer, cloudBillingContract } from "./oblien-contract"; export type { + NamespaceResourceLimits, NamespaceUsageUnits, NamespaceUsageUnitBucket, NamespaceUsageUnitsParams, diff --git a/packages/adapters/src/infra/cloud-routing-sdk.test.ts b/packages/adapters/src/infra/cloud-routing-sdk.test.ts index e96219677..30927a4f5 100644 --- a/packages/adapters/src/infra/cloud-routing-sdk.test.ts +++ b/packages/adapters/src/infra/cloud-routing-sdk.test.ts @@ -27,14 +27,14 @@ beforeEach(() => { return page ? Response.json({ success: true, page }) : Response.json({ error: "Not found" }, { status: 404 }); if (url.pathname === "/pages" && method === "POST") { page = { id: 42, slug: body.slug, domain: body.domain, namespace: h.namespace, - source_workspace_id: body.workspace_id, exported_path: body.path, url: `https://${hostname}` }; + source_vm_id: body.vm_id, exported_path: body.path, url: `https://${hostname}` }; return Response.json({ success: true, page }); } if (url.pathname === "/pages/app/enable" && method === "POST") return Response.json({ success: true }); - if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "GET") + if (url.pathname === `/vms/${h.workspaceId}/network` && method === "GET") return Response.json({ ingress_ports: [443] }); - if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "PATCH") + if (url.pathname === `/vms/${h.workspaceId}/network` && method === "PATCH") return Response.json({ success: true }); if (url.pathname === `/domain/routes/${hostname}` && method === "PUT") return Response.json({ success: true, hostname, version: writes.length, @@ -54,7 +54,7 @@ it.each([301, 302, 307, 308])("sends canonical redirect intent through the real } }); await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true }); const tables = writes.filter(request => request.path === `/domain/routes/${hostname}`); - expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(writes.filter(request => request.path === "/pages")).toHaveLength(1); expect(requests.some(url => url.pathname === "/workspace")).toBe(false); }); @@ -66,13 +66,13 @@ it("reuses the owned Page through the SDK after routes become a compiled table", const routes = writes.filter(request => request.path === `/domain/routes/${hostname}`); expect(routes).toHaveLength(2); expect(routes[1]).toEqual({ method: "PUT", path: `/domain/routes/${hostname}`, body: { - routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }], } }); - expect(writes).toContainEqual({ method: "PATCH", path: `/workspace/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } }); + expect(writes).toContainEqual({ method: "PATCH", path: `/vms/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } }); expect(requests.some(url => url.pathname === "/workspace")).toBe(false); }); -it.each(["namespace", "source_workspace_id", "exported_path"])("does not write when the Page's %s changes", async field => { +it.each(["namespace", "source_vm_id", "exported_path"])("does not write when the Page's %s changes", async field => { await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true }); page![field] = "different-owner"; writes.length = 0; @@ -92,7 +92,7 @@ it("publishes path-only routes through the SDK without a static or SPA fallback" spa: false, routes: [{ match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: h.workspaceId, port: 3000 }, + action: { kind: "proxy", vm: h.workspaceId, port: 3000 }, }], }, }); diff --git a/packages/adapters/src/infra/cloud-routing.test.ts b/packages/adapters/src/infra/cloud-routing.test.ts index b2b973a6c..8b13d6473 100644 --- a/packages/adapters/src/infra/cloud-routing.test.ts +++ b/packages/adapters/src/infra/cloud-routing.test.ts @@ -14,7 +14,7 @@ describe("project routes on a managed server", () => { }); expect(h.pages.create).toHaveBeenCalledOnce(); await h.infra.registerRoute(route); - expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(h.pages.create).toHaveBeenCalledOnce(); }); @@ -25,7 +25,7 @@ describe("project routes on a managed server", () => { }); expect(h.routes.set).toHaveBeenCalledWith(route.domain, { spa: false, - routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }], + routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }], }); }); it("updates one project-owned Page repeatedly without a new workspace", async () => { @@ -33,10 +33,10 @@ describe("project routes on a managed server", () => { await h.infra.registerRoute(route); expect(h.pages.create).toHaveBeenCalledOnce(); expect(h.routes.set).toHaveBeenCalledTimes(2); - expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(h.workspace.network.update).toHaveBeenCalledWith({ ingress_ports: [443, 3000] }); }); - it.each(["namespace", "source_workspace_id", "exported_path"])("refuses a changed %s before mutating the route", async field => { + it.each(["namespace", "source_vm_id", "exported_path"])("refuses a changed %s before mutating the route", async field => { await h.infra.registerRoute(route); h.records.get("app")![field] = "another-owner"; h.routes.set.mockClear(); h.pages.enable.mockClear(); @@ -58,8 +58,8 @@ describe("project routes on a managed server", () => { it("validates every composite backend, not only the root", async () => { await h.infra.registerRoute(route); h.routes.set.mockClear(); - await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong"); - await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned"); + await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong"); + await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned"); expect(h.routes.set).not.toHaveBeenCalled(); }); it("keeps unrelated ingress ports when adding an application", async () => { diff --git a/packages/adapters/src/infra/cloud.test.ts b/packages/adapters/src/infra/cloud.test.ts index 424061879..4c498d30c 100644 --- a/packages/adapters/src/infra/cloud.test.ts +++ b/packages/adapters/src/infra/cloud.test.ts @@ -15,7 +15,7 @@ let provider: CloudInfraProvider; beforeEach(() => { vi.mocked(probePublicTlsCertificate).mockReset().mockImplementation(async domain => ({ domain, verified: true, expiresAt: expiry, issuer: "Let's Encrypt", reason: "issued" })); page = { slug: "route-one", domain: "opsh.io", url: `https://${hostname}`, custom_domain: hostname, - namespace: "ns-one", source_workspace_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" }; + namespace: "ns-one", source_vm_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" }; routes = vi.fn(async () => ({ data: [{ hostname, namespace: "ns-one", owner_type: "page", owner_id: "route-one", is_custom: 1 }] })); pages = { list: vi.fn(async () => ({ pages: [page] })), get: vi.fn(async () => ({ page })), diff --git a/packages/adapters/src/infra/cloud.ts b/packages/adapters/src/infra/cloud.ts index 7a8fab081..eae46c2b3 100644 --- a/packages/adapters/src/infra/cloud.ts +++ b/packages/adapters/src/infra/cloud.ts @@ -109,7 +109,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } async getQuota(): Promise { - return this.client.workspaces.getQuota(); + return this.client.vms.getQuota(); } // ── Domain / Slug checks ─────────────────────────────────────────────── @@ -199,7 +199,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if ( !page || (this.workspaceId && - (page.source_workspace_id !== this.workspaceId || + (page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}`)) ) throw disconnected(); @@ -230,11 +230,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (route.protection) throw new Error("Password protection is not supported by the Cloud edge."); if (route.webhookProxy) throw new Error("Managed application routes cannot proxy control-plane webhooks"); - const proxyTargets = new Map(); + const proxyTargets = new Map(); for (const location of route.proxyLocations ?? []) { if (location.external) continue; proxyTargets.set(location.targetUrl, { - workspace: this.scope.workspaceId, + vm: this.scope.workspaceId, port: await this.scope.resolveUrl(location.targetUrl), }); } @@ -251,7 +251,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { trailingSlash: route.trailingSlash, }, { - root: port ? { workspace: this.scope.workspaceId, port } : undefined, + root: port ? { vm: this.scope.workspaceId, port } : undefined, staticPage: route.staticRoot ? slug : undefined, proxyTargets, }, @@ -300,7 +300,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } if ( page.namespace === this.options.namespace && - page.source_workspace_id === this.workspaceId && + page.source_vm_id === this.workspaceId && page.exported_path === `${this.routeRoot}/${page.slug}` ) hostnames.push(...cloudPageHostnames(page)); @@ -348,14 +348,14 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { ) throw new Error("Invalid cloud routing port"); const pathsOnly = hostPort === undefined && !staticRoot; - if (pathsOnly && !input?.routes.some((rule) => rule.action.kind === "proxy")) + if (pathsOnly && !input?.routes?.some((rule) => rule.action.kind === "proxy")) throw new Error("A route needs a process or a static release"); const slug = this.routeSlug(hostname, custom); let routes = input ?? { routes: [ { match: { path: "/", type: "prefix" as const }, - action: { kind: "proxy" as const, workspace: this.scope.workspaceId, port: hostPort! }, + action: { kind: "proxy" as const, vm: this.scope.workspaceId, port: hostPort! }, }, ], }; @@ -375,7 +375,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } const assertPage = () => { if ( - page!.source_workspace_id !== this.workspaceId || + page!.source_vm_id !== this.workspaceId || page!.namespace !== this.options.namespace || page!.exported_path !== path ) @@ -408,7 +408,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { ); if (page) { const deployed = await this.pages.deploy(slug, { - workspace_id: this.scope.workspaceId, + vm_id: this.scope.workspaceId, path, }); if (!deployed.success) throw new Error("Could not publish the static release"); @@ -422,7 +422,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (!page) { try { await this.pages.create({ - workspace_id: this.scope.workspaceId, + vm_id: this.scope.workspaceId, path, name: `Route ${hostname}`, slug, @@ -440,9 +440,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (page.custom_domain !== hostname) await this.pages.connectDomain(slug, { domain: hostname }); } - const ports = routes.routes.flatMap((rule) => + const ports = (routes.routes ?? []).flatMap((rule) => rule.action.kind === "proxy" && - rule.action.workspace === this.workspaceId && + rule.action.vm === this.workspaceId && rule.action.port ? [rule.action.port] : [], @@ -462,7 +462,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { // would leave a failed release live at the edge. if (hadPage && restored.trim() === "restored") { if ( - !(await this.pages.deploy(slug, { workspace_id: this.scope.workspaceId, path })) + !(await this.pages.deploy(slug, { vm_id: this.scope.workspaceId, path })) .success ) throw new Error("Could not republish the previous static release"); @@ -490,9 +490,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { async resolveRoutingTarget( containerId: string, port: number, - ): Promise<{ workspace: string; port: number }> { + ): Promise<{ vm: string; port: number }> { return { - workspace: this.scope.workspaceId, + vm: this.scope.workspaceId, port: await this.scope.resolveTarget(containerId, port), }; } @@ -513,9 +513,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { throw new AppError("Domain does not belong to this project", 404, "DOMAIN_NOT_FOUND"); await this.assertRouteTargets(input); await this.ensureIngressPorts( - input.routes.flatMap((route) => + (input.routes ?? []).flatMap((route) => route.action.kind === "proxy" && - route.action.workspace === this.workspaceId && + route.action.vm === this.workspaceId && route.action.port ? [route.action.port] : [], @@ -534,7 +534,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { const { page } = await this.pages.get(input.static.page); if ( page.namespace !== this.options.namespace || - page.source_workspace_id !== this.workspaceId || + page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}` ) throw new AppError( @@ -545,11 +545,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } const ports = new Set(); if (publishedPort !== undefined) ports.add(publishedPort); - for (const route of input.routes) { + for (const route of input.routes ?? []) { if ( route.action.kind === "proxy" && !route.action.origin && - (route.action.workspace !== this.workspaceId || + (route.action.vm !== this.workspaceId || typeof route.action.port !== "number") ) throw new AppError( @@ -570,7 +570,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { * only ensures the project's validated route ports can receive edge traffic. */ private async ensureIngressPorts(add: number[]) { if (!add.length) return; - const workspace = this.client.workspace(this.scope.workspaceId); + const workspace = this.client.vm(this.scope.workspaceId); const network = await workspace.network.get(); const current = Array.isArray(network.ingress_ports) ? (network.ingress_ports as number[]) : []; const next = [...new Set([...current, ...add])]; @@ -593,7 +593,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { * is uncertain state and must retain the deletion fence. */ private isForeignProjectRoute(page: { slug: string; - source_workspace_id?: string | null; + source_vm_id?: string | null; exported_path?: string | null; }): boolean { const prefix = `${CLOUD_DOCKER_ROUTE_ROOT}/projects/`; @@ -602,7 +602,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if ( !this.routeRoot || !canonicalRoot(this.routeRoot) || - !page.source_workspace_id?.trim() || + !page.source_vm_id?.trim() || !page.exported_path || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(page.slug) ) @@ -629,7 +629,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { const page = await this.pageForDomain(domain); if (!page) return "absent"; if ( - page.source_workspace_id !== this.workspaceId || + page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}` ) { if (mode === "project-cleanup" && this.isForeignProjectRoute(page)) return "foreign"; diff --git a/packages/adapters/src/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts new file mode 100644 index 000000000..d30d3bb5e --- /dev/null +++ b/packages/adapters/src/oblien-contract.test.ts @@ -0,0 +1,150 @@ +import { createServer } from "node:http"; +import { once } from "node:events"; +import { afterEach, expect, it, vi } from "vitest"; +import { DEFAULT_API_BASE_URL, Oblien as OfficialOblien } from "oblien"; +import { Oblien, cloudWorkspaceCreationFailure } from "./oblien"; +import { + cloudBillingContract, + oblienApiBaseUrl, + oblienApiUrl, + toOblienVmOffer, +} from "./oblien-contract"; + +afterEach(() => vi.unstubAllGlobals()); + +it("inherits the published SDK default for the adapter and official client", async () => { + const urls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => { + urls.push(String(input)); + return Response.json({ success: true, vms: [], namespaces: [] }); + }), + ); + await new Oblien({ token: "fixture" }).vms.list(); + await new OfficialOblien({ token: "fixture" }).vms.list(); + expect(DEFAULT_API_BASE_URL).toBe("https://api.oblien.com/v1"); + expect(oblienApiBaseUrl().href).toBe(DEFAULT_API_BASE_URL); + expect(urls).toEqual([`${DEFAULT_API_BASE_URL}/vms`, `${DEFAULT_API_BASE_URL}/vms`]); +}); + +it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE requests without replaying a failed create", async () => { + const calls: Array<{ path: string; body: Record }> = []; + const server = createServer(async (req, res) => { + let raw = ""; + for await (const chunk of req) raw += chunk; + calls.push({ path: req.url!, body: raw ? JSON.parse(raw) : {} }); + if (req.headers.authorization !== "Bearer fixture") { + res.writeHead(401).end(); + return; + } + if (req.url === "/proxy/v1/vms/vm-a/stats/stream") { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.end('data: {"cpu":12}\n\n'); + return; + } + res.setHeader("Content-Type", "application/json"); + if (req.url === "/proxy/v1/vms" && req.method === "POST") { + res + .writeHead(422) + .end( + JSON.stringify({ + success: false, + code: "CREATE_FAILED", + details: { vm_id: "vm-failed" }, + }), + ); + return; + } + if (req.url === "/proxy/v1/vms") { + res.end( + JSON.stringify({ success: true, vms: [{ id: "vm-a", namespace: "tenant-a" }], total: 1 }), + ); + return; + } + if (req.url === "/proxy/v1/vms/vm-a") { + res.end(JSON.stringify({ success: true, vm: { id: "vm-a", namespace: "tenant-a" } })); + return; + } + if (req.url === "/proxy/v1/pages") { + res.end(JSON.stringify({ success: true, page: { slug: "site", source_vm_id: "vm-a" } })); + return; + } + if (req.url === "/proxy/v1/domain/routes/site.example") { + res.end(JSON.stringify({ success: true })); + return; + } + res.writeHead(404).end(JSON.stringify({ success: false })); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No test listener"); + try { + const client = new Oblien({ + token: "fixture", + baseUrl: `http://127.0.0.1:${address.port}/proxy/v1`, + }); + expect((await client.vms.list()).vms[0]?.id).toBe("vm-a"); + expect((await client.vm("vm-a").get()).namespace).toBe("tenant-a"); + await client.pages.create({ vm_id: "vm-a", name: "Site", slug: "site", path: "/dist" }); + await client.routes.set("site.example", { + routes: [{ match: { path: "/" }, action: { kind: "proxy", vm: "vm-a", port: 3000 } }], + }); + for await (const sample of client.streamWorkspaceMetrics("vm-a")) { + expect(sample).toEqual({ cpu: 12 }); + break; + } + const failure = await client.vms.create({ wait_ready: false }).catch((error) => error); + expect(cloudWorkspaceCreationFailure(failure)).toMatchObject({ workspaceId: "vm-failed" }); + expect( + calls.filter((call) => call.path === "/proxy/v1/vms" && call.body.wait_ready === false), + ).toHaveLength(1); + expect(calls.every((call) => call.path.startsWith("/proxy/v1/"))).toBe(true); + expect(calls.find((call) => call.path.endsWith("/pages"))?.body).toMatchObject({ + vm_id: "vm-a", + }); + expect(JSON.stringify(calls)).not.toContain("workspace_id"); + } finally { + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } +}); + +it("preserves paid limits, zero and unlimited counts while leaving customer metadata opaque", () => { + const metadata = { + workspace: "customer-chosen", + max_workspaces: "opaque", + capacity: { vcpus: 8, memoryMb: 16, diskGb: 32, workspaces: 42 }, + }; + const saved = { + unitAmount: 12000, + resourceLimits: { max_workspaces: null, max_vcpus: 8 }, + capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 0 }, + policy: { overdraft: 0, onOverdraftAction: "stop_workspaces" as const }, + metadata, + }; + const native = toOblienVmOffer(saved); + expect(native).toEqual({ + unitAmount: 12000, + resourceLimits: { max_vms: null, max_vcpus: 8 }, + capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 0 }, + policy: { overdraft: 0, onOverdraftAction: "stop_vms" }, + metadata, + }); + expect(cloudBillingContract({ success: true, subscription: { offer: native } })).toEqual({ + success: true, + subscription: { offer: saved }, + }); + expect(native.metadata).toBe(metadata); + expect(saved.capacity.workspaces).toBe(0); +}); + +it("rejects request paths that escape a versioned mount", () => { + const base = oblienApiBaseUrl("https://provider.example/proxy/v2"); + for (const path of ["../vms", "/../vms", "https://other.example/vms", "//other.example/vms"]) + expect(() => oblienApiUrl(base, path)).toThrow(); + expect(oblienApiUrl(base, "/vms").href).toBe("https://provider.example/proxy/v2/vms"); +}); diff --git a/packages/adapters/src/oblien-contract.ts b/packages/adapters/src/oblien-contract.ts new file mode 100644 index 000000000..0b0a5367d --- /dev/null +++ b/packages/adapters/src/oblien-contract.ts @@ -0,0 +1,108 @@ +import { DEFAULT_API_BASE_URL } from "oblien"; + +/** The SDK owns the default. An operator override is a complete API mount. */ +export function oblienApiBaseUrl(input = DEFAULT_API_BASE_URL): URL { + const base = new URL(input); + if ( + base.username || + base.password || + base.search || + base.hash || + (base.protocol !== "https:" && + !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) + ) { + throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); + } + base.pathname = base.pathname.replace(/\/+$/, ""); + return base; +} + +export function oblienApiUrl(base: URL, path: string): URL { + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(path)) + throw new Error("Oblien request escaped its API origin"); + const root = base.toString().replace(/\/+$/, "") + "/"; + const url = new URL(path.replace(/^\//, ""), root); + if (url.origin !== base.origin || !url.pathname.startsWith(new URL(root).pathname)) + throw new Error("Oblien request escaped its API mount"); + return url; +} + +/** OpenShip's saved Cloud workspace policies are its own persisted contract. + * Map that count to provider VMs only at the external boundary. */ +export function toOblienVmLimits(limits: T) { + const { max_workspaces, ...rest } = limits; + return { ...rest, max_vms: max_workspaces }; +} + +export function toOblienVmCapacity(capacity: T) { + const { workspaces, ...rest } = capacity; + return { ...rest, vms: workspaces }; +} + +export function toOblienVmPolicy( + policy: T, +) { + const { onOverdraftAction, ...rest } = policy; + return { + ...rest, + onOverdraftAction: + onOverdraftAction === "stop_workspaces" ? ("stop_vms" as const) : onOverdraftAction, + }; +} + +export function toOblienVmOffer< + T extends { + resourceLimits?: { max_workspaces?: number | null }; + capacity?: { vcpus: number; memoryMb: number; diskGb: number; workspaces: number }; + policy?: { onOverdraftAction?: "stop_workspaces" | "block" }; + }, +>(offer: T) { + const { resourceLimits, capacity, policy, ...rest } = offer; + return { + ...rest, + ...(resourceLimits ? { resourceLimits: toOblienVmLimits(resourceLimits) } : {}), + ...(capacity ? { capacity: toOblienVmCapacity(capacity) } : {}), + ...(policy ? { policy: toOblienVmPolicy(policy) } : {}), + }; +} + +/** Decode only documented billing-contract nodes. Metadata, signatures and + * customer dictionaries stay opaque; no recursive word replacement is used. */ +export function cloudBillingContract(value: unknown, depth = 0): unknown { + if (!value || typeof value !== "object" || Array.isArray(value)) return value; + if (depth > 12) throw new Error("Oblien returned an invalid billing contract"); + const source = value as Record; + const result = { ...source }; + if ("vcpus" in source && "memoryMb" in source && "diskGb" in source) { + result.workspaces = source.vms; + delete result.vms; + } + if ( + source.resourceLimits && + typeof source.resourceLimits === "object" && + !Array.isArray(source.resourceLimits) + ) { + const { max_vms, ...rest } = source.resourceLimits as Record; + result.resourceLimits = { ...rest, max_workspaces: max_vms }; + } + if (source.onOverdraftAction === "stop_vms") result.onOverdraftAction = "stop_workspaces"; + for (const key of [ + "data", + "capacity", + "quote", + "current", + "next", + "subscription", + "offer", + "policy", + "pendingChange", + "change", + "pendingCheckout", + "checkout", + ]) + if (source[key] && typeof source[key] === "object") + result[key] = cloudBillingContract(source[key], depth + 1); + if (Array.isArray(source.presets)) + result.presets = source.presets.map((item) => cloudBillingContract(item, depth + 1)); + return result; +} diff --git a/packages/adapters/src/oblien-metrics.test.ts b/packages/adapters/src/oblien-metrics.test.ts index 4068260b6..67d449c5b 100644 --- a/packages/adapters/src/oblien-metrics.test.ts +++ b/packages/adapters/src/oblien-metrics.test.ts @@ -32,7 +32,7 @@ it("keeps provider credentials server-side, rejects redirects and releases the r } expect(cancel).toHaveBeenCalledOnce(); const [url, request] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit]; - expect(url.href).toBe("https://api.oblien.com/workspace/ws-owned/stats/stream"); + expect(url.href).toBe("https://api.oblien.com/v1/vms/ws-owned/stats/stream"); expect(request.redirect).toBe("error"); expect(new Headers(request.headers).get("Authorization")).toBe("Bearer scoped-token"); expect(request.signal?.aborted).toBe(true); diff --git a/packages/adapters/src/oblien.test.ts b/packages/adapters/src/oblien.test.ts index 52b806a6e..b3748bca9 100644 --- a/packages/adapters/src/oblien.test.ts +++ b/packages/adapters/src/oblien.test.ts @@ -7,7 +7,7 @@ describe("Oblien SDK transport", () => { status: 429, headers: { "Retry-After": retryAfter }, })); vi.stubGlobal("fetch", fetcher); - const error = await new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }).catch(error => error); + const error = await new Oblien({ token: "test" }).vms.create({ wait_ready: false }).catch(error => error); expect(error).toMatchObject({ status: 429, code: "OBLIEN_RATE_LIMITED" }); expect(error.details.retryAfterSeconds).toBeGreaterThan(0); expect(error.details.retryAfterSeconds).toBeLessThanOrEqual(30); @@ -17,7 +17,7 @@ describe("Oblien SDK transport", () => { }); it.each(["invalid", "-1", "99999999999999999999999"])("ignores invalid Retry-After %s", async (retryAfter) => { vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 503, headers: { "Retry-After": retryAfter } }))); - const error = await new Oblien({ token: "test" }).workspaces.get("ws").catch(error => error); + const error = await new Oblien({ token: "test" }).vms.get("ws").catch(error => error); expect(error.status).toBe(503); expect(error.details).toBeUndefined(); }); @@ -30,7 +30,7 @@ describe("Oblien SDK transport", () => { vi.stubGlobal("fetch", fetcher); const choices = await new Oblien({ token: "fixture-token" }).listOutboundIps(); expect(choices).toEqual([{ ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: null }]); - expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/zone/mine"); + expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/v1/zone/mine"); expect(JSON.stringify(choices)).not.toMatch(/pool-user|pool-password|private-id/); }); it("rejects an unreadable pool instead of presenting a successful empty picker", async () => { @@ -40,13 +40,13 @@ describe("Oblien SDK transport", () => { it("propagates an HTTP quota refusal even without success:false", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "NAMESPACE_LIMIT_REACHED" }, { status: 409 }))); const client = new Oblien({ token: "scoped-test-token" }); - const error = await client.workspaces.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error); + const error = await client.vms.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error); expect(error).toMatchObject({ status: 409, code: "NAMESPACE_LIMIT_REACHED" }); expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: true, rejected: true }); }); it("rejects an error HTTP status even when a payload claims success", async () => { - vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, workspace: { id: "not-created" } }, { status: 503 }))); - await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 }); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, vm: { id: "not-created" } }, { status: 503 }))); + await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 }); }); it.each(["NAMESPACE_LIMIT_REACHED", "SANDBOX_LIMIT_REACHED", "POOL_LIMIT_REACHED"])( "normalizes the provider's HTTP 200 %s refusal", @@ -56,31 +56,31 @@ describe("Oblien SDK transport", () => { vi.fn(async () => Response.json({ valid: false, error: "capacity exceeded", code })), ); await expect( - new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }), + new Oblien({ token: "test" }).vms.create({ wait_ready: false }), ).rejects.toMatchObject({ status: 409, code }); }, ); it("keeps official request formatting and never follows authenticated redirects", async () => { - const fetcher = vi.fn(async () => Response.json({ success: true, workspace: { id: "ws-a", namespace: "tenant-a" } })); + const fetcher = vi.fn(async () => Response.json({ success: true, vm: { id: "ws-a", namespace: "tenant-a" } })); vi.stubGlobal("fetch", fetcher); const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" }); - await client.workspaces.create({ namespace: "tenant-a", cpus: 2, wait_ready: false }); + await client.vms.create({ namespace: "tenant-a", cpus: 2, wait_ready: false }); const [url, init] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit]; - expect(url.pathname).toBe("/workspace"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal); + expect(url.pathname).toBe("/v1/vms"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal); expect(JSON.parse(init.body as string)).toMatchObject({ namespace: "tenant-a", config: { cpus: 2 } }); }); it("tracks token refresh and authentication restore without mixing scopes", async () => { const headers: Headers[] = []; - vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, workspaces: [] }); })); + vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, vms: [] }); })); const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" }); - await client.workspaces.list(); client.setToken("namespace-token"); await client.workspaces.list(); client._http.restoreAuth(); await client.workspaces.list(); + await client.vms.list(); client.setToken("namespace-token"); await client.vms.list(); client._http.restoreAuth(); await client.vms.list(); expect(headers[0]!.get("X-Client-ID")).toBe("test-owner"); expect(headers[1]!.get("Authorization")).toBe("Bearer namespace-token"); expect(headers[1]!.has("X-Client-Secret")).toBe(false); expect(headers[2]!.get("X-Client-ID")).toBe("test-owner"); expect(headers[2]!.has("Authorization")).toBe(false); }); it("does not expose provider error details or tokens", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "scope_denied", message: "private-secret", details: { token: "private-secret" } }, { status: 403 }))); - const error = await new Oblien({ token: "test" }).workspaces.get("ws-b").catch(error => error); + const error = await new Oblien({ token: "test" }).vms.get("ws-b").catch(error => error); expect(error.message).not.toContain("private-secret"); expect(error.details).toBeUndefined(); expect(error.status).toBe(403); expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: false, rejected: true }); }); @@ -108,7 +108,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error).toMatchObject({ @@ -159,7 +159,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error.details.violations).toEqual([ @@ -212,7 +212,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error.details).toBeUndefined(); @@ -228,7 +228,7 @@ describe("Oblien SDK transport", () => { code: "CREATE_FAILED", message: "private-account-data", details: { - workspace_id: "ws-failed", + vm_id: "ws-failed", token: "private-secret", workspace: { env: { SECRET: "private-secret" } }, }, @@ -237,13 +237,13 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error).toMatchObject({ status: 422, code: "CREATE_FAILED", - details: { workspace_id: "ws-failed" }, + details: { vm_id: "ws-failed" }, }); expect(cloudWorkspaceCreationFailure(error)).toEqual({ workspaceId: "ws-failed", capacityRejected: false, rejected: false }); expect(JSON.stringify(error)).not.toContain("private-"); @@ -257,7 +257,7 @@ describe("Oblien SDK transport", () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: code, message: "private-account-data", details: { violations: ["private-namespace-name"] }, }, { status: 400 }))); - const error = await new Oblien({ token: "scoped-test-token" }).workspaces.get("ws-a").catch(error => error); + const error = await new Oblien({ token: "scoped-test-token" }).vms.get("ws-a").catch(error => error); expect(error).toMatchObject({ status: 400, code }); expect(error.message).toContain(description); expect(error.message).not.toContain("private-"); @@ -272,7 +272,7 @@ describe("Oblien SDK transport", () => { const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher); const controller = new AbortController(); const reason = new Error("Deployment cancelled"); controller.abort(reason); - await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason); + await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason); expect(fetcher).not.toHaveBeenCalled(); }); it("preserves SDK cancellation during a request instead of returning a retryable provider error", async () => { @@ -283,7 +283,7 @@ describe("Oblien SDK transport", () => { }))); const controller = new AbortController(); const reason = new Error("Deployment cancelled"); - const pending = new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal }); + const pending = new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal }); const result = expect(pending).rejects.toBe(reason); controller.abort(reason); await result; diff --git a/packages/adapters/src/oblien.ts b/packages/adapters/src/oblien.ts index 530ad51ad..8d6467f14 100644 --- a/packages/adapters/src/oblien.ts +++ b/packages/adapters/src/oblien.ts @@ -1,4 +1,5 @@ import { workspaceMetricsStream } from "./oblien-metrics"; +import { oblienApiBaseUrl, oblienApiUrl } from "./oblien-contract"; import { diagnosticTraceparent, reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; import { withDiagnosticSpan } from "@repo/core/diagnostics/node"; import { @@ -36,13 +37,13 @@ const resourceUnits = { cpus: "vCPU", memory_mb: "MB", disk_size_mb: "MB", - workspaces: "workspaces", + vms: "VMs", } as const; const resourceLabels = { cpus: "CPU", memory_mb: "RAM", disk_size_mb: "Disk", - workspaces: "Workspaces", + vms: "VMs", } as const; type CapacityViolation = { resource: keyof typeof resourceUnits; @@ -91,7 +92,7 @@ function namespaceCapacityDetails(raw: unknown) { } function workspaceIdFromDetails(details: unknown): string | undefined { - const id = (details as { workspace_id?: unknown } | null)?.workspace_id; + const id = (details as { vm_id?: unknown } | null)?.vm_id; return typeof id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(id) ? id : undefined; } @@ -140,7 +141,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null const retryAfterSeconds = Number.isSafeInteger(delay) && delay >= 0 && delay <= 86400 ? delay : undefined; const details = capacity || workspaceId || retryAfterSeconds !== undefined ? { ...capacity, - ...(workspaceId ? { workspace_id: workspaceId } : {}), + ...(workspaceId ? { vm_id: workspaceId } : {}), ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}), } : undefined; const requestId = @@ -153,7 +154,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null const scope = value.enforcementScope === "namespace_allocated_pool" ? "namespace total" - : value.resource === "workspaces" + : value.resource === "vms" ? "namespace workspace count" : "per workspace"; return ( @@ -219,11 +220,7 @@ export class Oblien extends OblienSdk { invalidate?(rejectedToken: string): Promise; }; }) { - const base = new URL(options.baseUrl ?? "https://api.oblien.com"); - if (base.username || base.password || base.search || base.hash || - (base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)))) { - throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); - } + const base = oblienApiBaseUrl(options.baseUrl); super(options); const original = new Headers(); if ("token" in options) { if (options.token) original.set("Authorization", `Bearer ${options.token}`); } @@ -262,7 +259,7 @@ export class Oblien extends OblienSdk { const renewal = ensureAuth(); if (renewal) await renewal; subscriptionSignal.throwIfAborted(); - const url = new URL(`/workspace/${encodeURIComponent(workspaceId)}/stats/stream`, base); + const url = oblienApiUrl(base, `/vms/${encodeURIComponent(workspaceId)}/stats/stream`); const headers = new Headers(auth); headers.set("Accept", "text/event-stream"); const response = await fetch(url, { headers, redirect: "error", signal: subscriptionSignal }); @@ -271,7 +268,7 @@ export class Oblien extends OblienSdk { }, signal); this._http.request = async (request: RequestOptions): Promise => withDiagnosticSpan({ kind: "operation", component: "oblien", operation: "oblien.request", method: request.method }, async () => { request.signal?.throwIfAborted(); - const url = new URL(request.path, base); + const url = oblienApiUrl(base, request.path); if (url.origin !== base.origin || url.username || url.password) throw new Error("Oblien request escaped its API origin"); const renewal = ensureAuth(); if (renewal) await renewal; @@ -284,7 +281,7 @@ export class Oblien extends OblienSdk { headers.set("Accept", "application/json"); headers.set("Content-Type", "application/json"); for (const [key, value] of auth) headers.set(key, value); - const waitingCreate = request.method === "POST" && /^\/workspace\/?$/.test(url.pathname) && + const waitingCreate = request.method === "POST" && /^\/vms\/?$/.test(request.path) && (request.body as { wait_ready?: boolean } | undefined)?.wait_ready !== false; let response: Response; let body: unknown; @@ -323,13 +320,11 @@ export class Oblien extends OblienSdk { } return body as T; }, { kind: "client" }); - // SDK 2.5 types get() as WorkloadInfo but leaves the HTTP envelope intact, - // unlike create() and list(). Normalize at the provider boundary so process - // control and server-resize recovery read the same saved workload record. - const getWorkload = this.workspaces.workloads.get.bind(this.workspaces.workloads); - this.workspaces.workloads.get = async (workspaceId, workloadId) => { + // Validate the native record before process control and resize recovery. + const getWorkload = this.vms.workloads.get.bind(this.vms.workloads); + this.vms.workloads.get = async (workspaceId, workloadId) => { const response = await getWorkload(workspaceId, workloadId); - const workload = response.workload ?? response; + const workload = response; if (!workload || typeof workload !== "object" || Array.isArray(workload) || !("id" in workload) || typeof workload.id !== "string") { throw new OblienError("Oblien returned an invalid application process record", 502, "OBLIEN_WORKLOAD_INVALID"); diff --git a/packages/adapters/src/runtime/cloud-deploy-static.test.ts b/packages/adapters/src/runtime/cloud-deploy-static.test.ts index 155b826e3..c06209b7a 100644 --- a/packages/adapters/src/runtime/cloud-deploy-static.test.ts +++ b/packages/adapters/src/runtime/cloud-deploy-static.test.ts @@ -6,7 +6,7 @@ beforeEach(() => { h = managedRoutingFixture(); }); describe("shared static releases on managed ingress", () => { it.each([".", "dist"])("normalizes %s under its owned release and exports only the project route tree", async output => { await h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-a/${output}`, tls: true }); - expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ workspace_id: h.workspaceId, path: `${h.paths.routes}/site` })); + expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ vm_id: h.workspaceId, path: `${h.paths.routes}/site` })); expect(h.scope.resolveUrl).not.toHaveBeenCalled(); expect(h.routes.set).toHaveBeenCalledOnce(); }); @@ -33,7 +33,7 @@ describe("shared static releases on managed ingress", () => { h.routes.set.mockRejectedValueOnce(new Error("route table unavailable")); await expect(h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-b`, tls: true })).rejects.toThrow("route table unavailable"); expect(h.pages.deploy).toHaveBeenCalledTimes(2); - expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { workspace_id: h.workspaceId, path: `${h.paths.routes}/site` }); + expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { vm_id: h.workspaceId, path: `${h.paths.routes}/site` }); }); }); @@ -48,7 +48,7 @@ it("switches a live proxy hostname to exported files and back without claiming a }); expect(h.records.get("site")).toBe(page); expect(h.pages.deploy).toHaveBeenCalledWith("site", { - workspace_id: h.workspaceId, + vm_id: h.workspaceId, path: `${h.paths.routes}/site`, }); expect(JSON.stringify(h.routes.set.mock.lastCall)).toContain('"static"'); diff --git a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts index ae6213923..bca0b073f 100644 --- a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts +++ b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts @@ -16,7 +16,7 @@ const config = { target: "cloud" as const, cloudToken: "namespace-token", cloudN beforeEach(() => { const row = { id: "vm-a", namespace: "namespace-a", status: "running" }; - fixture.client = { workspace: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), workspaces: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } }; + fixture.client = { vm: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), vms: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } }; }); afterEach(async () => { for (const platform of platforms.splice(0)) await platform.runtime.dispose?.(); @@ -35,13 +35,13 @@ describe("Cloud changes the execution destination, not the deployment runtime", expect(platform.executor).toBeInstanceOf(CloudWorkspaceExecutor); expect(platform.localHost).toBe(false); expect(platform.system).toBeNull(); - expect(fixture.client.workspaces.create).not.toHaveBeenCalled(); + expect(fixture.client.vms.create).not.toHaveBeenCalled(); }); it("has no implicit host when a Cloud destination is absent", async () => { const platform = await make({ cloudServer: undefined }); await expect(platform.runtime.build({ projectId: "project-a", buildStrategy: "local" } as never)).rejects.toMatchObject({ code: "DEPLOYMENT_SERVER_REQUIRED" }); expect(platform.executor).toBeNull(); - expect(fixture.client.workspace).not.toHaveBeenCalled(); + expect(fixture.client.vm).not.toHaveBeenCalled(); }); it.each(["docker", "bare"] as const)("requires namespace-scoped credentials for %s", async runtime => { await expect(make({ runtime, cloudToken: undefined })).rejects.toThrow("organization-scoped credentials"); @@ -52,14 +52,14 @@ describe("Cloud changes the execution destination, not the deployment runtime", const transfer = vi.spyOn(platform.executor!, "transferIn"); await expect(platform.runtime.build({ projectId: "project-a", localPath: "/etc", buildStrategy: "local" } as never)).rejects.toThrow(/control-plane|host/i); expect(transfer).not.toHaveBeenCalled(); - expect(fixture.client.workspaces.create).not.toHaveBeenCalled(); + expect(fixture.client.vms.create).not.toHaveBeenCalled(); }); it("resolves bare process ports without opening Docker and rejects sibling ports", async () => { const workloads = [ { id: "openship-release-a", labels: { "openship.project": "project-a", "openship.deployment": "release-a", "openship.ports": "[3000]" } }, { id: "openship-release-b", labels: { "openship.project": "project-b", "openship.deployment": "release-b", "openship.ports": "[4000]" } }, ]; - fixture.client.workspace.mockReturnValue({ workloads: { list: async () => workloads } }); + fixture.client.vm.mockReturnValue({ workloads: { list: async () => workloads } }); const connection = new CloudServerConnection(fixture.client, { workspaceId: server.workspaceId, namespace: config.cloudNamespace }); const containers = vi.fn(async () => ({ resolveUrl: async () => { throw new Error("unowned port"); }, resolveTarget: vi.fn() })); const scope = managedProjectRoutingScope(connection, server, containers); diff --git a/packages/adapters/src/runtime/cloud/docker.test.ts b/packages/adapters/src/runtime/cloud/docker.test.ts index ad9e34fb9..9be7fe688 100644 --- a/packages/adapters/src/runtime/cloud/docker.test.ts +++ b/packages/adapters/src/runtime/cloud/docker.test.ts @@ -54,13 +54,13 @@ beforeEach(async () => { if (!page) throw new NotFoundError("missing"); return { page }; }), - create: vi.fn(async (input: { slug: string; workspace_id: string; path: string }) => { - const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_workspace_id: input.workspace_id, exported_path: input.path }; + create: vi.fn(async (input: { slug: string; vm_id: string; path: string }) => { + const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_vm_id: input.vm_id, exported_path: input.path }; pageRows.set(input.slug, page); return { page }; }), enable: vi.fn(async () => ({ success: true })), connectDomain: vi.fn(), delete: vi.fn(async () => ({ success: true })), }; - provider = { workspace: vi.fn(() => ws), workspaces: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages }; + provider = { vm: vi.fn(() => ws), vms: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages }; runtime = await CloudDockerRuntime.forWorkspace(provider as unknown as Oblien, { projectId: "project-a", ownerWorkspaceId: "managed-a", workspaceId: "workspace-a", namespace: "namespace-a", beforeProvision: async () => { await spend(); }, provisionLock: { run: fn => fn() }, resolveRegistryAuth: async () => undefined, @@ -145,7 +145,7 @@ describe("containers on one Oblien Docker workspace", () => { const options = { projectId: "project-a", serviceName: "api", onReplaced: vi.fn() }; await expect(runtime.applyEnvironment("container-a", { VALUE: "new" }, options)).resolves.toEqual({ containerId: "replacement-a" }); expect(apply).toHaveBeenCalledExactlyOnceWith("container-a", { VALUE: "new" }, options); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); expect(ws.restart).not.toHaveBeenCalled(); expect(ws.delete).not.toHaveBeenCalled(); expect(spend).toHaveBeenCalled(); @@ -356,8 +356,8 @@ describe("containers on one Oblien Docker workspace", () => { expect(first.hostPortByContainerPort![8080]).not.toBe(first.hostPortByContainerPort![9090]); expect(next.hostPortByContainerPort![8080]).toBe(first.hostPortByContainerPort![8080]); await infra.publishRoute("project-a.opsh.io", next.hostPortByContainerPort![8080]!, false); - expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", workspace: "workspace-a", port: next.hostPortByContainerPort![8080] } })] })); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", vm: "workspace-a", port: next.hostPortByContainerPort![8080] } })] })); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("keeps named and image-declared volume identities across container replacements", async () => { await runtime.deployServiceWorkload(group, config); @@ -496,7 +496,7 @@ describe("containers on one Oblien Docker workspace", () => { expect(ws.delete).not.toHaveBeenCalled(); }); it("does not take over another project's hostname in the same organization", async () => { - pageRows.set("project-a", { namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/app" }); + pageRows.set("project-a", { namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/app" }); const result = await runtime.deployServiceWorkload(group, config); await expect(infra.publishRoute("project-a.opsh.io", result.hostPortByContainerPort![8080]!, false)).rejects.toThrow(/owned|belong/); expect(pages.enable).not.toHaveBeenCalled(); @@ -549,7 +549,7 @@ describe("containers on one Oblien Docker workspace", () => { const failure = Object.assign(new Error("Provider unavailable"), { status: 503 }); ws.get.mockRejectedValue(failure); await expect(runtime.listAllContainers()).rejects.toBe(failure); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("refuses another namespace's container inventory", async () => { ws.get.mockResolvedValue({ namespace: "another-namespace", status: "running" }); @@ -603,7 +603,7 @@ describe("containers on one Oblien Docker workspace", () => { adminProxy: { pages: pages as never, domainRoutes: async () => ({ data: [{ hostname: "project-a.opsh.io", namespace: "namespace-a", owner_type: "page", owner_id: "project-a" }] }) as never } }); await cleanup.removeRoute("project-a.opsh.io"); expect(pages.delete).toHaveBeenCalledWith("project-a"); - pageRows.get("project-a")!.source_workspace_id = "workspace-other"; + pageRows.get("project-a")!.source_vm_id = "workspace-other"; await expect(cleanup.removeRoute("project-a.opsh.io")).rejects.toThrow("not owned"); }); it("inventories disabled routing Pages without confusing their numeric IDs with slugs", async () => { @@ -611,7 +611,7 @@ describe("containers on one Oblien Docker workspace", () => { Ports: [{ PrivatePort: 8080, PublicPort: 30001, Type: "tcp" }] }]; await infra.publishRoute("project-a.opsh.io", 30001, false); pageRows.get("project-a")!.status = "disabled"; - pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" }); + pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" }); expect(await infra.listProjectRouteHostnames()).toEqual(["project-a.opsh.io"]); const cleanup = new CloudInfraProvider(provider as unknown as Oblien, { namespace: "namespace-a", scope: runtime.routingScope() }); await cleanup.removeRoute("project-a.opsh.io"); @@ -707,7 +707,7 @@ describe("containers on one Oblien Docker workspace", () => { expect(dockerfile).toContain("OPENSHIP_BUILD_PACKAGE_MANAGER_VERSION='1.4.4'"); expect(transfer).not.toHaveBeenCalled(); expect(runtime.connectionOptions?.executor).toBe(runtime.executor); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("does not let an empty image-only source mask a later inline build context", async () => { const source = { projectId: "project-a", sessionId: "build-a", repoUrl: "" }; diff --git a/packages/adapters/src/runtime/cloud/docker.ts b/packages/adapters/src/runtime/cloud/docker.ts index 6f1023f13..7c3d33f17 100644 --- a/packages/adapters/src/runtime/cloud/docker.ts +++ b/packages/adapters/src/runtime/cloud/docker.ts @@ -789,7 +789,7 @@ export class CloudDockerRuntime extends DockerRuntime { }; } override async listAllContainers() { - const workspace = await this.client.workspaces.get(this.workspaceId); + const workspace = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId); assertCloudWorkspaceRunning(workspace); const containers = await super.listAllContainers(); @@ -802,7 +802,7 @@ export class CloudDockerRuntime extends DockerRuntime { throw new Error("A Docker workspace is not a service container"); let workspace; try { - workspace = await this.client.workspaces.get(this.workspaceId); + workspace = await this.client.vms.get(this.workspaceId); } catch (error) { if (notFound(error)) return { containerId, status: "missing" }; throw error; @@ -841,7 +841,7 @@ export class CloudDockerRuntime extends DockerRuntime { override async stop(containerId: string) { if (containerId === this.workspaceId) throw new Error("A Docker workspace is not a service container"); - const workspace = await this.client.workspaces.get(this.workspaceId); + const workspace = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId); if (!isDockerWorkspaceRunning(workspace)) return; return super.stop(containerId); diff --git a/packages/adapters/src/runtime/cloud/server-connection.ts b/packages/adapters/src/runtime/cloud/server-connection.ts index 3dd7ac665..a55a2dc8f 100644 --- a/packages/adapters/src/runtime/cloud/server-connection.ts +++ b/packages/adapters/src/runtime/cloud/server-connection.ts @@ -60,7 +60,7 @@ export function managedProcessState(workload: WorkloadInfo): ContainerStatus { /** Workload GET is saved configuration and can retain an old state after a VM * restart. The provider's status endpoint is the live process authority. */ export async function readManagedProcessStatus( - workloads: ReturnType["workloads"], + workloads: ReturnType["workloads"], saved: WorkloadInfo, ): Promise { let result: Awaited>; @@ -147,7 +147,7 @@ export class CloudServerConnection { } workspace() { - return this.client.workspace(this.workspaceId); + return this.client.vm(this.workspaceId); } runtime(options?: { force?: boolean }): Promise { @@ -230,7 +230,7 @@ export class CloudServerConnection { private ensureBridge(): Promise { const initialize = async () => { - const info = await this.client.workspaces.get(this.workspaceId); + const info = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(info, this.options.namespace, this.workspaceId); assertCloudWorkspaceRunning(info); let runtime = await this.runtime(); @@ -263,7 +263,7 @@ export class CloudServerConnection { try { // Refresh only through this namespace's existing client. A revoked // namespace credential must still fail the control-plane check. - runtime = await this.client.workspace(this.workspaceId).runtime({ force: true }); + runtime = await this.client.vm(this.workspaceId).runtime({ force: true }); } catch (diagnosticFailure) { observeCaughtError(diagnosticFailure, "adapters/runtime/cloud/server-connection"); throw new AppError( @@ -304,7 +304,7 @@ export class CloudServerConnection { // A modified image missing it must fail at that boundary, not attempt to // bootstrap Python through the transport which already requires it. await this.executor.writeFile(BRIDGE_SCRIPT, CLOUD_DOCKER_BRIDGE_SOURCE, { mode: 0o700 }); - const workspace = this.client.workspace(this.workspaceId); + const workspace = this.client.vm(this.workspaceId); const workload = (await workspace.workloads.list({ name: BRIDGE_WORKLOAD })).find( (item) => item.name === BRIDGE_WORKLOAD, ); @@ -354,7 +354,7 @@ export class CloudServerConnection { async resume(): Promise { await this.options.beforeProvision?.(); - const ws = this.client.workspace(this.workspaceId); + const ws = this.client.vm(this.workspaceId); const data = await ws.get(); assertDockerWorkspaceOwner(data, this.options.namespace, this.workspaceId); if (isDockerWorkspaceRunning(data)) return; diff --git a/packages/adapters/src/runtime/cloud/workspace-delete.ts b/packages/adapters/src/runtime/cloud/workspace-delete.ts index a6cbca3c9..507616a0c 100644 --- a/packages/adapters/src/runtime/cloud/workspace-delete.ts +++ b/packages/adapters/src/runtime/cloud/workspace-delete.ts @@ -1,10 +1,10 @@ import { setTimeout as delay } from "node:timers/promises"; -import type { WorkspaceHandle } from "oblien"; +import type { VMHandle } from "oblien"; /** An accepted deletion is still running on Oblien. Keep local cleanup pending * until the scoped resource is absent; a failed read must not erase ownership. */ export async function deleteCloudWorkspace( - workspace: Pick, + workspace: Pick, options: { timeoutMs?: number } = {}, ): Promise { try { diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts index 4a4b7e426..421cf754b 100644 --- a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts +++ b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts @@ -8,7 +8,7 @@ describe("Docker workspace readiness", () => { vi.useFakeTimers(); const get = vi.fn().mockResolvedValueOnce({ id: "owned-vm", namespace: "tenant", ...state, ready: false, provisioning: { state: "running" } }) .mockResolvedValue({ id: "owned-vm", namespace: "tenant", ...state, ready: true, provisioning: { state: "ready" } }); - const waiting = waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "owned-vm", "tenant"); + const waiting = waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "owned-vm", "tenant"); await vi.advanceTimersByTimeAsync(1000); await expect(waiting).resolves.toMatchObject({ ready: true }); expect(get).toHaveBeenCalledTimes(2); @@ -16,25 +16,25 @@ describe("Docker workspace readiness", () => { }); it("uses the live VM state even while the workspace record remains active", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "active", info: { status: "stopped" }, provisioning: { state: "ready" } }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting"); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting"); expect(cloudWorkspaceStatus({ status: "active", info: { is_running: false } })).toBe("stopped"); expect(cloudWorkspaceStatus({ status: "active", info: { is_running: true } })).toBe("running"); }); it("rejects a changed namespace even when the VM is ready", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "other-tenant", status: "active", ready: true }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); }); it("rejects a different server in the same namespace before using its state", async () => { const get = vi.fn().mockResolvedValue({ id: "different-vm", namespace: "tenant", status: "running", ready: true }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); }); it("surfaces a failed provisioning attempt without creating a replacement", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "error", provisioning: { state: "failed" } }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk"); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk"); }); it("cancels the wait before another provider read", async () => { const get = vi.fn(); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow(); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow(); expect(get).not.toHaveBeenCalled(); }); }); diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.ts b/packages/adapters/src/runtime/cloud/workspace-ready.ts index de1010f56..2daf9c604 100644 --- a/packages/adapters/src/runtime/cloud/workspace-ready.ts +++ b/packages/adapters/src/runtime/cloud/workspace-ready.ts @@ -1,8 +1,8 @@ import { setTimeout as delay } from "node:timers/promises"; -import type { Oblien, WorkspaceData } from "oblien"; +import type { Oblien, VMData } from "oblien"; import { AppError } from "@repo/core"; -export function assertDockerWorkspaceOwner(workspace: WorkspaceData, namespace: string, workspaceId: string): void { +export function assertDockerWorkspaceOwner(workspace: VMData, namespace: string, workspaceId: string): void { if (workspace.namespace !== namespace || workspace.id !== workspaceId) throw new AppError("Cloud workspace identity does not match its server", 502, "CLOUD_SERVER_IDENTITY_MISMATCH"); } @@ -20,7 +20,7 @@ export function isDockerWorkspaceRunning(workspace: { status: string; info?: unk return cloudWorkspaceStatus(workspace) === "running"; } -export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void { +export function assertCloudWorkspaceRunning(workspace: VMData): void { const state = cloudWorkspaceStatus(workspace); if (state === "running") return; if (["stopped", "paused", "suspended"].includes(state)) @@ -35,7 +35,7 @@ export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void { export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: string, namespace: string) { const deadline = Date.now() + 60_000; for (;;) { - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); assertDockerWorkspaceOwner(workspace, namespace, workspaceId); if (["stopped", "paused", "suspended"].includes(cloudWorkspaceStatus(workspace))) return; if (Date.now() >= deadline) throw new Error("The managed server has not returned to its stopped state"); @@ -47,11 +47,11 @@ export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: export async function waitForCloudDockerWorkspace( client: Oblien, workspaceId: string, namespace: string, options: { signal?: AbortSignal; timeoutMs?: number } = {}, -): Promise { +): Promise { const deadline = Date.now() + (options.timeoutMs ?? 600_000); while (true) { options.signal?.throwIfAborted(); - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); assertDockerWorkspaceOwner(workspace, namespace, workspaceId); const provisioning = workspace.provisioning as { state?: string; error?: unknown } | undefined; if (provisioning?.state === "failed" || ["error", "failed"].includes(cloudWorkspaceStatus(workspace))) { diff --git a/packages/adapters/src/runtime/cloud/workspace-resources.ts b/packages/adapters/src/runtime/cloud/workspace-resources.ts index e6440d18e..627e4a124 100644 --- a/packages/adapters/src/runtime/cloud/workspace-resources.ts +++ b/packages/adapters/src/runtime/cloud/workspace-resources.ts @@ -1,4 +1,4 @@ -import type { WorkspaceData, WorkspaceHandle } from "oblien"; +import type { VMData, VMHandle } from "oblien"; import { cloudCpus, type ResourceConfig } from "../../types"; import { cloudWorkspaceStatus } from "./workspace-ready"; @@ -6,7 +6,7 @@ type WorkspaceResources = Pick & Partial>; export function cloudWorkspaceHasResources( - workspace: Pick, + workspace: Pick, expected: WorkspaceResources, ): boolean { const actual = workspace.resources; @@ -21,9 +21,9 @@ export function cloudWorkspaceHasResources( * Require an applied change and read the allocation back before claiming the * runtime was resized. Callers retain ownership of readiness and restoration. */ export async function updateCloudWorkspaceResources( - workspace: WorkspaceHandle, + workspace: VMHandle, resources: WorkspaceResources, - current?: WorkspaceData, + current?: VMData, ): Promise { const before = current ?? (await workspace.get()); if (before.id !== workspace.id) diff --git a/packages/adapters/src/runtime/oblien-routing.ts b/packages/adapters/src/runtime/oblien-routing.ts index 6a232b1d1..542192084 100644 --- a/packages/adapters/src/runtime/oblien-routing.ts +++ b/packages/adapters/src/runtime/oblien-routing.ts @@ -18,12 +18,12 @@ import type { RoutingConfig } from "@repo/core"; import { compileVercelRouting, type CompiledRouting } from "../infra/vercel-routing"; /** Sentinel so reused `compileVercelRouting` marks which proxy targets are the - * owned backend (→ Oblien `workspace`+`port`) vs. a literal external URL. */ + * owned backend (→ Oblien `vm`+`port`) vs. a literal external URL. */ const BACKEND_SENTINEL = "oblien-backend://self"; -/** An owned Oblien workspace to reverse-proxy to. */ -export interface OblienWorkspaceTarget { - workspace: string; +/** An owned Oblien VM to reverse-proxy to. */ +export interface OblienVmTarget { + vm: string; port: number; } @@ -34,11 +34,11 @@ export interface OblienRoutingContext { /** Workspace backing `/` when the frontend runs as a container instead of a * Page (a catch-all `/` proxy is appended last). Mutually exclusive with * `staticPage`. Also the server-only shape: set `root`, omit `backend`. */ - root?: OblienWorkspaceTarget; + root?: OblienVmTarget; /** Backend workspace that path rewrites (e.g. `/api/*`) proxy to. */ - backend?: OblienWorkspaceTarget; + backend?: OblienVmTarget; /** Resolved internal URLs, shared by the generic route-registration path. */ - proxyTargets?: ReadonlyMap; + proxyTargets?: ReadonlyMap; } /** Oblien only accepts 301/302/307/308; coerce anything else to a safe default @@ -51,7 +51,7 @@ function toOblienRedirectStatus(code: number): 301 | 302 | 307 | 308 { export function compileRoutingToOblien( routing: RoutingConfig, ctx: OblienRoutingContext = {}, -): RoutesInput { +): RoutesInput & { routes: RouteRule[] } { const compiled = compileVercelRouting(routing, { backendTargetUrl: ctx.backend ? BACKEND_SENTINEL : undefined, }); @@ -63,7 +63,7 @@ export function compileRoutingToOblien( export function compileResolvedRoutingToOblien( compiled: Pick, ctx: OblienRoutingContext = {}, -): RoutesInput { +): RoutesInput & { routes: RouteRule[] } { const routes: RouteRule[] = []; // Terminal rules are first-match-wins, evaluated before static files; order @@ -88,7 +88,7 @@ export function compileResolvedRoutingToOblien( for (const loc of compiled.proxyLocations) { const owned = loc.targetUrl === BACKEND_SENTINEL ? ctx.backend : ctx.proxyTargets?.get(loc.targetUrl); const action: RouteProxyAction = owned - ? { kind: "proxy", workspace: owned.workspace, port: owned.port } + ? { kind: "proxy", vm: owned.vm, port: owned.port } : { kind: "proxy", origin: loc.targetUrl }; // A capture-bearing rewrite carries its upstream path as a `$1..$9` template — // exactly what `RouteProxyAction.path` takes, against a `wildcard` match. @@ -107,7 +107,7 @@ export function compileResolvedRoutingToOblien( if (ctx.root) { routes.push({ match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: ctx.root.workspace, port: ctx.root.port }, + action: { kind: "proxy", vm: ctx.root.vm, port: ctx.root.port }, }); } @@ -118,7 +118,7 @@ export function compileResolvedRoutingToOblien( }); } - const input: RoutesInput = { routes }; + const input: RoutesInput & { routes: RouteRule[] } = { routes }; if (ctx.staticPage) { input.static = { page: ctx.staticPage }; if (compiled.spaFallback !== undefined) input.spa = compiled.spaFallback; diff --git a/packages/adapters/src/runtime/transfer.ts b/packages/adapters/src/runtime/transfer.ts index f5a80b487..a630ce5a5 100644 --- a/packages/adapters/src/runtime/transfer.ts +++ b/packages/adapters/src/runtime/transfer.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; -import type { WorkspaceHandle } from "oblien"; +import type { VMHandle } from "oblien"; import { TRANSFER_EXCLUDES, safeErrorMessage } from "@repo/core"; import { getTarCreateEnv, prepareSourceTarArgs } from "../archive"; @@ -24,7 +24,7 @@ export type LocalDirectoryTarget = } | { kind: "cloud-runtime"; - runtime: Awaited>; + runtime: Awaited>; path: string; }; diff --git a/packages/adapters/test/cloud-infra.test.ts b/packages/adapters/test/cloud-infra.test.ts index 6fede0853..170cdb457 100644 --- a/packages/adapters/test/cloud-infra.test.ts +++ b/packages/adapters/test/cloud-infra.test.ts @@ -23,7 +23,7 @@ describe("managed route cleanup", () => { await h.infra.removeRoute("app.opsh.io"); expect(h.pages.delete).toHaveBeenCalledWith("app"); }); - it.each(["source_workspace_id", "exported_path"])("refuses cleanup after %s changes", async field => { + it.each(["source_vm_id", "exported_path"])("refuses cleanup after %s changes", async field => { h.records.get("app")![field] = "another-owner"; await expect(h.infra.removeRoute("app.opsh.io")).rejects.toThrow("not owned"); expect(h.pages.delete).not.toHaveBeenCalled(); diff --git a/packages/adapters/test/cloud-project-route-cleanup.test.ts b/packages/adapters/test/cloud-project-route-cleanup.test.ts index c2d1b7605..98284162c 100644 --- a/packages/adapters/test/cloud-project-route-cleanup.test.ts +++ b/packages/adapters/test/cloud-project-route-cleanup.test.ts @@ -17,7 +17,7 @@ describe("project-scoped route cleanup", () => { it.each(["workspace-one", "another-workspace"])( "preserves a different project's Page on %s while explicit removal stays strict", async (workspaceId) => { - h.records.get("app")!.source_workspace_id = workspaceId; + h.records.get("app")!.source_vm_id = workspaceId; h.records.get("app")!.exported_path = `${cloudDockerProjectPaths("active-project").routes}/app`; const activePage = structuredClone(h.records.get("app")); @@ -61,13 +61,13 @@ describe("project-scoped route cleanup", () => { }); it.each([ - { source_workspace_id: "another-workspace" }, + { source_vm_id: "another-workspace" }, { exported_path: undefined }, { exported_path: "/unrecognised-owner/app" }, { exported_path: `${cloudDockerProjectPaths("active-project").routes}/wrong-slug` }, { exported_path: `${cloudDockerProjectPaths("active-project").routes}/app`, - source_workspace_id: null, + source_vm_id: null, }, ])("blocks deletion when foreign ownership is unproven: %j", async (changes) => { Object.assign(h.records.get("app")!, changes); diff --git a/packages/adapters/test/managed-routing-fixture.ts b/packages/adapters/test/managed-routing-fixture.ts index 5521a4611..6123076b7 100644 --- a/packages/adapters/test/managed-routing-fixture.ts +++ b/packages/adapters/test/managed-routing-fixture.ts @@ -26,8 +26,8 @@ export function managedRoutingFixture(): { if (!records.has(slug)) throw new NotFoundError("missing Page"); return { page: records.get(slug)! }; }), - create: vi.fn(async (input: { slug: string; domain: string; path: string; workspace_id: string }) => { - const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_workspace_id: input.workspace_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` }; + create: vi.fn(async (input: { slug: string; domain: string; path: string; vm_id: string }) => { + const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_vm_id: input.vm_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` }; records.set(input.slug, page); return { success: true, page }; }), deploy: vi.fn(async () => ({ success: true })), @@ -51,7 +51,7 @@ export function managedRoutingFixture(): { { hostname: `${page.slug}.${page.domain}`, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: false }, ...(page.custom_domain ? [{ hostname: page.custom_domain, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: true }] : []), ]) })) }; - const client = { pages, routes, domain, workspace: vi.fn(() => workspace) } as unknown as Oblien; + const client = { pages, routes, domain, vm: vi.fn(() => workspace) } as unknown as Oblien; const infra = new CloudInfraProvider(client, { namespace, scope }); return { namespace, workspaceId, projectId, paths, records, pages, executor, scope, workspace, routes, domain, client, infra }; } diff --git a/packages/adapters/test/oblien-routing.test.ts b/packages/adapters/test/oblien-routing.test.ts index 2f29cc418..dbaf58071 100644 --- a/packages/adapters/test/oblien-routing.test.ts +++ b/packages/adapters/test/oblien-routing.test.ts @@ -11,7 +11,7 @@ describe("compileRoutingToOblien", () => { { source: "/(.*)", destination: "/index.html" }, ], }, - { staticPage: "my-frontend", backend: { workspace: "ws_backend", port: 3000 } }, + { staticPage: "my-frontend", backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.static).toEqual({ page: "my-frontend" }); @@ -19,7 +19,7 @@ describe("compileRoutingToOblien", () => { expect(input.routes).toEqual([ { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: "ws_backend", port: 3000 }, + action: { kind: "proxy", vm: "ws_backend", port: 3000 }, }, ]); }); @@ -27,27 +27,27 @@ describe("compileRoutingToOblien", () => { it("builds a COMPLETE table for the workspace topology (frontend + backend both workspaces)", () => { const input = compileRoutingToOblien( { rewrites: [{ source: "/api/(.*)", destination: "/api/index.js" }] }, - { root: { workspace: "ws_frontend", port: 8080 }, backend: { workspace: "ws_backend", port: 3000 } }, + { root: { vm: "ws_frontend", port: 8080 }, backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.static).toBeUndefined(); // /api proxies to the backend; `/` catch-all proxies to the frontend LAST. expect(input.routes).toEqual([ - { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_backend", port: 3000 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_frontend", port: 8080 } }, + { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "ws_backend", port: 3000 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_frontend", port: 8080 } }, ]); }); it("builds a server-only table (root workspace backs everything)", () => { - const input = compileRoutingToOblien({}, { root: { workspace: "ws_api", port: 8080 } }); + const input = compileRoutingToOblien({}, { root: { vm: "ws_api", port: 8080 } }); expect(input.routes).toEqual([ - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_api", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_api", port: 8080 } }, ]); }); it("proxies a full-URL rewrite to a literal origin (not the owned workspace)", () => { const input = compileRoutingToOblien( { rewrites: [{ source: "/proxy/(.*)", destination: "https://api.example.com/fixed" }] }, - { backend: { workspace: "ws_backend", port: 3000 } }, + { backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.routes).toEqual([ { @@ -80,13 +80,13 @@ describe("compileRoutingToOblien", () => { { source: "/see", destination: "/other", statusCode: 303 }, // Oblien has no 303 → 307 ], }, - { root: { workspace: "ws_app", port: 8080 } }, + { root: { vm: "ws_app", port: 8080 } }, ); expect(input.routes).toEqual([ { match: { path: "/old", type: "exact" }, action: { kind: "redirect", status: 308, to: "/new" } }, { match: { path: "/tmp", type: "exact" }, action: { kind: "redirect", status: 307, to: "/temp" } }, { match: { path: "/see", type: "exact" }, action: { kind: "redirect", status: 307, to: "/other" } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } }, ]); }); @@ -101,7 +101,7 @@ describe("compileRoutingToOblien", () => { { source: "/docs/(.*)", destination: "/documentation/$1" }, ], }, - { root: { workspace: "ws_app", port: 8080 } }, + { root: { vm: "ws_app", port: 8080 } }, ); expect(input.routes).toEqual([ { @@ -112,7 +112,7 @@ describe("compileRoutingToOblien", () => { match: { path: "/docs/(.*)", type: "wildcard" }, action: { kind: "redirect", status: 308, to: "/documentation/$1" }, }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } }, ]); }); @@ -155,7 +155,7 @@ describe("compileRoutingToOblien", () => { rewrites: [{ source: "/evil; } location / { proxy_pass http://x; }", destination: "/api" }], redirects: [{ source: "/r", destination: "/y; return 200 'pwned'" }], }, - { backend: { workspace: "ws_backend", port: 3000 } }, + { backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.routes).toEqual([]); }); @@ -165,6 +165,6 @@ describe("compileRoutingToOblien", () => { describe("Cloud static fallback", () => { it.each([undefined, true, false])("carries the static setting to the provider: %s", (spaFallback) => { expect(compileRoutingToOblien({ spaFallback }, { staticPage: "site" }).spa).toBe(spaFallback); - expect(compileRoutingToOblien({ spaFallback }, { root: { workspace: "app", port: 8080 } })).not.toHaveProperty("spa"); + expect(compileRoutingToOblien({ spaFallback }, { root: { vm: "app", port: 8080 } })).not.toHaveProperty("spa"); }); }); diff --git a/packages/platform/src/engine/config/env.ts b/packages/platform/src/engine/config/env.ts index fe6eb4b37..5d94e18a9 100644 --- a/packages/platform/src/engine/config/env.ts +++ b/packages/platform/src/engine/config/env.ts @@ -375,7 +375,7 @@ const envSchema = z.object({ OBLIEN_CLIENT_ID: z.string().optional(), OBLIEN_CLIENT_SECRET: z.string().optional(), /** Control-plane endpoint. Override only for an Oblien staging installation. */ - OBLIEN_API_URL: z.url().default("https://api.oblien.com"), + OBLIEN_API_URL: z.url().optional(), OBLIEN_RUNTIME_URL: z.url().default("https://workspace.oblien.com"), /** Optional published software preset for NEW managed Docker workspaces. */ OBLIEN_DOCKER_PRESET: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(), diff --git a/packages/platform/src/engine/lib/cloud-capacity.ts b/packages/platform/src/engine/lib/cloud-capacity.ts index c651a5934..3c4696c2c 100644 --- a/packages/platform/src/engine/lib/cloud-capacity.ts +++ b/packages/platform/src/engine/lib/cloud-capacity.ts @@ -14,7 +14,7 @@ const workspaceResources = z.object({ /** One ownership/shape check for both previews and deployment admission. */ export async function readCloudWorkspaceAllocation(workspaceId: string, namespace: string) { - const workspace = await getOblienClient().workspaces.get(workspaceId); + const workspace = await getOblienClient().vms.get(workspaceId); if (workspace.id !== workspaceId || workspace.namespace !== namespace) { throw new AppError("Cloud workspace ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); } diff --git a/packages/platform/src/engine/lib/cloud-docker-workspace.ts b/packages/platform/src/engine/lib/cloud-docker-workspace.ts index b946e6500..65b9334d1 100644 --- a/packages/platform/src/engine/lib/cloud-docker-workspace.ts +++ b/packages/platform/src/engine/lib/cloud-docker-workspace.ts @@ -42,10 +42,10 @@ export async function findOwnedDockerWorkspace( ownerWorkspaceId: string, namespace: string, ) { - let found: Awaited> | undefined; + let found: Awaited> | undefined; for (let page = 1; ; page++) { - const result = await client.workspaces.list({ page, limit: 100 }); - const matches = result.workspaces.filter( + const result = await client.vms.list({ page, limit: 100 }); + const matches = result.vms.filter( (item) => item.slug === workspaceSlug(ownerWorkspaceId) && item.namespace === namespace, ); for (const workspace of matches) { @@ -55,7 +55,7 @@ export async function findOwnedDockerWorkspace( ); found = workspace; } - if (!result.workspaces.length || page * result.limit >= result.total) return found; + if (!result.vms.length || page * result.limit >= result.total) return found; } } @@ -78,7 +78,7 @@ export async function resizeDockerWorkspace(input: { save(workloads: NonNullable): Promise; }; }) { - const ws = input.client.workspace(input.workspaceId); + const ws = input.client.vm(input.workspaceId); const executor = new CloudWorkspaceExecutor(options => ws.runtime(options), input.workspaceId); try { const inspect = () => @@ -331,7 +331,7 @@ async function ensureDockerHost( ); input.signal.throwIfAborted(); } - const workspace = await client.workspaces + const workspace = await client.vms .create({ name: managed.name, slug: workspaceSlug(ownerId), @@ -355,7 +355,7 @@ async function ensureDockerHost( .catch(async (error) => { const failure = cloudWorkspaceCreationFailure(error); if (failure.workspaceId) { - const created = await client.workspaces.get(failure.workspaceId); + const created = await client.vms.get(failure.workspaceId); if ( created.id !== failure.workspaceId || created.namespace !== namespace || @@ -387,7 +387,7 @@ async function ensureDockerHost( // Complete this even after cancellation: retries must know which disk exists. await repos.cloudDockerWorkspace.attach(owner, input.organizationId, namespace, workspaceId); } - const ws = client.workspace(workspaceId); + const ws = client.vm(workspaceId); const current = await ws.get(); if (current.namespace !== namespace) throw new Error("Cloud workspace namespace changed"); input.signal?.throwIfAborted(); @@ -397,7 +397,7 @@ async function ensureDockerHost( input.onProgress?.( "Retrying the managed server's initial provisioning with its existing disk.\n", ); - const retried = await client.workspaces.retryCreation(workspaceId); + const retried = await client.vms.retryCreation(workspaceId); if (retried.id !== workspaceId || retried.namespace !== namespace) throw new Error("Cloud provisioning retry returned an unexpected workspace"); } else if (status === "stopped") await ws.start(); diff --git a/packages/platform/src/engine/lib/cloud-preflight.ts b/packages/platform/src/engine/lib/cloud-preflight.ts index 8515d80d3..67f55292b 100644 --- a/packages/platform/src/engine/lib/cloud-preflight.ts +++ b/packages/platform/src/engine/lib/cloud-preflight.ts @@ -1,3 +1,4 @@ +import { oblienApiBaseUrl } from "@repo/adapters"; import { reportCaughtError as observeCaughtError, diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { createPlatform, type CloudInfraProvider } from "@repo/adapters"; import { ensureNamespace, getOblienClient, issueNamespaceToken } from "./openship-cloud"; @@ -99,7 +100,7 @@ export async function runCloudPreflight( await assertCloudCanSpend(organizationId, opts.workspaceId); const cloudPlatform = await createPlatform({ target: "cloud", cloudToken: token.token, cloudNamespace: token.namespace, - cloudApiUrl: env.OBLIEN_API_URL, + cloudApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString(), }); cloud = cloudPlatform.routing as CloudInfraProvider; } catch (err) { diff --git a/packages/platform/src/engine/lib/cloud-resource-limits.ts b/packages/platform/src/engine/lib/cloud-resource-limits.ts index 64455831a..eac0f264c 100644 --- a/packages/platform/src/engine/lib/cloud-resource-limits.ts +++ b/packages/platform/src/engine/lib/cloud-resource-limits.ts @@ -1,6 +1,7 @@ import { AppError, resolvePlan, type CloudCapacityPool, type PlanTierId } from "@repo/core"; import { getOblienClient } from "./oblien-client"; import { z } from "zod"; +import { toOblienVmLimits, type NamespaceResourceLimits } from "@repo/adapters"; type NamespaceLimits = ReturnType; @@ -10,8 +11,8 @@ export function cloudNamespaceLimits(tier: PlanTierId) { return { ...resolvePlan(tier).oblienLimits }; } -export async function initialCloudNamespaceLimits(): Promise { - return cloudNamespaceLimits("free"); +export async function initialCloudNamespaceLimits() { + return toOblienVmLimits(cloudNamespaceLimits("free")); } /** Submit the verified subscription's declared policy under the billing lock. @@ -25,13 +26,14 @@ export async function syncCloudResourceLimits( ): Promise { const client = getOblienClient(); const { data: current } = await client.namespaces.get(namespace); + const providerLimits = toOblienVmLimits(desired); if (current.slug !== namespace) throw new AppError("Cloud namespace ownership changed", 502, "CLOUD_NAMESPACE_MISMATCH"); // Compare declared policy, never Oblien's effective_resource_limits: account // capacity may change without changing the customer's purchase contract. - const matches = (limits: Partial | null | undefined) => - (Object.keys(desired) as Array).every(key => (limits?.[key] ?? null) === desired[key]); + const matches = (limits: NamespaceResourceLimits | null | undefined) => + (Object.keys(providerLimits) as Array).every(key => (limits?.[key] ?? null) === providerLimits[key]); if (matches(current.resource_limits)) return; - const { data: updated } = await client.namespaces.update(current.id, { resource_limits: { ...desired } }); + const { data: updated } = await client.namespaces.update(current.id, { resource_limits: providerLimits }); if (updated.slug !== namespace || !matches(updated.resource_limits)) { throw new AppError("Cloud resource limits were not confirmed", 502, "CLOUD_RESOURCE_LIMITS_UNCONFIRMED"); } @@ -39,13 +41,13 @@ export async function syncCloudResourceLimits( const capacityResponse = z.object({ success: z.literal(true), data: z.object({ slug: z.string(), - effective_resource_limits: z.object({ max_workspaces: z.number().nonnegative().nullable(), + effective_resource_limits: z.object({ max_vms: z.number().nonnegative().nullable(), max_vcpus: z.number().nonnegative().nullable().optional(), max_ram_mb: z.number().nonnegative().nullable().optional(), max_disk_gb: z.number().nonnegative().nullable().optional(), max_total_vcpus: z.number().nonnegative().nullable(), max_total_ram_mb: z.number().nonnegative().nullable(), max_total_disk_gb: z.number().nonnegative().nullable() }).optional(), - allocated_resource_usage: z.object({ workspaces: z.number().nonnegative(), vcpus: z.number().nonnegative(), + allocated_resource_usage: z.object({ vms: z.number().nonnegative(), vcpus: z.number().nonnegative(), ram_mb: z.number().nonnegative(), disk_gb: z.number().nonnegative(), pending_updates: z.number().int().nonnegative() }).optional(), }) }); @@ -63,7 +65,7 @@ function presentCapacity(data: Awaited> const limits = data.effective_resource_limits, used = data.allocated_resource_usage; if (!limits || !used) return {}; return { - workspaces: { used: used.workspaces, max: limits.max_workspaces }, + workspaces: { used: used.vms, max: limits.max_vms }, vcpus: { used: used.vcpus, max: limits.max_total_vcpus }, ramMb: { used: used.ram_mb, max: limits.max_total_ram_mb }, diskGb: { used: used.disk_gb, max: limits.max_total_disk_gb }, diff --git a/packages/platform/src/engine/lib/cloud-tenant-admin.ts b/packages/platform/src/engine/lib/cloud-tenant-admin.ts index 8be2b268f..f7f0b032b 100644 --- a/packages/platform/src/engine/lib/cloud-tenant-admin.ts +++ b/packages/platform/src/engine/lib/cloud-tenant-admin.ts @@ -17,7 +17,7 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string }; const requireWorkspace = async (id: string) => { validateId(id); - const workspace = await admin.workspaces.get(id); + const workspace = await admin.vms.get(id); if (workspace.namespace !== namespace) throw deny(); return workspace; }; @@ -47,13 +47,13 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string get: requirePage, create: async (input) => { if (input.slug) validateId(input.slug); - await requireWorkspace(input.workspace_id); + await requireWorkspace(input.vm_id); await assertCloudCanSpend(organizationId, workspaceId); return admin.pages.create({ ...input, namespace }); }, deploy: async (slug, input) => { await requirePage(slug); - await requireWorkspace(input.workspace_id); + await requireWorkspace(input.vm_id); await assertCloudCanSpend(organizationId, workspaceId); return admin.pages.deploy(slug, input); }, @@ -83,14 +83,14 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string if (!owned) throw deny(); if (input.static) await requirePage(input.static.page); const workspaces = new Set(); - for (const rule of input.routes) { + for (const rule of input.routes ?? []) { if (rule.action.kind !== "proxy") continue; // External origins need separate tenant ownership verification. Admin // scope alone would authorize another customer's verified origin. - if (rule.action.origin || !rule.action.workspace) { + if (rule.action.origin || !rule.action.vm) { throw new AppError("Cloud routes must target a workspace in this organization", 400, "CLOUD_ROUTE_TARGET_INVALID"); } - workspaces.add(rule.action.workspace); + workspaces.add(rule.action.vm); } await Promise.all([...workspaces].map(requireWorkspace)); return admin.routes.set(normalized, input); diff --git a/packages/platform/src/engine/lib/cloud-workspace-host.ts b/packages/platform/src/engine/lib/cloud-workspace-host.ts index 2ca3a9305..cd3175dc9 100644 --- a/packages/platform/src/engine/lib/cloud-workspace-host.ts +++ b/packages/platform/src/engine/lib/cloud-workspace-host.ts @@ -32,7 +32,7 @@ export async function readCloudWorkspaceHost(organizationId: string, id: string) if (!env.CLOUD_MODE) { const connection = await remoteServerConnection(organizationId, id); const { client } = await getNamespaceClient(organizationId, id, connection); - const workspace = await client.workspaces.get(connection.workspaceId); + const workspace = await client.vms.get(connection.workspaceId); if (workspace.namespace !== connection.namespace) throw new AppError("Cloud space ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); if (workspace.id !== connection.workspaceId) throw new AppError("Cloud returned a different Cloud space", 502, "CLOUD_SERVER_IDENTITY_MISMATCH"); @@ -76,7 +76,7 @@ async function runningConnection(organizationId: string, id: string) { * a host or installing the Docker API bridge just to read metrics/open a shell. */ export async function openCloudWorkspaceExecutor(organizationId: string, id: string) { const { client, binding } = await runningConnection(organizationId, id); - return new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!); + return new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!); } /** Server-authorized Docker operations (inventory and migration). Applications @@ -127,7 +127,7 @@ async function measuredHost(organizationId: string, id: string) { export async function sampleCloudWorkspaceResources(organizationId: string, id: string, sampleUsage = true) { const { client, binding, provider } = await runningConnection(organizationId, id); if (!sampleUsage) return { capacity: provider.allocation, usage: unavailableServerUsage("Not sampled for an uncapped build") }; - const executor = new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!); + const executor = new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!); try { return { capacity: provider.allocation, usage: await sampleServerUsage(executor) }; } finally { diff --git a/packages/platform/src/engine/lib/cloud/types.ts b/packages/platform/src/engine/lib/cloud/types.ts index bc667d548..530b6a914 100644 --- a/packages/platform/src/engine/lib/cloud/types.ts +++ b/packages/platform/src/engine/lib/cloud/types.ts @@ -115,7 +115,7 @@ export interface CloudClient { }; pages: { create(input: { - workspace_id: string; + vm_id: string; path: string; name: string; slug: string; diff --git a/packages/platform/src/engine/lib/oblien-billing-api.ts b/packages/platform/src/engine/lib/oblien-billing-api.ts index e8b612c25..4cfa98bee 100644 --- a/packages/platform/src/engine/lib/oblien-billing-api.ts +++ b/packages/platform/src/engine/lib/oblien-billing-api.ts @@ -3,7 +3,7 @@ import { withDiagnosticSpan } from "@repo/core/diagnostics/node"; import { z } from "zod"; import { AppError } from "@repo/core"; import { OperationError } from "@repo/contracts"; -import { Oblien } from "@repo/adapters"; +import { Oblien, oblienApiBaseUrl, oblienApiUrl, toOblienVmOffer, toOblienVmPolicy, cloudBillingContract } from "@repo/adapters"; import { isDeepStrictEqual } from "node:util"; import { computeBillingModeSchema, oblienCapacityCatalogSchema, oblienCapacityPoolSchema, oblienNamespaceCapacitySchema } from "./oblien-capacity"; @@ -197,7 +197,7 @@ export type OblienPlanChangeQuote = z.infer; export type OblienPlanChange = z.infer; const policySchema = z.object({ - success: z.literal(true), service: z.literal("workspace_vm"), + success: z.literal(true), service: z.literal("vm_compute"), quotaLimit: allowance, overdraft: amount.nonnegative(), onOverdraftAction: z.enum(["stop_workspaces", "block"]), suspendThreshold: allowance, }); @@ -314,11 +314,7 @@ export class OblienBillingApi { clientId?: string; clientSecret?: string; baseUrl?: string; fetch?: typeof fetch; timeoutMs?: number; } = {}) { - const url = new URL(options.baseUrl ?? "https://api.oblien.com"); - if (url.username || url.password || url.search || url.hash || - (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) { - throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); - } + const url = oblienApiBaseUrl(options.baseUrl); this.baseUrl = url.toString().replace(/\/+$/, ""); this.fetcher = options.fetch ?? fetch; // The SDK has no client-wide fetch/timeout option. Replace this transport @@ -466,7 +462,7 @@ export class OblienBillingApi { ...(Object.keys(diagnostic).length ? { details: diagnostic } : {}), }); } - return payload as T; + return cloudBillingContract(payload) as T; } private async validate(response: Promise, schema: z.ZodType, slug?: string): Promise { @@ -612,7 +608,7 @@ export class OblienBillingApi { /** Mode A only: the complimentary-plan service owns these explicit grants. */ setPolicy(slug: string, input: Pick) { - return this.validate(this.billing.setPolicy(slug, input), policySchema.extend({ namespace }), slug); + return this.validate(this.billing.setPolicy(slug, toOblienVmPolicy(input)), policySchema.extend({ namespace }), slug); } resetQuota(slug: string, periodEnd: string) { @@ -641,9 +637,10 @@ export class OblienBillingApi { async previewPlanChange(slug: string, input: OblienPlanChangeInput) { const request = oblienPlanChangeInputSchema.parse(input); + const offer = toOblienVmOffer(request.offer); const result = await this.validate(request.offer.billingMode === "service" - ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request } }) - : this.billing.previewPlanChange(slug, { ...request, offer: { ...request.offer, billingMode: request.offer.billingMode } }), z.object({ + ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request, offer } }) + : this.billing.previewPlanChange(slug, { ...request, offer: { ...offer, billingMode: request.offer.billingMode } }), z.object({ success: z.literal(true), namespace, quote: oblienPlanChangeQuoteSchema, }), slug); if (result.quote.namespace !== slug || result.quote.billingInterval !== input.billingInterval) @@ -691,9 +688,10 @@ export class OblienBillingApi { // and this saved namespace offer before creating the Stripe session. const parsed = oblienCheckoutInputSchema.parse(input); const request = { ...parsed, allowPromotionCodes: parsed.offer?.unitAmount !== 0 }; + const offer = request.offer ? toOblienVmOffer(request.offer) : undefined; const result = await this.validate((request.offer?.billingMode === "service" || (request.kind === "subscription" && !!request.affiliateBuyer)) - ? this.request({ method: "POST", path: "/billing/checkout", body: request }) - : this.billing.checkout({ ...request, offer: request.offer ? { ...request.offer, billingMode: request.offer.billingMode === "monthly" ? "monthly" : request.offer.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema); + ? this.request({ method: "POST", path: "/billing/checkout", body: { ...request, offer } }) + : this.billing.checkout({ ...request, offer: offer ? { ...offer, billingMode: request.offer?.billingMode === "monthly" ? "monthly" : request.offer?.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema); this.validateCheckoutUrl(result.url); return result; } @@ -702,7 +700,7 @@ export class OblienBillingApi { const url = new URL(value); if (url.hostname === "api.oblien.com") { this.validateHostedUrl(value, "api.oblien.com"); - if (url.pathname === "/billing/pay" && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return; + if (url.pathname === oblienApiUrl(oblienApiBaseUrl(), "/billing/pay").pathname && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return; throw new AppError("Cloud billing returned an invalid hosted URL", 502, "OBLIEN_BILLING_INVALID_RESPONSE"); } this.validateHostedUrl(value, "checkout.stripe.com"); diff --git a/packages/platform/src/engine/lib/oblien-namespace.ts b/packages/platform/src/engine/lib/oblien-namespace.ts index 850b79330..a387bd59b 100644 --- a/packages/platform/src/engine/lib/oblien-namespace.ts +++ b/packages/platform/src/engine/lib/oblien-namespace.ts @@ -1,4 +1,5 @@ -import { AppError, type OblienLimits } from "@repo/core"; +import { AppError } from "@repo/core"; +import type { NamespaceResourceLimits } from "@repo/adapters"; import { getOblienClient } from "./oblien-client"; import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quota"; @@ -7,7 +8,7 @@ import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quot export async function ensureCloudNamespace(input: { name: string; slug: string; - resource_limits: OblienLimits; + resource_limits: NamespaceResourceLimits; }): Promise { await ensureOblienDefaultQuota(); const ensured = await getOblienClient().namespaces.ensure(input); diff --git a/packages/platform/src/engine/lib/openship-cloud.ts b/packages/platform/src/engine/lib/openship-cloud.ts index 6552d0582..2cb6d116c 100644 --- a/packages/platform/src/engine/lib/openship-cloud.ts +++ b/packages/platform/src/engine/lib/openship-cloud.ts @@ -5,7 +5,7 @@ */ import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { createHash } from "node:crypto"; -import { Oblien, OblienError } from "@repo/adapters"; +import { Oblien, OblienError, oblienApiBaseUrl } from "@repo/adapters"; import { OperationError } from "@repo/contracts"; import { AppError, safeErrorMessage } from "@repo/core"; import { repos } from "@repo/db"; @@ -108,7 +108,7 @@ export async function issueNamespaceToken(organizationId: string, workspaceId?: const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId); try { const result = await getOblienClient().tokens.create({ scope: "namespace", namespace, ttl: 1800 }); - return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: env.OBLIEN_API_URL }; + return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString() }; } catch (error) { errorDiagnostics.warn("platform/engine/lib/openship-cloud", `[oblien] token issuance failed for org ${organizationId}: ${safeErrorMessage(error)}`, error); if (error instanceof OblienError && typeof error.status === "number" && [429, 502, 503, 504].includes(error.status)) { @@ -130,7 +130,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou // Authorization is always read before cache lookup. A token cache must never // turn a deleted/moved workspace into access granted by an earlier request. const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId); - const key = namespaceTokenKey(organizationId, namespace, env.OBLIEN_API_URL); + const key = namespaceTokenKey(organizationId, namespace, oblienApiBaseUrl(env.OBLIEN_API_URL).toString()); const store = await cacheStore("oblien-internal-tokens", { maxSize: 10_000 }); const readFresh = async () => { const cached = await store.get(key); @@ -142,7 +142,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou const renewed = await readFresh(); if (renewed) return renewed; const credentials = await issueNamespaceToken(organizationId, workspaceId); - if (credentials.namespace !== namespace || credentials.providerApiUrl !== env.OBLIEN_API_URL) + if (credentials.namespace !== namespace || credentials.providerApiUrl !== oblienApiBaseUrl(env.OBLIEN_API_URL).toString()) throw new AppError("Cloud execution ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); const ttl = Math.floor((Date.parse(credentials.expiresAt) - Date.now() - 60_000) / 1000); if (!credentials.token || !Number.isFinite(ttl) || ttl <= 0) diff --git a/packages/platform/src/engine/modules/actions/billing-namespace.ts b/packages/platform/src/engine/modules/actions/billing-namespace.ts index afb9e861c..c7cf99aae 100644 --- a/packages/platform/src/engine/modules/actions/billing-namespace.ts +++ b/packages/platform/src/engine/modules/actions/billing-namespace.ts @@ -30,7 +30,7 @@ export async function ensureActionsBillingNamespace(organizationId: string): Pro // Preparing checkout must not permit compute before paid runner setup. // These initial caps do not replace an existing namespace's limits. resource_limits: { - max_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, @@ -79,7 +79,7 @@ export async function ensureFundedActionRunners(organizationId: string): Promise disk: Math.max(...runners.map((r) => r.diskGb)), }; const limits = { - max_workspaces: maxParallel, + max_vms: maxParallel, max_vcpus: maximum.cpu, max_ram_mb: maximum.memory, max_disk_gb: maximum.disk, diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts index 1390c3d64..7679d3099 100644 --- a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts +++ b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts @@ -30,7 +30,7 @@ vi.mock("@repo/adapters", async (original) => ({ prepare = state.prepare; }, Oblien: class { - workspaces = { + vms = { create: state.create, get: state.get, delete: state.remove, diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.ts b/packages/platform/src/engine/modules/actions/cloud-runner.ts index ee84aad79..6079ce3da 100644 --- a/packages/platform/src/engine/modules/actions/cloud-runner.ts +++ b/packages/platform/src/engine/modules/actions/cloud-runner.ts @@ -268,8 +268,8 @@ export async function openCloudActionWorker( let workspace; try { workspace = job.providerWorkspaceId - ? await client.workspaces.get(job.providerWorkspaceId) - : await client.workspaces.create(workspaceInput(job, runner)); + ? await client.vms.get(job.providerWorkspaceId) + : await client.vms.create(workspaceInput(job, runner)); } catch (error) { if (job.providerWorkspaceId && isMissing(error)) throw new AppError( @@ -318,7 +318,7 @@ export async function openCloudActionWorker( } if (workspace.ready === false || !["active", "running"].includes(status)) return null; const executor = new CloudWorkspaceExecutor( - options => client.workspace(workspace.id).runtime(options), + options => client.vm(workspace.id).runtime(options), workspace.id, ); try { @@ -333,7 +333,7 @@ export async function openCloudActionWorker( // The authenticated Runtime API gateway needs host ingress. Enabling the // API adds its port but does not enable that firewall path. Restrict this // disposable VM to the API port; do not expose SSH or workflow services. - await client.workspaces.network.update(workspace.id, { + await client.vms.network.update(workspace.id, { public_access: true, ingress_ports: [9990], }); @@ -386,8 +386,8 @@ export async function removeCloudActionWorker( // An uncertain create is resolved with its ORIGINAL key and config. No new // key, image, resources or paid purchase is introduced by cleanup retries. const workspace = job.providerWorkspaceId - ? await client.workspaces.get(job.providerWorkspaceId) - : await client.workspaces.create(workspaceInput(job, runner)); + ? await client.vms.get(job.providerWorkspaceId) + : await client.vms.create(workspaceInput(job, runner)); assertWorkspace(workspace, job, runner); if (!job.providerWorkspaceId) { const saved = await update({ @@ -396,9 +396,9 @@ export async function removeCloudActionWorker( if (!saved) throw new Error("Actions lease changed before worker cleanup"); job = saved; } - await client.workspaces.delete(workspace.id); + await client.vms.delete(workspace.id); try { - await client.workspaces.get(workspace.id); + await client.vms.get(workspace.id); // Deletion is asynchronous. Keep the scheduler slot and poll on the // next tick without replacing the workflow result with a cleanup error. return false; diff --git a/packages/platform/src/engine/modules/assistant/remote-target.ts b/packages/platform/src/engine/modules/assistant/remote-target.ts index b65fd7d51..180f59a30 100644 --- a/packages/platform/src/engine/modules/assistant/remote-target.ts +++ b/packages/platform/src/engine/modules/assistant/remote-target.ts @@ -187,7 +187,7 @@ export async function createRemoteAssistantClient( connection.organizationId, server!.workspaceId, ); - let runtime = await owned.client.workspace(owned.binding.workspaceId!).runtime(); + let runtime = await owned.client.vm(owned.binding.workspaceId!).runtime(); const baseUrl = "http://openship-assistant.invalid"; return { id: `assistant:${server!.id}`, @@ -210,7 +210,7 @@ export async function createRemoteAssistantClient( let result = await send(); if (result.status === 401) { runtime = await owned.client - .workspace(owned.binding.workspaceId!) + .vm(owned.binding.workspaceId!) .runtime({ force: true }); result = await send(); } diff --git a/packages/platform/src/engine/modules/billing/billing-resources.service.ts b/packages/platform/src/engine/modules/billing/billing-resources.service.ts index 987fd3b5f..1d7657156 100644 --- a/packages/platform/src/engine/modules/billing/billing-resources.service.ts +++ b/packages/platform/src/engine/modules/billing/billing-resources.service.ts @@ -1,7 +1,7 @@ /** Display telemetry is independent of checkout, entitlements and provisioning. */ import { observedAllSettled, diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { z } from "zod"; -import { Oblien } from "@repo/adapters"; +import { Oblien, oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters"; import { type PlanTierId } from "@repo/core"; import type { BillingResources } from "@repo/contracts"; import { env } from "../../config/env"; @@ -28,12 +28,12 @@ function timedClient(options: ConstructorParameters[0], signal: A const client = new Oblien(options); // The SDK owns endpoint formatting; its default transport has no redirect // control. Never forward owner credentials or a scoped token to another host. - const base = (options.baseUrl ?? "https://api.oblien.com").replace(/\/+$/, ""); + const base = oblienApiBaseUrl(options.baseUrl); const headers = { "Content-Type": "application/json", ...("token" in options ? { Authorization: `Bearer ${options.token}` } : { "X-Client-ID": options.clientId, "X-Client-Secret": options.clientSecret }) }; client._http.request = async ({ path, method, query, body }: Parameters[0]): Promise => { - const url = new URL(`${base}${path}`); + const url = oblienApiUrl(base, path); for (const [key, value] of Object.entries(query ?? {})) if (value !== undefined) url.searchParams.set(key, String(value)); const response = await fetch(url.toString(), { method, headers, signal, redirect: "error", ...(body === undefined ? {} : { body: JSON.stringify(body) }), diff --git a/packages/platform/src/engine/modules/billing/management.service.ts b/packages/platform/src/engine/modules/billing/management.service.ts index dda956942..3a1b7ca0b 100644 --- a/packages/platform/src/engine/modules/billing/management.service.ts +++ b/packages/platform/src/engine/modules/billing/management.service.ts @@ -243,7 +243,7 @@ export async function purchaseManagement(ctx: ExecutionContext, input: Managemen name: "Openship Manage", slug: owner.namespace, resource_limits: { - max_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts index a22939167..0a2c01839 100644 --- a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts +++ b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts @@ -29,7 +29,7 @@ export interface OblienEventEnvelope { namespace?: string; data?: { namespace?: string; - workspace_id?: string; + vm_id?: string; period_end?: string; [key: string]: unknown; }; diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts index 9ee03e86a..4304fe097 100644 --- a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts +++ b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts @@ -39,7 +39,7 @@ interface OblienUsageBucket { interface OblienWebhookData { namespace?: string; - workspace_id?: string; + vm_id?: string; workspace_name?: string; service?: string; /** credits.usage */ diff --git a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts index c9ad35403..97265587e 100644 --- a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts +++ b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts @@ -704,7 +704,7 @@ export async function processWorkspaceOperation(id: string): Promise { const namespace = row.namespace; if (!namespace || namespace !== binding.namespace) throw new Error("Cloud workspace namespace changed"); - const ws = client.workspace(binding.workspaceId); + const ws = client.vm(binding.workspaceId); try { const current = await ws.get(); if (current.namespace !== namespace) diff --git a/packages/platform/src/engine/modules/domains/routing-apply.service.ts b/packages/platform/src/engine/modules/domains/routing-apply.service.ts index 599377080..25ae28ddd 100644 --- a/packages/platform/src/engine/modules/domains/routing-apply.service.ts +++ b/packages/platform/src/engine/modules/domains/routing-apply.service.ts @@ -538,7 +538,7 @@ export async function applyCloudRouting(opts: { !input.routes.some( (rule) => rule.action.kind === "proxy" && - rule.action.workspace === backend.workspace && + rule.action.vm === backend.vm && rule.action.port === backend.port, ) ) { diff --git a/packages/platform/src/engine/modules/system/managed-server-access.ts b/packages/platform/src/engine/modules/system/managed-server-access.ts index cab255ce0..ca1ede263 100644 --- a/packages/platform/src/engine/modules/system/managed-server-access.ts +++ b/packages/platform/src/engine/modules/system/managed-server-access.ts @@ -25,7 +25,7 @@ export async function managedConnection(ctx: ExecutionContext, id: string) { return { ...connection, workspaceId, - workspace: connection.client.workspace(connection.binding.workspaceId!), + workspace: connection.client.vm(connection.binding.workspaceId!), }; } export type ManagedConnection = Awaited>; diff --git a/packages/platform/src/engine/modules/system/server-managed.operations.ts b/packages/platform/src/engine/modules/system/server-managed.operations.ts index 89be3401f..36811293f 100644 --- a/packages/platform/src/engine/modules/system/server-managed.operations.ts +++ b/packages/platform/src/engine/modules/system/server-managed.operations.ts @@ -267,7 +267,7 @@ const controls: ResourceServices = { if ((await runtimeStatus(connection)).enabled !== true) { const result = await connection.workspace.apiAccess.enable(); requireProviderSuccess(result); - connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!); + connection.client.vms.invalidateRuntime(connection.binding.workspaceId!); auditManagedControl(ctx, id, "runtime.enable"); } const after = await runtimeStatus(connection); @@ -299,7 +299,7 @@ const controls: ResourceServices = { try { requireProviderSuccess(await connection.workspace.apiAccess.rotateToken()); } finally { - connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!); + connection.client.vms.invalidateRuntime(connection.binding.workspaceId!); } const after = await runtimeCredential(connection); if (after.revision === before.revision) diff --git a/packages/platform/test/deployment-container-info-schema.test.ts b/packages/platform/test/deployment-container-info-schema.test.ts index 273113f3a..409a1f8c6 100644 --- a/packages/platform/test/deployment-container-info-schema.test.ts +++ b/packages/platform/test/deployment-container-info-schema.test.ts @@ -15,7 +15,7 @@ async function createRuntime(kind: "Docker" | "Cloud", workspaceStatus = "runnin ? await DockerRuntime.create({ dockerSocketPath: "/tmp/openship-test-absent.sock" }) : await CloudDockerRuntime.forWorkspace( { - workspaces: { + vms: { get: async () => ({ id: "workspace-a", namespace: "namespace-a", From 8a329803866e2af2561f8661ed314a6988268aa1 Mon Sep 17 00:00:00 2001 From: hydralerne Date: Sat, 14 Nov 2026 20:40:40 +0100 Subject: [PATCH 2/6] test(cloud): decode native VM catalog fixture at the provider boundary --- apps/api/src/modules/billing/billing-capacity-catalog.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts index e49d13054..eea7004b3 100644 --- a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts +++ b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts @@ -9,6 +9,7 @@ import type { OblienSubscription } from "@repo/platform/engine/lib/oblien-billin import { savedOffer, savedMetadata, savedMonthlyHobby } from "../../../test/helpers/saved-cloud-offer"; import capacityFixture from "../../../test/fixtures/oblien-capacity-catalog.json"; import { oblienCapacityCatalogSchema } from "@repo/platform/engine/lib/oblien-capacity"; +import { cloudBillingContract } from "@repo/adapters"; const savedPro = (): NonNullable => ({ tierId: "reseller", status: "active", billingInterval: "monthly", periodStart: "2026-09-01T00:00:00Z", periodEnd: "2026-10-01T00:00:00Z", cancelAtPeriodEnd: false, canceledAt: null, @@ -17,7 +18,7 @@ const monthlyPro = (): NonNullable => ({ ...savedPro(), offer: subscriptionOffer("pro", "monthly"), metadata: subscriptionMetadata("pro", "org-a", "ns-a") }); describe("funded Cloud offers and isolated capacity", () => { - it.each([undefined, oblienCapacityCatalogSchema.parse(capacityFixture)])( + it.each([undefined, oblienCapacityCatalogSchema.parse(cloudBillingContract(capacityFixture))])( "publishes only subscription plans without prepaid compute offers (with or without provider capacity)", (provider) => { const catalog = presentCloudPlans("en", provider); From b7fdcacbbf8617d6e4ba2f164a888e210195795b Mon Sep 17 00:00:00 2001 From: hydralerne Date: Sat, 14 Nov 2026 20:42:31 +0100 Subject: [PATCH 3/6] style(cloud): format VM contract regression test --- packages/adapters/src/oblien-contract.test.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/packages/adapters/src/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts index d30d3bb5e..3740a5dd5 100644 --- a/packages/adapters/src/oblien-contract.test.ts +++ b/packages/adapters/src/oblien-contract.test.ts @@ -45,15 +45,13 @@ it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE request } res.setHeader("Content-Type", "application/json"); if (req.url === "/proxy/v1/vms" && req.method === "POST") { - res - .writeHead(422) - .end( - JSON.stringify({ - success: false, - code: "CREATE_FAILED", - details: { vm_id: "vm-failed" }, - }), - ); + res.writeHead(422).end( + JSON.stringify({ + success: false, + code: "CREATE_FAILED", + details: { vm_id: "vm-failed" }, + }), + ); return; } if (req.url === "/proxy/v1/vms") { From eb567ea843d69abb35e3c9b699c68bf259dd1ae4 Mon Sep 17 00:00:00 2001 From: hydralerne Date: Sat, 14 Nov 2026 20:50:43 +0100 Subject: [PATCH 4/6] test(cli): select non-root SSH session in sudo-refusal fixture --- apps/cli/test/unit/compose-env-preserve.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/cli/test/unit/compose-env-preserve.test.ts b/apps/cli/test/unit/compose-env-preserve.test.ts index 1ca62a9cd..7ea232daa 100644 --- a/apps/cli/test/unit/compose-env-preserve.test.ts +++ b/apps/cli/test/unit/compose-env-preserve.test.ts @@ -1753,10 +1753,13 @@ describe("composeUp — the host channel is provisioned out loud (#509)", () => seedHostKey(); h.channelAuth = () => ({ status: 0, stdout: "openship-sudo=refused\n", stderr: "" }); - await composeUp({}); + // Select a non-root session explicitly: the test runner may itself be root, + // whose SSH login already has privilege and needs no sudo warning. + await composeUp({ hostSshUser: "ops" }); // A working channel, so it IS written — just one with no route to root. expect(writtenEnv().OPENSHIP_HOST_SSH_HOST).toBe("host.docker.internal"); + expect(writtenEnv().OPENSHIP_HOST_SSH_USER).toBe("ops"); expect(warned.join("\n")).toContain("no route to it"); }); From 4e89ed44cbb74f17217d99af908b9ba5f79489a8 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 21:58:22 +0200 Subject: [PATCH 5/6] Complete native VM credentials, alerts and SDK rollout checks --- apps/api/scripts/cloud-readiness.ts | 11 +++++----- .../billing/oblien-webhook.controller.test.ts | 4 ++-- apps/api/test/lib/oblien-runtime-env.test.ts | 18 ++++++++++++++++ .../test/modules/billing/credit-alert.test.ts | 8 ++++++- .../system/server-managed-controls.test.ts | 13 +++++++++--- apps/api/tsconfig.json | 2 +- docs/managed-cloud-servers.md | 12 ++++++----- docs/openship-cloud-launch.md | 18 ++++++++++++++++ .../adapters/scripts/verify-cloud-docker.ts | 2 +- .../scripts/verify-cloud-isolation.ts | 4 ++-- packages/adapters/src/oblien-contract.test.ts | 21 +++++++++++++++++++ packages/adapters/src/oblien.ts | 5 ++--- packages/adapters/tsconfig.json | 2 +- packages/platform/src/engine/config/env.ts | 2 +- .../src/engine/lib/cloud-preflight.ts | 3 +-- .../src/engine/lib/oblien-billing-api.ts | 2 +- .../modules/billing/billing-credit-alert.ts | 3 ++- .../modules/billing/oblien-webhook.service.ts | 2 +- .../system/server-managed.operations.ts | 4 ++-- 19 files changed, 104 insertions(+), 32 deletions(-) create mode 100644 apps/api/test/lib/oblien-runtime-env.test.ts diff --git a/apps/api/scripts/cloud-readiness.ts b/apps/api/scripts/cloud-readiness.ts index 1c2330b94..0a483cae5 100644 --- a/apps/api/scripts/cloud-readiness.ts +++ b/apps/api/scripts/cloud-readiness.ts @@ -1,4 +1,5 @@ /** Read-only release checks. Does not create tokens, checkouts, or resources. */ +import { oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters"; import { runtimeTarget } from "@repo/core"; import { assertOblienEntitlementMatchesSubscription, OblienBillingApi } from "@repo/platform/engine/lib/oblien-billing-api"; import { OBLIEN_WEBHOOK_EVENTS, oblienWebhookUrl } from "@repo/platform/engine/lib/oblien-webhook-config"; @@ -7,13 +8,13 @@ const results: Array<{ check: string; ok: boolean; skipped?: boolean; detail?: s const record = (check: string, ok: boolean, detail?: string) => results.push({ check, ok, ...(detail ? { detail } : {}) }); const clientId = process.env.OBLIEN_CLIENT_ID; const clientSecret = process.env.OBLIEN_CLIENT_SECRET; -const apiBase = process.env.OBLIEN_API_URL ?? "https://api.oblien.com"; +const apiBase = oblienApiBaseUrl(process.env.OBLIEN_API_URL); record("Cloud mode", process.env.CLOUD_MODE === "true"); record("Oblien credentials configured", Boolean(clientId && clientSecret)); record("Webhook secret configured", Boolean(process.env.OBLIEN_WEBHOOK_SECRET)); record("Subscription purchases enabled", process.env.BILLING_ENABLED === "true"); -const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase }); +const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase.toString() }); const checks = await Promise.allSettled([ (async () => { await billing.assertResellerSupport(); @@ -35,13 +36,13 @@ const checks = await Promise.allSettled([ (async () => { const callback = oblienWebhookUrl(process.env.OBLIEN_WEBHOOK_URL, runtimeTarget.api); if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing"); - const response = await fetch(`${apiBase.replace(/\/+$/, "")}/webhooks`, { + const response = await fetch(oblienApiUrl(apiBase, "/webhooks"), { headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret }, redirect: "error", signal: AbortSignal.timeout(15_000), }); if (!response.ok) throw new Error(`Webhook registry HTTP ${response.status}`); const body = await response.json() as { success: boolean; webhooks?: Array<{ url: string; active: boolean; namespace?: string | null; events: string[]; secret?: string | null }> }; - const webhook = body.success && body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active); + const webhook = body.success ? body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active) : undefined; const missing = OBLIEN_WEBHOOK_EVENTS.filter((event) => !webhook || !webhook.events.includes(event)); const maskedSecret = typeof webhook?.secret === "string" && /^[*•*…]+$/u.test(webhook.secret); const matchingSecret = Boolean(webhook?.secret && webhook.secret === process.env.OBLIEN_WEBHOOK_SECRET); @@ -56,7 +57,7 @@ const checks = await Promise.allSettled([ })(), (async () => { if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing"); - const response = await fetch(`${apiBase.replace(/\/+$/, "")}/namespaces?limit=1`, { + const response = await fetch(oblienApiUrl(apiBase, "/namespaces?limit=1"), { headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret }, redirect: "error", signal: AbortSignal.timeout(15_000), }); diff --git a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts index 360375850..2302b9d73 100644 --- a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts +++ b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts @@ -294,7 +294,7 @@ describe("oblienWebhook — dispatch", () => { describe("durable quota alert receipt", () => { it("returns 503 without a checkpoint when notification storage fails, then retries the same event", async () => { - const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } }); + const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); h.enqueue.mockRejectedValueOnce(new Error("database unavailable")); expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-critical"))) as unknown as JsonResult).status).toBe(503); expect(h.processed.size).toBe(0); @@ -305,7 +305,7 @@ describe("durable quota alert receipt", () => { expect(h.processed.size).toBe(1); }); it("leaves the event retryable when exhaustion activity cannot be recorded", async () => { - const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } }); + const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); h.auditRecord.mockRejectedValueOnce(new Error("activity storage unavailable")); expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-activity"))) as unknown as JsonResult).status).toBe(503); expect(h.processed.size).toBe(0); diff --git a/apps/api/test/lib/oblien-runtime-env.test.ts b/apps/api/test/lib/oblien-runtime-env.test.ts new file mode 100644 index 000000000..a8fd024d3 --- /dev/null +++ b/apps/api/test/lib/oblien-runtime-env.test.ts @@ -0,0 +1,18 @@ +import { afterEach, expect, it, vi } from "vitest"; + +afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); +}); + +it.each([ + [undefined, "https://vm.oblien.com"], + ["https://runtime.staging.example", "https://runtime.staging.example"], +])("configures the native VM credential endpoint with override %s", async (override, expected) => { + vi.resetModules(); + vi.stubEnv("NODE_ENV", "test"); + vi.stubEnv("BILLING_ENABLED", "false"); + vi.stubEnv("OBLIEN_RUNTIME_URL", override); + const { env } = await import("@repo/platform/engine/config/env"); + expect(env.OBLIEN_RUNTIME_URL).toBe(expected); +}); diff --git a/apps/api/test/modules/billing/credit-alert.test.ts b/apps/api/test/modules/billing/credit-alert.test.ts index d02ca881d..437b90dae 100644 --- a/apps/api/test/modules/billing/credit-alert.test.ts +++ b/apps/api/test/modules/billing/credit-alert.test.ts @@ -23,13 +23,19 @@ const input = { eventType: "namespace.quota.threshold", eventId: "evt1", timestamp: "2026-09-28T00:00:00Z", - data: { namespace: "tenant", service: "workspace_vm", threshold: 95, alert: { limit: 4000 } }, + data: { namespace: "tenant", service: "vm_compute", threshold: 95, alert: { limit: 4000 } }, organizationId: "org-a", dashboardUrl: "https://app.openship.io", entitlement: state(), }; describe("provider credit alerts", () => { + it("accepts a pre-cutover delivery without changing its idempotency key", () => { + const result = creditAlertNotification({ + ...input, data: { ...input.data, service: "workspace_vm" }, + }); + expect(result).toEqual(creditAlertNotification(input)); + }); it("uses current provider numbers and an organization-bound billing link", () => { const result = creditAlertNotification(input)!; expect(result.payload.message).toContain("95%"); diff --git a/apps/api/test/modules/system/server-managed-controls.test.ts b/apps/api/test/modules/system/server-managed-controls.test.ts index 6eaeeffb6..364e1abd0 100644 --- a/apps/api/test/modules/system/server-managed-controls.test.ts +++ b/apps/api/test/modules/system/server-managed-controls.test.ts @@ -72,11 +72,11 @@ let workloads: Map; let vm: any; let handle: any; -const jwt = (id = vmId, type = "workspace") => +const jwt = (id = vmId, type = "vm") => `e30.${Buffer.from( JSON.stringify({ type, - workspace_id: id, + vm_id: id, token: runtimeToken, exp: Math.floor(Date.now() / 1000) + 3600, }), @@ -402,7 +402,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", ).toBe(400); expect(handle.ssh.setPassword).not.toHaveBeenCalled(); }); - it("reveals only a workspace gateway token and fences repeat rotations", async () => { + it("reveals only a VM gateway token and fences repeat rotations", async () => { const revealed = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(revealed.status, JSON.stringify(revealed.body)).toBe(200); expect(revealed.body.endpoint).toBe("https://runtime.example.test"); @@ -420,6 +420,13 @@ describe("managed server controls through real HTTP, policy and SQL ownership", (await request("managed/runtime-api/credential", "POST", { confirm: true })).status, ).toBe(502); }); + it.each(["workspace", "namespace", "account"])("rejects %s credentials even with the selected VM ID", async (type) => { + handle.apiAccess.getToken.mockResolvedValue({ token: jwt(vmId, type) }); + const result = await request("managed/runtime-api/credential", "POST", { confirm: true }); + expect(result.status).toBe(502); + expect(result.body.code).toBe("MANAGED_CREDENTIAL_UNAVAILABLE"); + expect(JSON.stringify(result.body)).not.toContain(runtimeToken); + }); it("keeps the original network response for clients that do not request diagnostics", async () => { const legacy = { internetAccess: true, ingressPorts: [80, 9990] }; expect((await request("network-settings")).body).toEqual(legacy); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json index 7c483898a..94a494d7e 100644 --- a/apps/api/tsconfig.json +++ b/apps/api/tsconfig.json @@ -15,6 +15,6 @@ "declaration": false, "declarationMap": false }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "scripts/cloud-readiness.ts"], "exclude": ["node_modules", "dist"] } diff --git a/docs/managed-cloud-servers.md b/docs/managed-cloud-servers.md index 2ab754f07..6d2858c3d 100644 --- a/docs/managed-cloud-servers.md +++ b/docs/managed-cloud-servers.md @@ -212,11 +212,13 @@ root-equivalent access to this server, not project-scoped access. Direct SSH/SDK clients run outside Openship's deployment queue; administrators must coordinate their own commands with application work. -The provider Runtime endpoint defaults to `https://workspace.oblien.com` and can -be overridden with `OBLIEN_RUNTIME_URL`. All provider methods used here are in -Oblien SDK 2.10.0; no new provider SDK release is required. Deploy the Openship API -and dashboard from the same release to use the new controls. Existing server -response shapes are unchanged. Detailed network reads opt in with +The provider Runtime endpoint defaults to `https://vm.oblien.com` and can +be overridden with `OBLIEN_RUNTIME_URL`. These controls use Oblien SDK 3.0.2 and +require the matching native VM API/gateway and fresh scoped credentials. Follow +the [SDK 3 cutover instructions](openship-cloud-launch.md#oblien-sdk-3-and-versioned-api-activation), +including the Desktop/self-hosted client rollout. Deploy the Openship API and +dashboard from the same release. Existing OpenShip server response shapes are +unchanged. Detailed network reads opt in with `getNetworkSettings(id, { details: true })` / `?details=true`; writes return diagnostics only when the caller supplies `expectedRevision`, preserving the original internet-only contract for older clients. diff --git a/docs/openship-cloud-launch.md b/docs/openship-cloud-launch.md index cc7f378c6..3c733cdb8 100644 --- a/docs/openship-cloud-launch.md +++ b/docs/openship-cloud-launch.md @@ -818,3 +818,21 @@ this integration. Older SDK routes are not probed and failed writes are not replayed. OpenShip's organization/workspace records, managed-server IDs, paid offer snapshots and customer metadata retain their existing identities. The provider boundary maps those saved workspace counts to native VM capacity. + +The matching runtime gateway is `https://vm.oblien.com`; remove or update any +old `OBLIEN_RUNTIME_URL` override. Runtime credentials must carry `type: "vm"` +and the selected `vm_id`. Namespace/account tokens are never runtime credentials. + +This cutover also requires a Desktop/self-hosted release containing SDK 3 for +installations that use Cloud servers. Those clients execute provider requests +directly using scoped tokens; redeploying the hosted API alone cannot upgrade +their SDK 2 transport. Coordinate that client rollout with the provider cutover, +and obtain fresh credentials. Existing VM IDs, disks, and project data must be +preserved. Self-hosted local/SSH-only deployments do not use this provider API. + +Before reopening customer operations, run `bun run --cwd apps/api cloud:check` +with the deployed Cloud environment and both explicit staging verification +scripts (`verify-cloud-docker.ts` and `verify-cloud-isolation.ts`) against the +matching API/gateway. Verify an existing VM in addition to disposable creation, +exec/files, routing, namespace isolation and cleanup. Local HTTP fixtures and +unit tests do not establish that the provider deployment has been activated. diff --git a/packages/adapters/scripts/verify-cloud-docker.ts b/packages/adapters/scripts/verify-cloud-docker.ts index 0a78c00de..6e7ab79bb 100644 --- a/packages/adapters/scripts/verify-cloud-docker.ts +++ b/packages/adapters/scripts/verify-cloud-docker.ts @@ -147,7 +147,7 @@ try { (await client.vms.get(workspaceId)).mode === "permanent", ); await client - .workspace(workspaceId) + .vm(workspaceId) .lifecycle.makeTemporary({ ttl: "20m", ttl_action: "remove", remove_on_exit: false }); const pageMethods = [ "list", diff --git a/packages/adapters/scripts/verify-cloud-isolation.ts b/packages/adapters/scripts/verify-cloud-isolation.ts index ba0453d47..131a01d2a 100644 --- a/packages/adapters/scripts/verify-cloud-isolation.ts +++ b/packages/adapters/scripts/verify-cloud-isolation.ts @@ -176,7 +176,7 @@ try { finally { await executor.dispose(); } pages.set(namespace, namespace); await save(); - await admin.pages.create({ slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" }); + await admin.pages.create({ name: namespace, slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" }); } const visibleA = (await clientA.vms.list()).vms; const visibleB = (await clientB.vms.list()).vms; @@ -297,7 +297,7 @@ try { try { const current = await admin.namespaces.get(id); if (current.data.slug !== namespace || !namespace.startsWith(`${tag}-`)) throw new Error("Test namespace identity changed"); - await admin.namespaces.delete(id, { deleteWorkspaces: true }); + await admin.namespaces.delete(id, { deleteVms: true }); namespaceIds.delete(namespace); } catch (error) { if ((error as { status?: number }).status === 404) namespaceIds.delete(namespace); diff --git a/packages/adapters/src/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts index 3740a5dd5..66507f17b 100644 --- a/packages/adapters/src/oblien-contract.test.ts +++ b/packages/adapters/src/oblien-contract.test.ts @@ -64,6 +64,10 @@ it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE request res.end(JSON.stringify({ success: true, vm: { id: "vm-a", namespace: "tenant-a" } })); return; } + if (req.url === "/proxy/v1/vms/vm-a/workloads/process-a") { + res.end(JSON.stringify({ success: true, workload: { id: "process-a", status: "running" } })); + return; + } if (req.url === "/proxy/v1/pages") { res.end(JSON.stringify({ success: true, page: { slug: "site", source_vm_id: "vm-a" } })); return; @@ -85,6 +89,10 @@ it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE request }); expect((await client.vms.list()).vms[0]?.id).toBe("vm-a"); expect((await client.vm("vm-a").get()).namespace).toBe("tenant-a"); + expect(await client.vm("vm-a").workloads.get("process-a")).toMatchObject({ + id: "process-a", + status: "running", + }); await client.pages.create({ vm_id: "vm-a", name: "Site", slug: "site", path: "/dist" }); await client.routes.set("site.example", { routes: [{ match: { path: "/" }, action: { kind: "proxy", vm: "vm-a", port: 3000 } }], @@ -111,6 +119,19 @@ it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE request } }); +it.each([undefined, null, [], { status: "running" }])( + "rejects an invalid native workload record: %j", + async (workload) => { + vi.stubGlobal( + "fetch", + vi.fn(async () => Response.json({ success: true, workload })), + ); + await expect( + new Oblien({ token: "fixture" }).vm("vm-a").workloads.get("process-a"), + ).rejects.toMatchObject({ code: "OBLIEN_WORKLOAD_INVALID" }); + }, +); + it("preserves paid limits, zero and unlimited counts while leaving customer metadata opaque", () => { const metadata = { workspace: "customer-chosen", diff --git a/packages/adapters/src/oblien.ts b/packages/adapters/src/oblien.ts index 8d6467f14..aabc70696 100644 --- a/packages/adapters/src/oblien.ts +++ b/packages/adapters/src/oblien.ts @@ -323,13 +323,12 @@ export class Oblien extends OblienSdk { // Validate the native record before process control and resize recovery. const getWorkload = this.vms.workloads.get.bind(this.vms.workloads); this.vms.workloads.get = async (workspaceId, workloadId) => { - const response = await getWorkload(workspaceId, workloadId); - const workload = response; + const workload = await getWorkload(workspaceId, workloadId); if (!workload || typeof workload !== "object" || Array.isArray(workload) || !("id" in workload) || typeof workload.id !== "string") { throw new OblienError("Oblien returned an invalid application process record", 502, "OBLIEN_WORKLOAD_INVALID"); } - return workload as typeof response; + return workload; }; } } diff --git a/packages/adapters/tsconfig.json b/packages/adapters/tsconfig.json index a22f17e3d..cc2e306d2 100644 --- a/packages/adapters/tsconfig.json +++ b/packages/adapters/tsconfig.json @@ -6,6 +6,6 @@ "types": ["node"], "outDir": "dist" }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "scripts/verify-cloud-docker.ts", "scripts/verify-cloud-isolation.ts"], "exclude": ["node_modules", "dist"] } diff --git a/packages/platform/src/engine/config/env.ts b/packages/platform/src/engine/config/env.ts index 5d94e18a9..1be661c5a 100644 --- a/packages/platform/src/engine/config/env.ts +++ b/packages/platform/src/engine/config/env.ts @@ -376,7 +376,7 @@ const envSchema = z.object({ OBLIEN_CLIENT_SECRET: z.string().optional(), /** Control-plane endpoint. Override only for an Oblien staging installation. */ OBLIEN_API_URL: z.url().optional(), - OBLIEN_RUNTIME_URL: z.url().default("https://workspace.oblien.com"), + OBLIEN_RUNTIME_URL: z.url().default("https://vm.oblien.com"), /** Optional published software preset for NEW managed Docker workspaces. */ OBLIEN_DOCKER_PRESET: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(), /** diff --git a/packages/platform/src/engine/lib/cloud-preflight.ts b/packages/platform/src/engine/lib/cloud-preflight.ts index 67f55292b..b3256be79 100644 --- a/packages/platform/src/engine/lib/cloud-preflight.ts +++ b/packages/platform/src/engine/lib/cloud-preflight.ts @@ -1,6 +1,5 @@ -import { oblienApiBaseUrl } from "@repo/adapters"; import { reportCaughtError as observeCaughtError, diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; -import { createPlatform, type CloudInfraProvider } from "@repo/adapters"; +import { createPlatform, oblienApiBaseUrl, type CloudInfraProvider } from "@repo/adapters"; import { ensureNamespace, getOblienClient, issueNamespaceToken } from "./openship-cloud"; import { env } from "../config/env"; import { assertCloudCanSpend } from "../modules/billing/billing-oblien-quota"; diff --git a/packages/platform/src/engine/lib/oblien-billing-api.ts b/packages/platform/src/engine/lib/oblien-billing-api.ts index 4cfa98bee..215024175 100644 --- a/packages/platform/src/engine/lib/oblien-billing-api.ts +++ b/packages/platform/src/engine/lib/oblien-billing-api.ts @@ -332,7 +332,7 @@ export class OblienBillingApi { private async requestBilling({ method, path, body, query }: Parameters[0]): Promise { const meteredPricing = method === "GET" && path === "/pricing/calculator"; if (!path.startsWith("/billing/") && !meteredPricing) throw new Error("Billing transport only accepts billing routes"); - const url = new URL(`${this.baseUrl}${path}`); + const url = oblienApiUrl(oblienApiBaseUrl(this.baseUrl), path); for (const [key, value] of Object.entries(query ?? {})) { if (value !== undefined) url.searchParams.set(key, String(value)); } diff --git a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts index a3211e1c9..6140a439c 100644 --- a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts +++ b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts @@ -14,7 +14,8 @@ export function creditAlertNotification(input: { const { eventType, eventId, data, entitlement, organizationId } = input; // Late credit events cannot turn a paid capacity contract into a credit alert. if (entitlement.tierId === "capacity") return null; - if (data.service !== undefined && data.service !== "workspace_vm") return null; + // Signed deliveries queued before the VM API cutover can still name the old service. + if (data.service !== undefined && data.service !== "vm_compute" && data.service !== "workspace_vm") return null; const alert = entitlement.quota.alert; if (!alert || !["low", "grace", "depleted"].includes(alert.state)) return null; const created = diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts index 4304fe097..e14a9978f 100644 --- a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts +++ b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts @@ -40,7 +40,7 @@ interface OblienUsageBucket { interface OblienWebhookData { namespace?: string; vm_id?: string; - workspace_name?: string; + vm_name?: string; service?: string; /** credits.usage */ balance?: number; diff --git a/packages/platform/src/engine/modules/system/server-managed.operations.ts b/packages/platform/src/engine/modules/system/server-managed.operations.ts index 36811293f..ab41cb5a3 100644 --- a/packages/platform/src/engine/modules/system/server-managed.operations.ts +++ b/packages/platform/src/engine/modules/system/server-managed.operations.ts @@ -75,8 +75,8 @@ async function runtimeCredential(connection: ManagedConnection) { } if ( !result.token || - claims.type !== "workspace" || - claims.workspace_id !== connection.binding.workspaceId || + claims.type !== "vm" || + claims.vm_id !== connection.binding.workspaceId || typeof claims.token !== "string" || claims.token.length < 16 || typeof claims.exp !== "number" || From 9620e08ec9ab6d9edbb8797b40a1472748073919 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 22:09:06 +0200 Subject: [PATCH 6/6] Preserve the documented hosted checkout URL across the API cutover --- .../modules/billing/oblien-billing-api.test.ts | 16 +++++++++------- docs/openship-cloud-launch.md | 4 ++++ .../src/engine/lib/oblien-billing-api.ts | 3 ++- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/api/src/modules/billing/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts index 5c991d871..881c093c6 100644 --- a/apps/api/src/modules/billing/oblien-billing-api.test.ts +++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts @@ -279,21 +279,23 @@ describe("Oblien billing SDK and transport contract", () => { expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true }); }); - it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => { + it("keeps the hosted payment page unversioned while sending checkout requests to /v1", async () => { const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee"; - const url = `https://api.oblien.com/v1/billing/pay#${"a".repeat(43)}`; - const { api } = setup({ success: true, url, checkoutId }); + const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`; + const { api, fetcher } = setup({ success: true, url, checkoutId }); await expect(api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata, successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "promotion-checkout" })) .resolves.toMatchObject({ url, checkoutId }); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); }); it.each([ "http://api.oblien.com/billing/pay", "https://api.oblien.com.evil.example/billing/pay", - "https://api.oblien.com/v1/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other", - "https://api.oblien.com/v1/billing/pay", "https://user@api.oblien.com/billing/pay", - "https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/v1/billing/pay/", + "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other", + "https://api.oblien.com/billing/pay", "https://user@api.oblien.com/billing/pay", + "https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/billing/pay/", + "https://api.oblien.com/v1/billing/pay", ])("rejects an invalid promotion checkout URL: %s", async (value) => { - const url = value + (value === "https://api.oblien.com/v1/billing/pay" ? "#short" : `#${"a".repeat(43)}`); + const url = value + (value === "https://api.oblien.com/billing/pay" ? "#short" : `#${"a".repeat(43)}`); await expect(setup({ success: true, url, checkoutId: "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee" }).api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata, successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "bad-promotion-checkout" })) diff --git a/docs/openship-cloud-launch.md b/docs/openship-cloud-launch.md index 3c733cdb8..51b2f7784 100644 --- a/docs/openship-cloud-launch.md +++ b/docs/openship-cloud-launch.md @@ -813,6 +813,10 @@ operator needs a proxy, the override must be the complete API mount including its version. Remove a previously configured unversioned provider origin during the coordinated cutover. +The custom checkout browser page remains `https://api.oblien.com/billing/pay`. +Only its control-plane creation/status requests use `/v1`; do not rewrite the +returned payment URL or apply the API mount to Runtime/CDN URLs. + Activate the matching Oblien `/v1` API and migrated database before deploying this integration. Older SDK routes are not probed and failed writes are not replayed. OpenShip's organization/workspace records, managed-server IDs, paid diff --git a/packages/platform/src/engine/lib/oblien-billing-api.ts b/packages/platform/src/engine/lib/oblien-billing-api.ts index 215024175..f03eb63ce 100644 --- a/packages/platform/src/engine/lib/oblien-billing-api.ts +++ b/packages/platform/src/engine/lib/oblien-billing-api.ts @@ -700,7 +700,8 @@ export class OblienBillingApi { const url = new URL(value); if (url.hostname === "api.oblien.com") { this.validateHostedUrl(value, "api.oblien.com"); - if (url.pathname === oblienApiUrl(oblienApiBaseUrl(), "/billing/pay").pathname && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return; + // This is the hosted browser page, not a versioned control-plane endpoint. + if (url.pathname === "/billing/pay" && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return; throw new AppError("Cloud billing returned an invalid hosted URL", 502, "OBLIEN_BILLING_INVALID_RESPONSE"); } this.validateHostedUrl(value, "checkout.stripe.com");