mirror of
https://github.com/Dokploy/dokploy.git
synced 2026-12-03 22:55:45 +00:00
feat(cloud-servers): billing lifecycle, bandwidth metering and typed DigitalOcean client
- Non-payment flow: reminder emails 7, 3 and 1 days before a renewal with a missing or expiring card, power off when the renewal fails, last charge attempt and deletion after 2 days - Deleting a server credits the unused paid time to the customer balance, with the first hour always charged - Bandwidth is metered per server, warned at 80% and 100% of the plan allowance and billed at $0.03 per GB on the renewal invoice - No cloud_server row is created until the checkout is paid - One VPC per organization and region, firewall is opt-in - DigitalOcean client generated from the OpenAPI spec (openapi-fetch) - Cloud servers no longer count towards the plan's server quantity - Email templates point to a pinned Dokploy logo
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import type Stripe from "stripe";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
record: null as Record<string, unknown> | null,
|
||||
updateCloudServer: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server", () => ({}));
|
||||
vi.mock("@dokploy/server/services/cloud-server", () => ({
|
||||
findCloudServerBySubscriptionId: async () => mocks.record,
|
||||
updateCloudServer: mocks.updateCloudServer,
|
||||
}));
|
||||
vi.mock("@/server/utils/cloud-server-notifications", () => ({}));
|
||||
vi.mock("@/server/utils/billing", () => ({
|
||||
getStripeClient: () => stripe,
|
||||
}));
|
||||
vi.mock("@/server/utils/stripe", () => ({}));
|
||||
|
||||
const { cancelCloudServerSubscription } = await import(
|
||||
"@/server/utils/cloud-server-billing"
|
||||
);
|
||||
|
||||
const GB = 1024 ** 3;
|
||||
const retrieve = vi.fn();
|
||||
const cancel = vi.fn();
|
||||
const createInvoiceItem = vi.fn();
|
||||
const finalizeInvoice = vi.fn();
|
||||
const stripe = {
|
||||
subscriptions: { retrieve, cancel },
|
||||
invoiceItems: { create: createInvoiceItem },
|
||||
invoices: { finalizeInvoice },
|
||||
} as unknown as Stripe;
|
||||
|
||||
const NOW = "2026-11-24T10:00:00.000Z";
|
||||
const paid = (startedAt: string) => ({
|
||||
status: "active",
|
||||
latest_invoice: { status: "paid" },
|
||||
start_date: Date.parse(startedAt) / 1000,
|
||||
current_period_start: Date.parse("2026-11-24T00:00:00.000Z") / 1000,
|
||||
current_period_end: Date.parse("2026-12-24T00:00:00.000Z") / 1000,
|
||||
items: { data: [{ price: { unit_amount: 1999 } }] },
|
||||
});
|
||||
|
||||
describe("cloud server cancellation credit", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(NOW));
|
||||
for (const mock of [retrieve, cancel, createInvoiceItem, finalizeInvoice]) {
|
||||
mock.mockReset();
|
||||
}
|
||||
mocks.updateCloudServer.mockReset();
|
||||
mocks.record = { cloudServerId: "cs-1", plan: "hobby", bandwidthBytes: 0 };
|
||||
retrieve.mockResolvedValue(paid("2026-11-10T10:00:00.000Z"));
|
||||
cancel.mockResolvedValue({
|
||||
latest_invoice: {
|
||||
id: "in_final",
|
||||
subscription: "sub_1",
|
||||
customer: "cus_1",
|
||||
currency: "usd",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("charges a full hour for a server deleted 5 minutes after it was bought", async () => {
|
||||
retrieve.mockResolvedValue(paid("2026-11-24T09:55:00.000Z"));
|
||||
|
||||
await cancelCloudServerSubscription("sub_1", {
|
||||
creditUnusedTime: true,
|
||||
});
|
||||
|
||||
expect(createInvoiceItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ invoice: "in_final", amount: 3 }),
|
||||
{ idempotencyKey: "cloud-server-minimum-in_final" },
|
||||
);
|
||||
});
|
||||
|
||||
it("credits the unused time right away when the customer deletes a paid server", async () => {
|
||||
await cancelCloudServerSubscription("sub_1", {
|
||||
creditUnusedTime: true,
|
||||
});
|
||||
|
||||
expect(cancel).toHaveBeenCalledWith("sub_1", {
|
||||
invoice_now: true,
|
||||
prorate: true,
|
||||
expand: ["latest_invoice"],
|
||||
});
|
||||
expect(createInvoiceItem).not.toHaveBeenCalled();
|
||||
expect(finalizeInvoice).toHaveBeenCalledWith("in_final");
|
||||
});
|
||||
|
||||
it("takes the extra bandwidth out of the credit", async () => {
|
||||
mocks.record = {
|
||||
cloudServerId: "cs-1",
|
||||
plan: "starter",
|
||||
bandwidthBytes: 4050 * GB,
|
||||
};
|
||||
|
||||
await cancelCloudServerSubscription("sub_1", {
|
||||
creditUnusedTime: true,
|
||||
});
|
||||
|
||||
expect(createInvoiceItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ invoice: "in_final", amount: 150 }),
|
||||
{ idempotencyKey: "cloud-server-bandwidth-in_final" },
|
||||
);
|
||||
expect(createInvoiceItem.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
finalizeInvoice.mock.invocationCallOrder[0] as number,
|
||||
);
|
||||
});
|
||||
|
||||
it("gives no credit for a period that was never paid", async () => {
|
||||
retrieve.mockResolvedValue({
|
||||
status: "past_due",
|
||||
latest_invoice: { status: "open" },
|
||||
});
|
||||
|
||||
await cancelCloudServerSubscription("sub_1", {
|
||||
creditUnusedTime: true,
|
||||
});
|
||||
|
||||
expect(cancel).toHaveBeenCalledWith("sub_1", {
|
||||
invoice_now: false,
|
||||
prorate: false,
|
||||
expand: ["latest_invoice"],
|
||||
});
|
||||
expect(finalizeInvoice).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("gives no credit when Dokploy removes the server for non-payment", async () => {
|
||||
await cancelCloudServerSubscription("sub_1");
|
||||
|
||||
expect(cancel).toHaveBeenCalledWith("sub_1", {
|
||||
invoice_now: false,
|
||||
prorate: false,
|
||||
expand: ["latest_invoice"],
|
||||
});
|
||||
expect(finalizeInvoice).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type Stripe from "stripe";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
organization: { id: "org-1" } as { id: string } | undefined,
|
||||
createCloudServer: vi.fn(),
|
||||
provisionCloudServer: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server", () => ({
|
||||
findOrganizationById: async () => mocks.organization,
|
||||
}));
|
||||
vi.mock("@dokploy/server/services/cloud-server", () => ({
|
||||
buildCloudServerHostname: () => "acme-x7k2p9",
|
||||
createCloudServer: mocks.createCloudServer,
|
||||
provisionCloudServer: mocks.provisionCloudServer,
|
||||
}));
|
||||
vi.mock("@/server/utils/cloud-server-notifications", () => ({}));
|
||||
vi.mock("@/server/utils/billing", () => ({
|
||||
getStripeClient: () => stripe,
|
||||
CLOUD_SERVER_METADATA_TYPE: "cloud_server",
|
||||
}));
|
||||
vi.mock("@/server/utils/stripe", () => ({}));
|
||||
|
||||
const { handleCloudServerEvent } = await import(
|
||||
"@/server/utils/cloud-server-billing"
|
||||
);
|
||||
|
||||
const retrieve = vi.fn();
|
||||
const cancel = vi.fn();
|
||||
const refund = vi.fn();
|
||||
const stripe = {
|
||||
subscriptions: { retrieve, cancel },
|
||||
refunds: { create: refund },
|
||||
} as unknown as Stripe;
|
||||
|
||||
const checkoutCompleted = (metadata: Record<string, string>) =>
|
||||
({
|
||||
type: "checkout.session.completed",
|
||||
data: {
|
||||
object: { id: "cs_1", subscription: "sub_1", metadata },
|
||||
},
|
||||
}) as unknown as Stripe.Event;
|
||||
|
||||
const order = {
|
||||
type: "cloud_server",
|
||||
cloudServerId: "cs-1",
|
||||
organizationId: "org-1",
|
||||
plan: "starter",
|
||||
zone: "nyc1",
|
||||
};
|
||||
|
||||
describe("cloud server checkout", () => {
|
||||
beforeEach(() => {
|
||||
for (const mock of [retrieve, cancel, refund]) mock.mockReset();
|
||||
mocks.createCloudServer.mockReset();
|
||||
mocks.provisionCloudServer.mockReset();
|
||||
mocks.provisionCloudServer.mockResolvedValue(undefined);
|
||||
mocks.organization = { id: "org-1" };
|
||||
retrieve.mockResolvedValue({
|
||||
status: "active",
|
||||
latest_invoice: { paid: true, amount_paid: 3999, payment_intent: "pi_1" },
|
||||
});
|
||||
cancel.mockResolvedValue({});
|
||||
});
|
||||
|
||||
it("creates the server from the paid order and provisions it", async () => {
|
||||
mocks.createCloudServer.mockImplementation(async (input) => input);
|
||||
|
||||
const handled = await handleCloudServerEvent(
|
||||
stripe,
|
||||
checkoutCompleted(order),
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(mocks.createCloudServer).toHaveBeenCalledWith({
|
||||
cloudServerId: "cs-1",
|
||||
organizationId: "org-1",
|
||||
plan: "starter",
|
||||
zone: "nyc1",
|
||||
hostname: "acme-x7k2p9",
|
||||
status: "provisioning",
|
||||
stripeSubscriptionId: "sub_1",
|
||||
stripeCheckoutSessionId: "cs_1",
|
||||
});
|
||||
expect(mocks.provisionCloudServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
cloudServerId: "cs-1",
|
||||
zone: "nyc1",
|
||||
hostname: "acme-x7k2p9",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("provisions once when Stripe delivers the webhook twice", async () => {
|
||||
mocks.createCloudServer.mockResolvedValue(undefined);
|
||||
|
||||
await handleCloudServerEvent(stripe, checkoutCompleted(order));
|
||||
|
||||
expect(mocks.provisionCloudServer).not.toHaveBeenCalled();
|
||||
expect(refund).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refunds a payment whose organization no longer exists", async () => {
|
||||
mocks.organization = undefined;
|
||||
|
||||
await handleCloudServerEvent(stripe, checkoutCompleted(order));
|
||||
|
||||
expect(mocks.createCloudServer).not.toHaveBeenCalled();
|
||||
expect(cancel).toHaveBeenCalledWith("sub_1", expect.anything());
|
||||
expect(refund).toHaveBeenCalledWith({ payment_intent: "pi_1" });
|
||||
});
|
||||
|
||||
it("leaves other checkouts to the plan logic", async () => {
|
||||
const handled = await handleCloudServerEvent(
|
||||
stripe,
|
||||
checkoutCompleted({ adminId: "user-1" }),
|
||||
);
|
||||
|
||||
expect(handled).toBe(false);
|
||||
expect(mocks.createCloudServer).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -29,9 +29,7 @@ describe("default VPC of a region", () => {
|
||||
});
|
||||
|
||||
const requests = () =>
|
||||
fetchMock.mock.calls.map(
|
||||
([url, options]) => `${options?.method ?? "GET"} ${url}`,
|
||||
);
|
||||
fetchMock.mock.calls.map(([request]) => `${request.method} ${request.url}`);
|
||||
|
||||
it("finds the default VPC when it sits past the first 200", async () => {
|
||||
fetchMock
|
||||
@@ -57,7 +55,7 @@ describe("default VPC of a region", () => {
|
||||
await ensureDigitalOceanDefaultVpc("tor1");
|
||||
|
||||
expect(requests().at(-1)).toMatch(/^POST .*\/vpcs$/);
|
||||
expect(JSON.parse(fetchMock.mock.calls.at(-1)?.[1].body)).toMatchObject({
|
||||
expect(await fetchMock.mock.calls.at(-1)?.[0].json()).toMatchObject({
|
||||
name: "default-tor1",
|
||||
region: "tor1",
|
||||
});
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import type Stripe from "stripe";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
record: null as Record<string, unknown> | null,
|
||||
updateCloudServer: vi.fn(),
|
||||
createInvoiceItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server", () => ({}));
|
||||
vi.mock("@dokploy/server/services/cloud-server", () => ({
|
||||
findCloudServerBySubscriptionId: async () => mocks.record,
|
||||
updateCloudServer: mocks.updateCloudServer,
|
||||
}));
|
||||
vi.mock("@/server/utils/billing", () => ({
|
||||
CLOUD_SERVER_METADATA_TYPE: "cloud_server",
|
||||
}));
|
||||
vi.mock("@/server/utils/stripe", () => ({}));
|
||||
|
||||
const { handleCloudServerEvent } = await import(
|
||||
"@/server/utils/cloud-server-billing"
|
||||
);
|
||||
|
||||
const GB = 1024 ** 3;
|
||||
const stripe = {
|
||||
invoiceItems: { create: mocks.createInvoiceItem },
|
||||
} as unknown as Stripe;
|
||||
|
||||
const invoiceCreated = (overrides: Record<string, unknown> = {}) =>
|
||||
({
|
||||
type: "invoice.created",
|
||||
data: {
|
||||
object: {
|
||||
id: "in_1",
|
||||
customer: "cus_1",
|
||||
subscription: "sub_1",
|
||||
currency: "usd",
|
||||
billing_reason: "subscription_cycle",
|
||||
subscription_details: {
|
||||
metadata: { type: "cloud_server", cloudServerId: "cs-1" },
|
||||
},
|
||||
...overrides,
|
||||
},
|
||||
},
|
||||
}) as unknown as Stripe.Event;
|
||||
|
||||
describe("cloud server extra bandwidth", () => {
|
||||
beforeEach(() => {
|
||||
mocks.updateCloudServer.mockReset();
|
||||
mocks.createInvoiceItem.mockReset();
|
||||
mocks.record = {
|
||||
cloudServerId: "cs-1",
|
||||
plan: "starter",
|
||||
bandwidthBytes: 4120 * GB,
|
||||
};
|
||||
});
|
||||
|
||||
it("adds the traffic over the plan allowance to the renewal invoice", async () => {
|
||||
const handled = await handleCloudServerEvent(stripe, invoiceCreated());
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(mocks.createInvoiceItem).toHaveBeenCalledWith(
|
||||
{
|
||||
customer: "cus_1",
|
||||
invoice: "in_1",
|
||||
amount: 360,
|
||||
currency: "usd",
|
||||
description: "Extra bandwidth: 120 GB",
|
||||
},
|
||||
{ idempotencyKey: "cloud-server-bandwidth-in_1" },
|
||||
);
|
||||
expect(mocks.updateCloudServer).toHaveBeenCalledWith("cs-1", {
|
||||
bandwidthBytes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a new period without a charge when the allowance was enough", async () => {
|
||||
mocks.record = { ...mocks.record, bandwidthBytes: 4000 * GB };
|
||||
|
||||
await handleCloudServerEvent(stripe, invoiceCreated());
|
||||
|
||||
expect(mocks.createInvoiceItem).not.toHaveBeenCalled();
|
||||
expect(mocks.updateCloudServer).toHaveBeenCalledWith("cs-1", {
|
||||
bandwidthBytes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves upgrade invoices alone", async () => {
|
||||
const handled = await handleCloudServerEvent(
|
||||
stripe,
|
||||
invoiceCreated({ billing_reason: "subscription_update" }),
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(mocks.createInvoiceItem).not.toHaveBeenCalled();
|
||||
expect(mocks.updateCloudServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores invoices of other subscriptions", async () => {
|
||||
const handled = await handleCloudServerEvent(
|
||||
stripe,
|
||||
invoiceCreated({ subscription_details: { metadata: {} } }),
|
||||
);
|
||||
|
||||
expect(handled).toBe(false);
|
||||
expect(mocks.createInvoiceItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,6 @@ const ANYWHERE = ["0.0.0.0/0", "::/0"];
|
||||
const mocks = vi.hoisted(() => ({
|
||||
record: {} as Record<string, unknown>,
|
||||
updates: [] as Record<string, unknown>[],
|
||||
calls: [] as string[],
|
||||
doFirewallRules: [] as unknown[],
|
||||
createFirewall: vi.fn(),
|
||||
updateFirewall: vi.fn(),
|
||||
@@ -14,6 +13,7 @@ const mocks = vi.hoisted(() => ({
|
||||
createVpc: vi.fn(),
|
||||
dropletCount: vi.fn(),
|
||||
getVpcRange: vi.fn(),
|
||||
deleteSshKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server/db", () => {
|
||||
@@ -46,7 +46,7 @@ vi.mock("@dokploy/server/utils/digitalocean", () => ({
|
||||
createDigitalOceanVpc: mocks.createVpc,
|
||||
getDigitalOceanVpcRange: mocks.getVpcRange,
|
||||
createDigitalOceanSshKey: vi.fn(async () => 1),
|
||||
deleteDigitalOceanSshKey: vi.fn(async () => undefined),
|
||||
deleteDigitalOceanSshKey: mocks.deleteSshKey,
|
||||
createDigitalOceanFirewall: mocks.createFirewall,
|
||||
updateDigitalOceanFirewall: mocks.updateFirewall,
|
||||
createDigitalOceanDroplet: mocks.createDroplet,
|
||||
@@ -71,6 +71,7 @@ vi.mock("@dokploy/server/utils/filesystem/ssh", () => ({
|
||||
|
||||
const {
|
||||
assertCloudServerCapacity,
|
||||
buildCloudServerHostname,
|
||||
getCloudServerFirewall,
|
||||
provisionCloudServer,
|
||||
updateCloudServerFirewall,
|
||||
@@ -85,7 +86,7 @@ const readyRecord = (overrides: Record<string, unknown> = {}) =>
|
||||
status: "ready",
|
||||
hostname: "dokploy-org1-abc",
|
||||
providerVmId: "123",
|
||||
providerNetworkId: "vpc-1",
|
||||
providerVpcId: "vpc-1",
|
||||
providerFirewallId: "fw-1",
|
||||
serverId: "server-1",
|
||||
...overrides,
|
||||
@@ -111,37 +112,34 @@ const sentRules = (mock: typeof mocks.createFirewall) =>
|
||||
describe("cloud server firewall", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.record = { providerNetworkId: "vpc-1" };
|
||||
mocks.record = { providerVpcId: "vpc-1" };
|
||||
mocks.updates = [];
|
||||
mocks.calls = [];
|
||||
mocks.doFirewallRules = [];
|
||||
mocks.getVpcRange.mockResolvedValue(VPC_RANGE);
|
||||
mocks.createVpc.mockResolvedValue("vpc-new");
|
||||
mocks.createFirewall.mockImplementation(async () => {
|
||||
mocks.calls.push("firewall");
|
||||
return "fw-new";
|
||||
});
|
||||
mocks.createDroplet.mockImplementation(async () => {
|
||||
mocks.calls.push("droplet");
|
||||
throw new Error("droplet limit reached");
|
||||
});
|
||||
mocks.createFirewall.mockResolvedValue("fw-new");
|
||||
mocks.createDroplet.mockRejectedValue(new Error("droplet limit reached"));
|
||||
mocks.deleteSshKey.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("creates the firewall before the droplet and keeps its id when the droplet fails", async () => {
|
||||
it("keeps trying to delete the temporary DO ssh key while DigitalOcean answers 404", async () => {
|
||||
vi.useFakeTimers();
|
||||
mocks.deleteSshKey
|
||||
.mockRejectedValueOnce(new Error("404"))
|
||||
.mockRejectedValueOnce(new Error("404"));
|
||||
|
||||
await expect(provision()).rejects.toThrow("droplet limit reached");
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
|
||||
expect(mocks.deleteSshKey).toHaveBeenCalledTimes(3);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("delivers a new server without a firewall", async () => {
|
||||
await expect(provision()).rejects.toThrow("droplet limit reached");
|
||||
|
||||
expect(mocks.calls).toEqual(["firewall", "droplet"]);
|
||||
expect(mocks.updates).toContainEqual(
|
||||
expect.objectContaining({ providerFirewallId: "fw-new" }),
|
||||
);
|
||||
expect(mocks.createFirewall.mock.calls[0]?.[0].tag).toBe("dokploy-cs:cs-1");
|
||||
});
|
||||
|
||||
it("never creates the droplet when the firewall can't be created", async () => {
|
||||
mocks.createFirewall.mockRejectedValue(new Error("firewall quota"));
|
||||
|
||||
await expect(provision()).rejects.toThrow("firewall quota");
|
||||
expect(mocks.createDroplet).not.toHaveBeenCalled();
|
||||
expect(mocks.createDroplet).toHaveBeenCalled();
|
||||
expect(mocks.createFirewall).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the VPC after the whole organization id, swapping the characters DO rejects", async () => {
|
||||
@@ -150,7 +148,7 @@ describe("cloud server firewall", () => {
|
||||
await provision("N7cQ83ecdyLqC-wO_kkdm").catch(() => undefined);
|
||||
|
||||
expect(mocks.createVpc.mock.calls[0]?.[0].name).toMatch(
|
||||
/^dokploy-N7cQ83ecdyLqC-wO\.kkdm-sfo2-[a-z0-9]{4}$/,
|
||||
/^dokploy-N7cQ83ecdyLqC-wO-kkdm-sfo2-[a-z0-9]{4}$/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -161,8 +159,12 @@ describe("cloud server firewall", () => {
|
||||
expect(mocks.createDroplet.mock.calls[0]?.[0].vpcId).toBe("vpc-1");
|
||||
});
|
||||
|
||||
it("opens only ssh, monitoring, web and the organization's own VPC by default", async () => {
|
||||
await provision().catch(() => undefined);
|
||||
it("opens only ssh, monitoring, web and the organization's own VPC when the customer enables it", async () => {
|
||||
const record = readyRecord({ providerFirewallId: null });
|
||||
mocks.record = record as unknown as Record<string, unknown>;
|
||||
|
||||
const { rules } = await getCloudServerFirewall(record);
|
||||
await updateCloudServerFirewall(record, rules);
|
||||
|
||||
expect(sentRules(mocks.createFirewall)).toEqual([
|
||||
{ protocol: "tcp", ports: "22", sources: { addresses: ANYWHERE } },
|
||||
@@ -179,8 +181,13 @@ describe("cloud server firewall", () => {
|
||||
},
|
||||
{ protocol: "tcp", ports: "80", sources: { addresses: ANYWHERE } },
|
||||
{ protocol: "tcp", ports: "443", sources: { addresses: ANYWHERE } },
|
||||
{ protocol: "icmp", sources: { addresses: ANYWHERE } },
|
||||
{
|
||||
protocol: "icmp",
|
||||
ports: "0",
|
||||
sources: { addresses: ANYWHERE },
|
||||
},
|
||||
]);
|
||||
expect(mocks.createFirewall.mock.calls[0]?.[0].tag).toBe("dokploy-cs:cs-1");
|
||||
});
|
||||
|
||||
it("lists the private network as a locked rule and hides it from the editable ones", async () => {
|
||||
@@ -256,7 +263,7 @@ describe("cloud server firewall", () => {
|
||||
|
||||
it("skips the private network rule for a server without a VPC", async () => {
|
||||
const firewall = await getCloudServerFirewall(
|
||||
readyRecord({ providerNetworkId: null }),
|
||||
readyRecord({ providerVpcId: null }),
|
||||
);
|
||||
|
||||
expect(mocks.getVpcRange).not.toHaveBeenCalled();
|
||||
@@ -269,6 +276,16 @@ describe("cloud server firewall", () => {
|
||||
).rejects.toThrow("Server is not ready");
|
||||
});
|
||||
|
||||
describe("hostname", () => {
|
||||
it("only uses characters DO accepts in firewall and droplet names", () => {
|
||||
for (let i = 0; i < 2000; i++) {
|
||||
expect(buildCloudServerHostname("N7cQ83ecdyLqC-wO_kkdm")).toMatch(
|
||||
/^dokploy-N7cQ83ecdyLqC-wO-kkdm-[a-z0-9]{6}$/,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("capacity", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import Stripe from "stripe";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
suspended: [] as Record<string, unknown>[],
|
||||
found: null as Record<string, unknown> | null,
|
||||
measured: [] as { previous: unknown; current: unknown }[],
|
||||
updateCloudServer: vi.fn(),
|
||||
terminateCloudServer: vi.fn(),
|
||||
resumeCloudServer: vi.fn(),
|
||||
sendDeleted: vi.fn(),
|
||||
sendReactivated: vi.fn(),
|
||||
sendBandwidth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server", () => ({}));
|
||||
vi.mock("@dokploy/server/services/cloud-server", () => ({
|
||||
findSuspendedCloudServersBefore: async () => mocks.suspended,
|
||||
findCloudServerBySubscriptionId: async () => mocks.found,
|
||||
recordCloudServersBandwidth: async () => mocks.measured,
|
||||
updateCloudServer: mocks.updateCloudServer,
|
||||
terminateCloudServer: mocks.terminateCloudServer,
|
||||
resumeCloudServer: mocks.resumeCloudServer,
|
||||
}));
|
||||
vi.mock("@/server/utils/cloud-server-notifications", () => ({
|
||||
sendCloudServerDeletedEmail: mocks.sendDeleted,
|
||||
sendCloudServerReactivatedEmail: mocks.sendReactivated,
|
||||
sendCloudServerBandwidthEmail: mocks.sendBandwidth,
|
||||
}));
|
||||
vi.mock("@/server/utils/billing", () => ({
|
||||
getStripeClient: () => stripe,
|
||||
CLOUD_SERVER_METADATA_TYPE: "cloud_server",
|
||||
isCloudServerSubscription: () => true,
|
||||
}));
|
||||
vi.mock("@/server/utils/stripe", () => ({}));
|
||||
|
||||
const {
|
||||
handleCloudServerEvent,
|
||||
recordBandwidthAndWarn,
|
||||
removeUnpaidCloudServers,
|
||||
} = await import("@/server/utils/cloud-server-billing");
|
||||
|
||||
const NOW = "2026-11-24T10:00:00.000Z";
|
||||
const GB = 1024 ** 3;
|
||||
const retrieve = vi.fn();
|
||||
const update = vi.fn();
|
||||
const cancel = vi.fn();
|
||||
const pay = vi.fn();
|
||||
const stripe = {
|
||||
subscriptions: { retrieve, update, cancel },
|
||||
invoices: { pay },
|
||||
} as unknown as Stripe;
|
||||
|
||||
const server = (overrides: Record<string, unknown> = {}) => ({
|
||||
cloudServerId: "cs-1",
|
||||
status: "suspended",
|
||||
plan: "hobby",
|
||||
stripeSubscriptionId: "sub_1",
|
||||
providerVmId: "101",
|
||||
suspendedAt: "2026-11-22T09:00:00.000Z",
|
||||
bandwidthBytes: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const unpaid = (customerCard: string | null = null) => ({
|
||||
id: "sub_1",
|
||||
status: "past_due",
|
||||
latest_invoice: { id: "in_1", status: "open" },
|
||||
customer: { invoice_settings: { default_payment_method: customerCard } },
|
||||
});
|
||||
|
||||
describe("cloud server non-payment", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(NOW));
|
||||
for (const mock of [retrieve, update, cancel, pay]) {
|
||||
mock.mockReset();
|
||||
}
|
||||
for (const mock of Object.values(mocks)) {
|
||||
if (typeof mock === "function") mock.mockReset();
|
||||
}
|
||||
mocks.suspended = [server()];
|
||||
mocks.found = null;
|
||||
mocks.measured = [];
|
||||
mocks.sendDeleted.mockResolvedValue(undefined);
|
||||
mocks.sendReactivated.mockResolvedValue(undefined);
|
||||
mocks.sendBandwidth.mockResolvedValue(undefined);
|
||||
cancel.mockResolvedValue({});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("deletes the server and tells the customer when the last charge is declined", async () => {
|
||||
retrieve.mockResolvedValue(unpaid());
|
||||
pay.mockRejectedValue(
|
||||
new Stripe.errors.StripeCardError({
|
||||
type: "card_error",
|
||||
message: "Your card was declined.",
|
||||
}),
|
||||
);
|
||||
|
||||
await removeUnpaidCloudServers();
|
||||
|
||||
expect(pay).toHaveBeenCalledWith("in_1");
|
||||
expect(cancel).toHaveBeenCalledWith("sub_1", expect.anything());
|
||||
expect(mocks.terminateCloudServer).toHaveBeenCalledWith("cs-1");
|
||||
expect(mocks.sendDeleted).toHaveBeenCalledWith(mocks.suspended[0]);
|
||||
});
|
||||
|
||||
it("keeps the server when the last charge goes through with the card the customer added", async () => {
|
||||
retrieve.mockResolvedValue(unpaid("pm_new"));
|
||||
pay.mockResolvedValue({ status: "paid" });
|
||||
|
||||
await removeUnpaidCloudServers();
|
||||
|
||||
expect(update).toHaveBeenCalledWith("sub_1", {
|
||||
default_payment_method: "pm_new",
|
||||
});
|
||||
expect(mocks.terminateCloudServer).not.toHaveBeenCalled();
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resumes a paid server whose webhook was missed instead of deleting it", async () => {
|
||||
retrieve.mockResolvedValue({ ...unpaid(), status: "active" });
|
||||
|
||||
await removeUnpaidCloudServers();
|
||||
|
||||
expect(pay).not.toHaveBeenCalled();
|
||||
expect(mocks.resumeCloudServer).toHaveBeenCalledWith(mocks.suspended[0]);
|
||||
expect(mocks.sendReactivated).toHaveBeenCalled();
|
||||
expect(mocks.terminateCloudServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not delete anything while Stripe is failing", async () => {
|
||||
retrieve.mockResolvedValue(unpaid());
|
||||
pay.mockRejectedValue(new Error("Stripe is down"));
|
||||
|
||||
await removeUnpaidCloudServers();
|
||||
|
||||
expect(mocks.terminateCloudServer).not.toHaveBeenCalled();
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("powers the server back on and emails when the payment arrives", async () => {
|
||||
mocks.found = server();
|
||||
|
||||
await handleCloudServerEvent(stripe, {
|
||||
type: "customer.subscription.updated",
|
||||
data: { object: { id: "sub_1", status: "active" } },
|
||||
} as unknown as Stripe.Event);
|
||||
|
||||
expect(mocks.resumeCloudServer).toHaveBeenCalledWith(mocks.found);
|
||||
expect(mocks.sendReactivated).toHaveBeenCalledWith(mocks.found);
|
||||
});
|
||||
|
||||
it("does not email on updates of a server that was never suspended", async () => {
|
||||
mocks.found = server({ status: "ready" });
|
||||
|
||||
await handleCloudServerEvent(stripe, {
|
||||
type: "customer.subscription.updated",
|
||||
data: { object: { id: "sub_1", status: "active" } },
|
||||
} as unknown as Stripe.Event);
|
||||
|
||||
expect(mocks.resumeCloudServer).not.toHaveBeenCalled();
|
||||
expect(mocks.sendReactivated).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("warns once when the transfer crosses 80% and again at 100%", async () => {
|
||||
const at = (gb: number) => server({ bandwidthBytes: gb * GB });
|
||||
mocks.measured = [{ previous: at(1500), current: at(1650) }];
|
||||
await recordBandwidthAndWarn();
|
||||
expect(mocks.sendBandwidth).toHaveBeenLastCalledWith(at(1650), 80, 2);
|
||||
|
||||
mocks.measured = [{ previous: at(1650), current: at(1900) }];
|
||||
await recordBandwidthAndWarn();
|
||||
expect(mocks.sendBandwidth).toHaveBeenCalledTimes(1);
|
||||
|
||||
mocks.measured = [{ previous: at(1900), current: at(2100) }];
|
||||
await recordBandwidthAndWarn();
|
||||
expect(mocks.sendBandwidth).toHaveBeenLastCalledWith(at(2100), 100, 2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import type Stripe from "stripe";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
ready: [] as Record<string, unknown>[],
|
||||
found: null as Record<string, unknown> | null,
|
||||
claim: vi.fn(),
|
||||
updateCloudServer: vi.fn(),
|
||||
suspendCloudServer: vi.fn(),
|
||||
sendRenewal: vi.fn(),
|
||||
sendFailed: vi.fn(),
|
||||
retrieve: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server", () => ({}));
|
||||
vi.mock("@dokploy/server/services/cloud-server", () => ({
|
||||
findReadyCloudServers: async () => mocks.ready,
|
||||
findCloudServerBySubscriptionId: async () => mocks.found,
|
||||
claimCloudServerPaymentReminder: mocks.claim,
|
||||
updateCloudServer: mocks.updateCloudServer,
|
||||
suspendCloudServer: mocks.suspendCloudServer,
|
||||
}));
|
||||
vi.mock("@/server/utils/cloud-server-notifications", () => ({
|
||||
sendCloudServerRenewalEmail: mocks.sendRenewal,
|
||||
sendCloudServerPaymentFailedEmail: mocks.sendFailed,
|
||||
}));
|
||||
vi.mock("@/server/utils/billing", () => ({
|
||||
getStripeClient: () => stripe,
|
||||
CLOUD_SERVER_METADATA_TYPE: "cloud_server",
|
||||
isCloudServerSubscription: () => true,
|
||||
}));
|
||||
vi.mock("@/server/utils/stripe", () => ({}));
|
||||
|
||||
const { handleCloudServerEvent, sendCloudServerPaymentReminders } =
|
||||
await import("@/server/utils/cloud-server-billing");
|
||||
|
||||
const NOW = "2026-11-24T10:00:00.000Z";
|
||||
const stripe = {
|
||||
subscriptions: { retrieve: mocks.retrieve },
|
||||
} as unknown as Stripe;
|
||||
|
||||
const server = (overrides: Record<string, unknown> = {}) => ({
|
||||
cloudServerId: "cs-1",
|
||||
status: "ready",
|
||||
stripeSubscriptionId: "sub_1",
|
||||
suspendedAt: null,
|
||||
paymentReminderAt: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const subscription = (
|
||||
renewsAt: string,
|
||||
card: { exp_month: number; exp_year: number } | null,
|
||||
) => ({
|
||||
status: "active",
|
||||
cancel_at_period_end: false,
|
||||
current_period_end: Date.parse(renewsAt) / 1000,
|
||||
default_payment_method: card && { card },
|
||||
customer: { invoice_settings: { default_payment_method: null } },
|
||||
});
|
||||
|
||||
describe("cloud server payment reminders", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(NOW));
|
||||
for (const mock of Object.values(mocks)) {
|
||||
if (typeof mock === "function") mock.mockReset();
|
||||
}
|
||||
mocks.ready = [server()];
|
||||
mocks.found = null;
|
||||
mocks.claim.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("warns 7 days before the renewal when the card expires first", async () => {
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-12-01T09:00:00.000Z", {
|
||||
exp_month: 11,
|
||||
exp_year: 2026,
|
||||
}),
|
||||
);
|
||||
|
||||
await sendCloudServerPaymentReminders();
|
||||
|
||||
expect(mocks.claim).toHaveBeenCalledWith(
|
||||
"cs-1",
|
||||
new Date("2026-11-24T09:00:00.000Z"),
|
||||
);
|
||||
expect(mocks.sendRenewal).toHaveBeenCalledWith(
|
||||
mocks.ready[0],
|
||||
new Date("2026-12-01T09:00:00.000Z"),
|
||||
);
|
||||
});
|
||||
|
||||
it("moves to the 3 and 1 day steps as the renewal gets closer", async () => {
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-11-26T12:00:00.000Z", null),
|
||||
);
|
||||
await sendCloudServerPaymentReminders();
|
||||
expect(mocks.claim).toHaveBeenLastCalledWith(
|
||||
"cs-1",
|
||||
new Date("2026-11-23T12:00:00.000Z"),
|
||||
);
|
||||
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-11-25T08:00:00.000Z", null),
|
||||
);
|
||||
await sendCloudServerPaymentReminders();
|
||||
expect(mocks.claim).toHaveBeenLastCalledWith(
|
||||
"cs-1",
|
||||
new Date("2026-11-24T08:00:00.000Z"),
|
||||
);
|
||||
});
|
||||
|
||||
it("stays quiet when the card is still valid on the renewal date", async () => {
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-11-30T23:00:00.000Z", {
|
||||
exp_month: 11,
|
||||
exp_year: 2026,
|
||||
}),
|
||||
);
|
||||
|
||||
await sendCloudServerPaymentReminders();
|
||||
|
||||
expect(mocks.claim).not.toHaveBeenCalled();
|
||||
expect(mocks.sendRenewal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays quiet more than 7 days before the renewal", async () => {
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-12-02T10:00:00.000Z", null),
|
||||
);
|
||||
|
||||
await sendCloudServerPaymentReminders();
|
||||
|
||||
expect(mocks.claim).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not send a step another instance already claimed", async () => {
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-11-27T10:00:00.000Z", null),
|
||||
);
|
||||
mocks.claim.mockResolvedValue(false);
|
||||
|
||||
await sendCloudServerPaymentReminders();
|
||||
|
||||
expect(mocks.sendRenewal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases the step when the email could not be sent", async () => {
|
||||
mocks.ready = [server({ paymentReminderAt: "2026-11-17T02:00:00.000Z" })];
|
||||
mocks.retrieve.mockResolvedValue(
|
||||
subscription("2026-11-27T10:00:00.000Z", null),
|
||||
);
|
||||
mocks.sendRenewal.mockRejectedValue(new Error("smtp down"));
|
||||
|
||||
await sendCloudServerPaymentReminders();
|
||||
|
||||
expect(mocks.updateCloudServer).toHaveBeenCalledWith("cs-1", {
|
||||
paymentReminderAt: "2026-11-17T02:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("emails the day the payment fails with the deletion date, once", async () => {
|
||||
const pastDue = {
|
||||
type: "customer.subscription.updated",
|
||||
data: { object: { id: "sub_1", status: "past_due" } },
|
||||
} as unknown as Stripe.Event;
|
||||
mocks.sendFailed.mockResolvedValue(undefined);
|
||||
|
||||
mocks.found = server();
|
||||
await handleCloudServerEvent(stripe, pastDue);
|
||||
expect(mocks.suspendCloudServer).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.sendFailed).toHaveBeenCalledWith(
|
||||
mocks.found,
|
||||
new Date("2026-11-26T10:00:00.000Z"),
|
||||
);
|
||||
|
||||
mocks.found = server({ status: "suspended" });
|
||||
await handleCloudServerEvent(stripe, pastDue);
|
||||
expect(mocks.suspendCloudServer).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.sendFailed).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -47,10 +47,10 @@ describe("droplet project", () => {
|
||||
|
||||
await createDigitalOceanDroplet(params);
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[1] ?? [];
|
||||
expect(url).toMatch(/\/projects\/project-1\/resources$/);
|
||||
expect(options.method).toBe("POST");
|
||||
expect(JSON.parse(options.body)).toEqual({
|
||||
const request: Request = fetchMock.mock.calls[1]?.[0];
|
||||
expect(request.url).toMatch(/\/projects\/project-1\/resources$/);
|
||||
expect(request.method).toBe("POST");
|
||||
expect(await request.json()).toEqual({
|
||||
resources: ["do:droplet:4242"],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
servers: [] as Record<string, unknown>[],
|
||||
updates: [] as Record<string, unknown>[],
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server/db", () => ({
|
||||
db: {
|
||||
query: { cloudServer: { findMany: async () => mocks.servers } },
|
||||
update: () => ({
|
||||
set: (values: Record<string, unknown>) => {
|
||||
mocks.updates.push(values);
|
||||
return { where: () => ({ returning: async () => [values] }) };
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@dokploy/server/services/server", () => ({}));
|
||||
vi.mock("@dokploy/server/services/ssh-key", () => ({}));
|
||||
vi.mock("@dokploy/server/services/deployment", () => ({}));
|
||||
vi.mock("@dokploy/server/setup/server-setup", () => ({}));
|
||||
vi.mock("@dokploy/server/utils/filesystem/ssh", () => ({}));
|
||||
vi.mock("@dokploy/server/utils/process/execAsync", () => ({}));
|
||||
|
||||
const { recordCloudServersBandwidth } = await import(
|
||||
"@dokploy/server/services/cloud-server"
|
||||
);
|
||||
|
||||
const NOW = "2026-11-24T10:00:00.000Z";
|
||||
const HOUR_AT_8_MBPS = 3_600_000_000;
|
||||
|
||||
const oneHourAt8Mbps = (request: Request) => {
|
||||
const start = Number(new URL(request.url).searchParams.get("start"));
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
result: [
|
||||
{
|
||||
values: [
|
||||
[start, "8"],
|
||||
[start + 3600, "8"],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const server = (overrides: Record<string, unknown> = {}) => ({
|
||||
cloudServerId: "cs-1",
|
||||
providerVmId: "123",
|
||||
createdAt: "2026-11-21T15:00:00.000Z",
|
||||
status: "ready",
|
||||
bandwidthBytes: 0,
|
||||
bandwidthMeasuredAt: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("cloud server bandwidth", () => {
|
||||
const fetchMock = vi.fn();
|
||||
|
||||
const requestedRange = (call: number) => {
|
||||
const { searchParams } = new URL(fetchMock.mock.calls[call]?.[0].url);
|
||||
return Object.fromEntries(searchParams);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(NOW));
|
||||
vi.stubEnv("DIGITALOCEAN_TOKEN", "token");
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
fetchMock.mockReset();
|
||||
fetchMock.mockImplementation(async (request: Request) =>
|
||||
oneHourAt8Mbps(request),
|
||||
);
|
||||
mocks.updates = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("measures a new server from the moment it was created", async () => {
|
||||
mocks.servers = [server()];
|
||||
|
||||
await recordCloudServersBandwidth();
|
||||
|
||||
expect(requestedRange(0)).toEqual({
|
||||
host_id: "123",
|
||||
interface: "public",
|
||||
direction: "outbound",
|
||||
start: String(Date.parse("2026-11-21T15:00:00Z") / 1000),
|
||||
end: String(Date.parse(NOW) / 1000),
|
||||
});
|
||||
expect(mocks.updates).toEqual([
|
||||
{ bandwidthBytes: HOUR_AT_8_MBPS, bandwidthMeasuredAt: NOW },
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds only the traffic since the last measurement", async () => {
|
||||
mocks.servers = [
|
||||
server({
|
||||
bandwidthBytes: 500,
|
||||
bandwidthMeasuredAt: "2026-11-23T10:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
await recordCloudServersBandwidth();
|
||||
|
||||
expect(requestedRange(0).start).toBe(
|
||||
String(Date.parse("2026-11-23T10:00:00Z") / 1000),
|
||||
);
|
||||
expect(mocks.updates).toEqual([
|
||||
{ bandwidthBytes: 500 + HOUR_AT_8_MBPS, bandwidthMeasuredAt: NOW },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps going with the other servers when DO fails for one", async () => {
|
||||
mocks.servers = [server(), server({ cloudServerId: "cs-2" })];
|
||||
fetchMock.mockRejectedValueOnce(new Error("network down"));
|
||||
|
||||
await recordCloudServersBandwidth();
|
||||
|
||||
expect(mocks.updates).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -4,15 +4,16 @@ import { AU, CA, DE, GB, IN, NL, SG, US } from "country-flag-icons/react/3x2";
|
||||
import { addDays, format, formatDistanceToNow } from "date-fns";
|
||||
import {
|
||||
AlertCircle,
|
||||
ArrowUpDown,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
CircleArrowUp,
|
||||
Clock,
|
||||
Copy,
|
||||
Cpu,
|
||||
CreditCard,
|
||||
FileText,
|
||||
HardDrive,
|
||||
Info,
|
||||
Loader2,
|
||||
Lock,
|
||||
MemoryStick,
|
||||
@@ -103,11 +104,6 @@ const STATUS_MAP: Record<
|
||||
variant: "default" | "secondary" | "destructive" | "outline";
|
||||
}
|
||||
> = {
|
||||
pending: {
|
||||
label: "Awaiting payment",
|
||||
icon: <Clock className="size-3" />,
|
||||
variant: "secondary",
|
||||
},
|
||||
provisioning: {
|
||||
label: "Provisioning",
|
||||
icon: <Loader2 className="size-3 animate-spin" />,
|
||||
@@ -178,10 +174,12 @@ function PlanSpecs({
|
||||
cpus,
|
||||
memoryGb,
|
||||
storageGb,
|
||||
transferTb,
|
||||
}: {
|
||||
cpus: number;
|
||||
memoryGb: number;
|
||||
storageGb: number;
|
||||
transferTb: number;
|
||||
}) {
|
||||
const specs = [
|
||||
{ icon: Cpu, label: `${cpus} vCPU` },
|
||||
@@ -196,10 +194,27 @@ function PlanSpecs({
|
||||
{label}
|
||||
</li>
|
||||
))}
|
||||
<li className="flex items-center gap-1.5">
|
||||
<ArrowUpDown className="size-3.5 shrink-0" />
|
||||
{transferTb} TB transfer
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Info className="size-3.5 shrink-0" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-60">
|
||||
{transferTb} TB of outbound transfer are included each month.
|
||||
Transfer above that is billed at {EXTRA_BANDWIDTH_PRICE} per GB on
|
||||
your next invoice.
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</li>
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
const SUSPENSION_GRACE_DAYS = 2;
|
||||
const EXTRA_BANDWIDTH_PRICE = "$0.03";
|
||||
|
||||
function formatPrice(priceCents: number) {
|
||||
return `$${(priceCents / 100).toFixed(2)}/mo`;
|
||||
}
|
||||
@@ -300,10 +315,14 @@ function OrderServerDialog() {
|
||||
cpus={p.cpus}
|
||||
memoryGb={p.memoryGb}
|
||||
storageGb={p.storageGb}
|
||||
transferTb={p.transferTb}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
None of these fit your workload? <ContactLink />
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Zone selector grouped by continent */}
|
||||
@@ -378,6 +397,13 @@ function OrderServerDialog() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
If a renewal payment fails, the server is powered off and
|
||||
deleted after {SUSPENSION_GRACE_DAYS} days. Deleting a server
|
||||
adds its unused time to your balance as credit instead of a
|
||||
refund, and the first hour is always charged.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
className="w-full"
|
||||
disabled={!selectedPlan || !selectedZone || purchase.isPending}
|
||||
@@ -519,10 +545,7 @@ function PowerControls({
|
||||
);
|
||||
}
|
||||
|
||||
const SUSPENSION_GRACE_DAYS = 7;
|
||||
|
||||
const IN_PROGRESS_STATUSES = [
|
||||
"pending",
|
||||
"provisioning",
|
||||
"configuring",
|
||||
"upgrading",
|
||||
@@ -532,6 +555,19 @@ const IN_PROGRESS_STATUSES = [
|
||||
type CloudServerItem = RouterOutputs["cloudServer"]["list"][number];
|
||||
type Plan = RouterOutputs["cloudServer"]["getPlans"][number];
|
||||
|
||||
function ContactLink() {
|
||||
return (
|
||||
<a
|
||||
href="https://dokploy.com/contact"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="underline underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
Contact us
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailItem({
|
||||
label,
|
||||
value,
|
||||
@@ -924,7 +960,7 @@ function UpgradeServerDialog({ cloudServerId }: { cloudServerId: string }) {
|
||||
) : !options?.length ? (
|
||||
<p className="text-sm text-muted-foreground py-4">
|
||||
This server is already on the largest plan available in its
|
||||
location.
|
||||
location. Need something bigger? <ContactLink />
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
@@ -951,10 +987,14 @@ function UpgradeServerDialog({ cloudServerId }: { cloudServerId: string }) {
|
||||
cpus={p.cpus}
|
||||
memoryGb={p.memoryGb}
|
||||
storageGb={p.storageGb}
|
||||
transferTb={p.transferTb}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
None of these fit your workload? <ContactLink />
|
||||
</p>
|
||||
|
||||
{selectedPlan && (
|
||||
<div className="rounded-lg bg-muted p-3 text-sm space-y-1">
|
||||
@@ -1070,7 +1110,9 @@ function TerminateServerDialog({
|
||||
<DialogTitle>Terminate Server</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will permanently destroy the server and all data on it. This
|
||||
action cannot be undone.
|
||||
action cannot be undone. The unused time of the period you already
|
||||
paid is added to your balance as credit and discounted from your
|
||||
next invoice.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{isLoading ? (
|
||||
@@ -1282,27 +1324,11 @@ function CloudServerRow({
|
||||
<TooltipContent>Open the server terminal</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{s.status === "pending" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Cancel order</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<TerminateServerDialog
|
||||
serverId={s.serverId}
|
||||
serverName={s.hostname ?? s.cloudServerId}
|
||||
onConfirm={onDelete}
|
||||
/>
|
||||
)}
|
||||
<TerminateServerDialog
|
||||
serverId={s.serverId}
|
||||
serverName={s.hostname ?? s.cloudServerId}
|
||||
onConfirm={onDelete}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1316,6 +1342,16 @@ function CloudServerRow({
|
||||
<DetailItem label="Price" value={formatPrice(plan.priceCents)} />
|
||||
</>
|
||||
)}
|
||||
{plan && (
|
||||
<DetailItem
|
||||
label="Transfer included"
|
||||
value={`${plan.transferTb} TB / month`}
|
||||
/>
|
||||
)}
|
||||
<DetailItem
|
||||
label="Bandwidth used"
|
||||
value={`${(s.bandwidthBytes / 1024 ** 3).toFixed(2)} GB`}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Location"
|
||||
value={
|
||||
@@ -1373,10 +1409,14 @@ export const ShowCloudServers = () => {
|
||||
const router = useRouter();
|
||||
const utils = api.useUtils();
|
||||
|
||||
// The server only shows up once Stripe's webhook lands, which can be after the redirect back from checkout.
|
||||
const [justPaid, setJustPaid] = useState(false);
|
||||
|
||||
const { data: servers, isLoading } = api.cloudServer.list.useQuery(
|
||||
undefined,
|
||||
{
|
||||
refetchInterval: (query) =>
|
||||
justPaid ||
|
||||
query.state.data?.some((s) => IN_PROGRESS_STATUSES.includes(s.status))
|
||||
? 5000
|
||||
: false,
|
||||
@@ -1386,11 +1426,13 @@ export const ShowCloudServers = () => {
|
||||
const { data: plans } = api.cloudServer.getPlans.useQuery(undefined, {
|
||||
enabled: !!servers?.length,
|
||||
});
|
||||
const { data: creditCents } = api.cloudServer.creditBalance.useQuery();
|
||||
|
||||
useEffect(() => {
|
||||
const { checkout, ...query } = router.query;
|
||||
if (!checkout) return;
|
||||
if (checkout === "success") {
|
||||
setJustPaid(true);
|
||||
toast.success(
|
||||
"Payment received! Your server is being provisioned, this takes ~5 minutes.",
|
||||
);
|
||||
@@ -1418,11 +1460,10 @@ export const ShowCloudServers = () => {
|
||||
});
|
||||
|
||||
const deleteServer = api.cloudServer.delete.useMutation({
|
||||
onSuccess: ({ cancelledOrder }) => {
|
||||
toast.success(
|
||||
cancelledOrder ? "Order cancelled." : "Server is being terminated.",
|
||||
);
|
||||
onSuccess: () => {
|
||||
toast.success("Server is being terminated.");
|
||||
utils.cloudServer.list.invalidate();
|
||||
utils.cloudServer.creditBalance.invalidate();
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
@@ -1471,6 +1512,12 @@ export const ShowCloudServers = () => {
|
||||
Servers provided by Dokploy Cloud, billed separately from
|
||||
your plan
|
||||
</p>
|
||||
{!!creditCents && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Credit balance: ${(creditCents / 100).toFixed(2)}, applied
|
||||
to your next invoice
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<OrderServerDialog />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "cloud_server" RENAME COLUMN "providerNetworkId" TO "providerVpcId";
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "cloud_server" ADD COLUMN "bandwidthBytes" bigint DEFAULT 0 NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "cloud_server" ADD COLUMN "bandwidthMeasuredAt" text;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "cloud_server" ADD COLUMN "paymentReminderAt" text;
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE "cloud_server" ALTER COLUMN "status" DROP DEFAULT;--> statement-breakpoint
|
||||
ALTER TABLE "cloud_server" ALTER COLUMN "status" SET DATA TYPE text;--> statement-breakpoint
|
||||
DROP TYPE "public"."cloudServerStatus";--> statement-breakpoint
|
||||
CREATE TYPE "public"."cloudServerStatus" AS ENUM('provisioning', 'configuring', 'ready', 'upgrading', 'error', 'suspended', 'terminating');--> statement-breakpoint
|
||||
ALTER TABLE "cloud_server" ALTER COLUMN "status" SET DATA TYPE "public"."cloudServerStatus" USING "status"::"public"."cloudServerStatus";
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1457,6 +1457,34 @@
|
||||
"when": 1795501000373,
|
||||
"tag": "0207_bored_quicksilver",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 208,
|
||||
"version": "7",
|
||||
"when": 1795557315497,
|
||||
"tag": "0208_cloud_server_vpc_id",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 209,
|
||||
"version": "7",
|
||||
"when": 1795561625607,
|
||||
"tag": "0209_cloud_server_bandwidth",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 210,
|
||||
"version": "7",
|
||||
"when": 1795686980773,
|
||||
"tag": "0210_cloud_server_payment_reminder",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 211,
|
||||
"version": "7",
|
||||
"when": 1795732334725,
|
||||
"tag": "0211_cloud_server_drop_pending",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -75,11 +75,11 @@ export default async function handler(
|
||||
"customer.subscription.created",
|
||||
"customer.subscription.deleted",
|
||||
"customer.subscription.updated",
|
||||
"invoice.created",
|
||||
"invoice.payment_succeeded",
|
||||
"invoice.payment_failed",
|
||||
"customer.deleted",
|
||||
"checkout.session.completed",
|
||||
"checkout.session.expired",
|
||||
"customer.subscription.trial_will_end",
|
||||
];
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
} from "@dokploy/server/db/schema/cloud-server";
|
||||
import {
|
||||
assertCloudServerCapacity,
|
||||
createCloudServer,
|
||||
deletePendingCloudServer,
|
||||
disableCloudServerFirewall,
|
||||
findCloudServerById,
|
||||
findCloudServersByOrg,
|
||||
@@ -29,12 +27,11 @@ import {
|
||||
getRegionInfo,
|
||||
} from "@dokploy/server/utils/digitalocean";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
cancelCloudServerSubscription,
|
||||
createCloudServerCheckout,
|
||||
expireCloudServerCheckout,
|
||||
getCloudServerCreditCents,
|
||||
getUpgradeOptions,
|
||||
previewCloudServerUpgrade,
|
||||
upgradeCloudServer,
|
||||
@@ -77,6 +74,11 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
});
|
||||
}),
|
||||
|
||||
creditBalance: adminProcedure.query(async ({ ctx }) => {
|
||||
if (!IS_CLOUD) return 0;
|
||||
return getCloudServerCreditCents(ctx.user.ownerId);
|
||||
}),
|
||||
|
||||
one: adminProcedure
|
||||
.input(apiFindOneCloudServer)
|
||||
.query(async ({ input, ctx }) => {
|
||||
@@ -116,35 +118,15 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
|
||||
await assertCloudServerCapacity();
|
||||
|
||||
const hostname =
|
||||
`dokploy-${ctx.session.activeOrganizationId.slice(0, 8)}-${nanoid(6)}`
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]/g, "x");
|
||||
|
||||
const managedRecord = await createCloudServer({
|
||||
const session = await createCloudServerCheckout({
|
||||
ownerId: ctx.user.ownerId,
|
||||
organizationId: ctx.session.activeOrganizationId,
|
||||
plan: input.plan,
|
||||
plan,
|
||||
zone: input.zone,
|
||||
hostname,
|
||||
status: "pending",
|
||||
regionName: region.description,
|
||||
});
|
||||
|
||||
try {
|
||||
const session = await createCloudServerCheckout({
|
||||
ownerId: ctx.user.ownerId,
|
||||
cloudServerId: managedRecord.cloudServerId,
|
||||
plan,
|
||||
regionName: region.description,
|
||||
});
|
||||
await updateCloudServer(managedRecord.cloudServerId, {
|
||||
stripeCheckoutSessionId: session.id,
|
||||
});
|
||||
if (!session.url) throw new Error("Stripe did not return a URL");
|
||||
return { url: session.url };
|
||||
} catch (err) {
|
||||
await deletePendingCloudServer(managedRecord.cloudServerId);
|
||||
throw err;
|
||||
}
|
||||
if (!session.url) throw new Error("Stripe did not return a URL");
|
||||
return { url: session.url };
|
||||
}),
|
||||
|
||||
delete: adminProcedure
|
||||
@@ -158,14 +140,6 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
if (record.status === "pending") {
|
||||
if (record.stripeCheckoutSessionId) {
|
||||
await expireCloudServerCheckout(record.stripeCheckoutSessionId);
|
||||
}
|
||||
await deletePendingCloudServer(input.cloudServerId);
|
||||
return { cancelledOrder: true };
|
||||
}
|
||||
|
||||
if (record.serverId && (await haveActiveServices(record.serverId))) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
@@ -180,7 +154,9 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
|
||||
if (record.stripeSubscriptionId) {
|
||||
try {
|
||||
await cancelCloudServerSubscription(record.stripeSubscriptionId);
|
||||
await cancelCloudServerSubscription(record.stripeSubscriptionId, {
|
||||
creditUnusedTime: true,
|
||||
});
|
||||
} catch (err) {
|
||||
await updateCloudServer(input.cloudServerId, {
|
||||
status: record.status,
|
||||
@@ -198,8 +174,6 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
errorMessage: `Termination failed: ${err?.message ?? "Unknown error"}`,
|
||||
});
|
||||
});
|
||||
|
||||
return { cancelledOrder: false };
|
||||
}),
|
||||
|
||||
reconnect: adminProcedure
|
||||
@@ -218,6 +192,13 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
message: "Server is already linked",
|
||||
});
|
||||
}
|
||||
// A suspended server must stay disconnected until it is paid.
|
||||
if (record.status !== "ready") {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Server is not ready",
|
||||
});
|
||||
}
|
||||
if (!record.ipAddress) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
@@ -250,7 +231,6 @@ export const cloudServerRouter = createTRPCRouter({
|
||||
|
||||
await updateCloudServer(input.cloudServerId, {
|
||||
serverId: serverRecord.serverId,
|
||||
status: "ready",
|
||||
});
|
||||
|
||||
return findCloudServerById(input.cloudServerId);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
deleteServer,
|
||||
findCloudServerByServerId,
|
||||
findCloudServerIds,
|
||||
findPlanServersByUserId,
|
||||
findServerById,
|
||||
findUserById,
|
||||
generateSSHKey,
|
||||
@@ -58,7 +59,6 @@ import {
|
||||
mariadb,
|
||||
mongo,
|
||||
mysql,
|
||||
organization,
|
||||
postgres,
|
||||
redis,
|
||||
server,
|
||||
@@ -338,16 +338,8 @@ export const serverRouter = createTRPCRouter({
|
||||
});
|
||||
}),
|
||||
count: protectedProcedure.query(async ({ ctx }) => {
|
||||
const organizations = await db.query.organization.findMany({
|
||||
where: eq(organization.ownerId, ctx.user.id),
|
||||
with: {
|
||||
servers: true,
|
||||
},
|
||||
});
|
||||
|
||||
const servers = organizations.flatMap((org) => org.servers);
|
||||
|
||||
return servers.length ?? 0;
|
||||
const servers = await findPlanServersByUserId(ctx.user.id);
|
||||
return servers.length;
|
||||
}),
|
||||
withSSHKey: protectedProcedure.query(async ({ ctx }) => {
|
||||
const accessibleIds = await getAccessibleServerIds(ctx.session);
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { findUserById, updateUser } from "@dokploy/server";
|
||||
import {
|
||||
findOrganizationById,
|
||||
findUserById,
|
||||
updateUser,
|
||||
} from "@dokploy/server";
|
||||
import {
|
||||
buildCloudServerHostname,
|
||||
type CloudServer,
|
||||
claimCloudServerForProvisioning,
|
||||
claimCloudServerForUpgrade,
|
||||
deletePendingCloudServer,
|
||||
claimCloudServerPaymentReminder,
|
||||
createCloudServer,
|
||||
findCloudServerById,
|
||||
findCloudServerBySubscriptionId,
|
||||
findReadyCloudServers,
|
||||
findSuspendedCloudServersBefore,
|
||||
powerOnCloudServerVm,
|
||||
provisionCloudServer,
|
||||
recordCloudServersBandwidth,
|
||||
releaseProviderResources,
|
||||
resizeCloudServerVm,
|
||||
resumeCloudServer,
|
||||
@@ -20,10 +27,12 @@ import {
|
||||
DOKPLOY_PLANS,
|
||||
type DokployPlan,
|
||||
deleteDigitalOceanDropletsByTag,
|
||||
EXTRA_BANDWIDTH_CENTS_PER_GB,
|
||||
getCloudServerTag,
|
||||
getDigitalOceanRegions,
|
||||
} from "@dokploy/server/utils/digitalocean";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { nanoid } from "nanoid";
|
||||
import { scheduleJob } from "node-schedule";
|
||||
import Stripe from "stripe";
|
||||
import {
|
||||
@@ -31,10 +40,21 @@ import {
|
||||
getStripeClient,
|
||||
isCloudServerSubscription,
|
||||
} from "@/server/utils/billing";
|
||||
import {
|
||||
sendCloudServerBandwidthEmail,
|
||||
sendCloudServerDeletedEmail,
|
||||
sendCloudServerPaymentFailedEmail,
|
||||
sendCloudServerReactivatedEmail,
|
||||
sendCloudServerRenewalEmail,
|
||||
} from "@/server/utils/cloud-server-notifications";
|
||||
import { WEBSITE_URL } from "@/server/utils/stripe";
|
||||
|
||||
const SUSPENSION_GRACE_DAYS = 7;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const SUSPENSION_GRACE_DAYS = 2;
|
||||
const RENEWAL_REMINDER_DAYS = [1, 3, 7];
|
||||
const BANDWIDTH_WARNING_PERCENTS = [100, 80];
|
||||
const CHECKOUT_EXPIRATION_MINUTES = 30;
|
||||
const MINIMUM_BILLED_SECONDS = 60 * 60;
|
||||
|
||||
const getCloudServerId = (metadata?: Stripe.Metadata | null) =>
|
||||
metadata?.type === CLOUD_SERVER_METADATA_TYPE
|
||||
@@ -73,16 +93,21 @@ const getPlanProductId = (plan: DokployPlan) => {
|
||||
|
||||
export const createCloudServerCheckout = async (params: {
|
||||
ownerId: string;
|
||||
cloudServerId: string;
|
||||
organizationId: string;
|
||||
plan: DokployPlan;
|
||||
zone: string;
|
||||
regionName: string;
|
||||
}) => {
|
||||
const stripe = getStripeClient();
|
||||
const customer = await getOrCreateStripeCustomer(params.ownerId, stripe);
|
||||
const { plan } = params;
|
||||
// The order only lives here until it is paid, the server record is created from it afterwards.
|
||||
const metadata = {
|
||||
type: CLOUD_SERVER_METADATA_TYPE,
|
||||
cloudServerId: params.cloudServerId,
|
||||
cloudServerId: nanoid(),
|
||||
organizationId: params.organizationId,
|
||||
plan: plan.id,
|
||||
zone: params.zone,
|
||||
};
|
||||
|
||||
return stripe.checkout.sessions.create({
|
||||
@@ -111,20 +136,13 @@ export const createCloudServerCheckout = async (params: {
|
||||
});
|
||||
};
|
||||
|
||||
export const expireCloudServerCheckout = async (sessionId: string) => {
|
||||
await getStripeClient()
|
||||
.checkout.sessions.expire(sessionId)
|
||||
.catch((err) =>
|
||||
console.error("[cloud-server] failed to expire checkout:", err),
|
||||
);
|
||||
};
|
||||
|
||||
export const cancelCloudServerSubscription = async (
|
||||
subscriptionId: string,
|
||||
stripe: Stripe = getStripeClient(),
|
||||
options: { creditUnusedTime?: boolean } = {},
|
||||
) => {
|
||||
const stripe = getStripeClient();
|
||||
const subscription = await stripe.subscriptions
|
||||
.retrieve(subscriptionId)
|
||||
.retrieve(subscriptionId, { expand: ["latest_invoice"] })
|
||||
.catch((err: unknown) => {
|
||||
if (
|
||||
err instanceof Stripe.errors.StripeError &&
|
||||
@@ -141,10 +159,41 @@ export const cancelCloudServerSubscription = async (
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await stripe.subscriptions.cancel(subscriptionId, {
|
||||
invoice_now: false,
|
||||
prorate: false,
|
||||
// A period that was never paid must not turn into credit.
|
||||
const credit =
|
||||
!!options.creditUnusedTime &&
|
||||
(subscription.latest_invoice as Stripe.Invoice | null)?.status === "paid";
|
||||
const cancelled = await stripe.subscriptions.cancel(subscriptionId, {
|
||||
invoice_now: credit,
|
||||
prorate: credit,
|
||||
expand: ["latest_invoice"],
|
||||
});
|
||||
if (!credit) return;
|
||||
|
||||
const invoice = cancelled.latest_invoice as Stripe.Invoice;
|
||||
const priceCents = subscription.items.data[0]?.price.unit_amount;
|
||||
const missingSeconds =
|
||||
MINIMUM_BILLED_SECONDS - (Date.now() / 1000 - subscription.start_date);
|
||||
// A server deleted after a few minutes rounds to $0.00, while DigitalOcean still bills us for it.
|
||||
if (priceCents && missingSeconds > 0) {
|
||||
await stripe.invoiceItems.create(
|
||||
{
|
||||
customer: invoice.customer as string,
|
||||
invoice: invoice.id,
|
||||
amount: Math.ceil(
|
||||
(priceCents * missingSeconds) /
|
||||
(subscription.current_period_end -
|
||||
subscription.current_period_start),
|
||||
),
|
||||
currency: invoice.currency,
|
||||
description: "Minimum charge: first hour",
|
||||
},
|
||||
{ idempotencyKey: `cloud-server-minimum-${invoice.id}` },
|
||||
);
|
||||
}
|
||||
await chargeExtraBandwidth(stripe, invoice);
|
||||
// Stripe keeps this invoice in draft for an hour, and the credit only reaches the balance once it is finalized.
|
||||
await stripe.invoices.finalizeInvoice(invoice.id);
|
||||
};
|
||||
|
||||
const refundInvoice = async (
|
||||
@@ -170,7 +219,7 @@ const refundAndCancelSubscription = async (
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
|
||||
expand: ["latest_invoice"],
|
||||
});
|
||||
await cancelCloudServerSubscription(subscriptionId, stripe);
|
||||
await cancelCloudServerSubscription(subscriptionId);
|
||||
await refundInvoice(stripe, subscription.latest_invoice);
|
||||
};
|
||||
|
||||
@@ -206,31 +255,35 @@ const handleProvisioningFailure = async (
|
||||
|
||||
const handleCheckoutCompleted = async (
|
||||
stripe: Stripe,
|
||||
cloudServerId: string,
|
||||
subscriptionId: string,
|
||||
session: Stripe.Checkout.Session,
|
||||
) => {
|
||||
const record = await claimCloudServerForProvisioning(
|
||||
cloudServerId,
|
||||
subscriptionId,
|
||||
);
|
||||
const subscriptionId = session.subscription as string;
|
||||
const { cloudServerId, organizationId, zone } = session.metadata ?? {};
|
||||
const plan = DOKPLOY_PLANS.find((p) => p.id === session.metadata?.plan);
|
||||
|
||||
if (!record) {
|
||||
const existing = await findCloudServerById(cloudServerId).catch(() => null);
|
||||
if (existing?.stripeSubscriptionId === subscriptionId) return;
|
||||
// Paid after the order was removed, there is nothing to provision.
|
||||
if (
|
||||
!cloudServerId ||
|
||||
!organizationId ||
|
||||
!zone ||
|
||||
!plan ||
|
||||
!(await findOrganizationById(organizationId))
|
||||
) {
|
||||
// Paid for an order that can no longer be fulfilled, there is nothing to provision.
|
||||
await refundAndCancelSubscription(stripe, subscriptionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const plan = DOKPLOY_PLANS.find((p) => p.id === record.plan);
|
||||
if (!plan || !record.hostname) {
|
||||
await handleProvisioningFailure(
|
||||
stripe,
|
||||
record,
|
||||
new Error(`Invalid order for plan "${record.plan}"`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const record = await createCloudServer({
|
||||
cloudServerId,
|
||||
organizationId,
|
||||
plan: plan.id,
|
||||
zone,
|
||||
hostname: buildCloudServerHostname(organizationId),
|
||||
status: "provisioning",
|
||||
stripeSubscriptionId: subscriptionId,
|
||||
stripeCheckoutSessionId: session.id,
|
||||
});
|
||||
if (!record) return;
|
||||
|
||||
// Provisioning takes minutes, far longer than Stripe waits for a webhook response.
|
||||
void provisionCloudServer({
|
||||
@@ -239,18 +292,35 @@ const handleCheckoutCompleted = async (
|
||||
doSize: plan.doSize,
|
||||
swapGb: Math.min(plan.memoryGb, 4),
|
||||
zone: record.zone,
|
||||
hostname: record.hostname,
|
||||
hostname: record.hostname!,
|
||||
}).catch((err) => handleProvisioningFailure(stripe, record, err));
|
||||
};
|
||||
|
||||
const logEmailError = (record: CloudServer) => (err: unknown) =>
|
||||
console.error(
|
||||
`[cloud-server] failed to send an email about ${record.cloudServerId}:`,
|
||||
err,
|
||||
);
|
||||
|
||||
const reactivateCloudServer = async (record: CloudServer) => {
|
||||
if (record.status !== "suspended") return;
|
||||
await resumeCloudServer(record);
|
||||
await sendCloudServerReactivatedEmail(record).catch(logEmailError(record));
|
||||
};
|
||||
|
||||
const handleSubscriptionUpdated = async (subscription: Stripe.Subscription) => {
|
||||
const record = await findCloudServerBySubscriptionId(subscription.id);
|
||||
if (!record) return;
|
||||
|
||||
if (subscription.status === "past_due" || subscription.status === "unpaid") {
|
||||
if (record.status !== "ready") return;
|
||||
await suspendCloudServer(record);
|
||||
await sendCloudServerPaymentFailedEmail(
|
||||
record,
|
||||
new Date(Date.now() + SUSPENSION_GRACE_DAYS * DAY_MS),
|
||||
).catch(logEmailError(record));
|
||||
} else if (subscription.status === "active") {
|
||||
await resumeCloudServer(record);
|
||||
await reactivateCloudServer(record);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -270,6 +340,7 @@ const handleSubscriptionDeleted = async (subscription: Stripe.Subscription) => {
|
||||
|
||||
await updateCloudServer(record.cloudServerId, { status: "terminating" });
|
||||
await terminateCloudServer(record.cloudServerId);
|
||||
await sendCloudServerDeletedEmail(record).catch(logEmailError(record));
|
||||
};
|
||||
|
||||
const PRORATION_DATE_MAX_AGE_SECONDS = 15 * 60;
|
||||
@@ -495,6 +566,34 @@ export const upgradeCloudServer = async (
|
||||
});
|
||||
};
|
||||
|
||||
// Stripe keeps a renewal invoice in draft for about an hour, the only moment a line can still be added to it.
|
||||
const chargeExtraBandwidth = async (
|
||||
stripe: Stripe,
|
||||
invoice: Stripe.Invoice,
|
||||
) => {
|
||||
const record = await findCloudServerBySubscriptionId(
|
||||
invoice.subscription as string,
|
||||
);
|
||||
const plan = DOKPLOY_PLANS.find((p) => p.id === record?.plan);
|
||||
if (!record || !plan) return;
|
||||
|
||||
const extraGb =
|
||||
Math.floor(record.bandwidthBytes / 1024 ** 3) - plan.transferTb * 1000;
|
||||
if (extraGb > 0) {
|
||||
await stripe.invoiceItems.create(
|
||||
{
|
||||
customer: invoice.customer as string,
|
||||
invoice: invoice.id,
|
||||
amount: extraGb * EXTRA_BANDWIDTH_CENTS_PER_GB,
|
||||
currency: invoice.currency,
|
||||
description: `Extra bandwidth: ${extraGb} GB`,
|
||||
},
|
||||
{ idempotencyKey: `cloud-server-bandwidth-${invoice.id}` },
|
||||
);
|
||||
}
|
||||
await updateCloudServer(record.cloudServerId, { bandwidthBytes: 0 });
|
||||
};
|
||||
|
||||
/** Returns true when the event belongs to a cloud server and was handled here. */
|
||||
export const handleCloudServerEvent = async (
|
||||
stripe: Stripe,
|
||||
@@ -503,19 +602,8 @@ export const handleCloudServerEvent = async (
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed": {
|
||||
const session = event.data.object;
|
||||
const cloudServerId = getCloudServerId(session.metadata);
|
||||
if (!cloudServerId) return false;
|
||||
await handleCheckoutCompleted(
|
||||
stripe,
|
||||
cloudServerId,
|
||||
session.subscription as string,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
case "checkout.session.expired": {
|
||||
const cloudServerId = getCloudServerId(event.data.object.metadata);
|
||||
if (!cloudServerId) return false;
|
||||
await deletePendingCloudServer(cloudServerId);
|
||||
if (!getCloudServerId(session.metadata)) return false;
|
||||
await handleCheckoutCompleted(stripe, session);
|
||||
return true;
|
||||
}
|
||||
case "customer.subscription.created":
|
||||
@@ -531,6 +619,16 @@ export const handleCloudServerEvent = async (
|
||||
await handleSubscriptionDeleted(event.data.object);
|
||||
return true;
|
||||
}
|
||||
case "invoice.created": {
|
||||
const invoice = event.data.object;
|
||||
if (!getCloudServerId(invoice.subscription_details?.metadata)) {
|
||||
return false;
|
||||
}
|
||||
if (invoice.billing_reason === "subscription_cycle") {
|
||||
await chargeExtraBandwidth(stripe, invoice);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "invoice.payment_succeeded":
|
||||
case "invoice.payment_failed":
|
||||
// Suspension and resume follow the subscription status, invoices only need to stay away from the plan logic.
|
||||
@@ -542,28 +640,182 @@ export const handleCloudServerEvent = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const initCloudServerCrons = () => {
|
||||
scheduleJob("cloud-server-suspension-cleanup", "0 * * * *", async () => {
|
||||
const cutoff = new Date(
|
||||
Date.now() - SUSPENSION_GRACE_DAYS * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
const expired = await findSuspendedCloudServersBefore(cutoff);
|
||||
|
||||
for (const record of expired) {
|
||||
try {
|
||||
await updateCloudServer(record.cloudServerId, {
|
||||
status: "terminating",
|
||||
});
|
||||
if (record.stripeSubscriptionId) {
|
||||
await cancelCloudServerSubscription(record.stripeSubscriptionId);
|
||||
}
|
||||
await terminateCloudServer(record.cloudServerId);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[cloud-server] failed to remove suspended server ${record.cloudServerId}:`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
const hasValidPaymentMethod = (subscription: Stripe.Subscription) => {
|
||||
const customer = subscription.customer as Stripe.Customer;
|
||||
const method = (subscription.default_payment_method ??
|
||||
customer.invoice_settings
|
||||
?.default_payment_method) as Stripe.PaymentMethod | null;
|
||||
if (!method) return false;
|
||||
if (!method.card) return true;
|
||||
// A card works until the end of its expiry month, which Date.UTC reaches because its months start at 0.
|
||||
return (
|
||||
Date.UTC(method.card.exp_year, method.card.exp_month) >
|
||||
subscription.current_period_end * 1000
|
||||
);
|
||||
};
|
||||
|
||||
const sendRenewalReminder = async (stripe: Stripe, record: CloudServer) => {
|
||||
const subscription = await stripe.subscriptions.retrieve(
|
||||
record.stripeSubscriptionId!,
|
||||
{
|
||||
expand: [
|
||||
"default_payment_method",
|
||||
"customer.invoice_settings.default_payment_method",
|
||||
],
|
||||
},
|
||||
);
|
||||
if (subscription.status !== "active" || subscription.cancel_at_period_end) {
|
||||
return;
|
||||
}
|
||||
|
||||
const renewsAt = subscription.current_period_end * 1000;
|
||||
const days = RENEWAL_REMINDER_DAYS.find(
|
||||
(d) => Date.now() >= renewsAt - d * DAY_MS,
|
||||
);
|
||||
if (!days || hasValidPaymentMethod(subscription)) return;
|
||||
|
||||
const claimed = await claimCloudServerPaymentReminder(
|
||||
record.cloudServerId,
|
||||
new Date(renewsAt - days * DAY_MS),
|
||||
);
|
||||
if (!claimed) return;
|
||||
|
||||
try {
|
||||
await sendCloudServerRenewalEmail(record, new Date(renewsAt));
|
||||
} catch (err) {
|
||||
await updateCloudServer(record.cloudServerId, {
|
||||
paymentReminderAt: record.paymentReminderAt,
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const sendCloudServerPaymentReminders = async () => {
|
||||
const stripe = getStripeClient();
|
||||
for (const record of await findReadyCloudServers()) {
|
||||
try {
|
||||
await sendRenewalReminder(stripe, record);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[cloud-server] failed to send the payment reminder of ${record.cloudServerId}:`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const recordBandwidthAndWarn = async () => {
|
||||
for (const { previous, current } of await recordCloudServersBandwidth()) {
|
||||
const plan = DOKPLOY_PLANS.find((p) => p.id === current.plan);
|
||||
if (!plan) continue;
|
||||
|
||||
const allowance = plan.transferTb * 1000 * 1024 ** 3;
|
||||
const percent = BANDWIDTH_WARNING_PERCENTS.find(
|
||||
(p) =>
|
||||
previous.bandwidthBytes < (allowance * p) / 100 &&
|
||||
current.bandwidthBytes >= (allowance * p) / 100,
|
||||
);
|
||||
if (percent) {
|
||||
await sendCloudServerBandwidthEmail(
|
||||
current,
|
||||
percent,
|
||||
plan.transferTb,
|
||||
).catch(logEmailError(current));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Returns true when the server must be kept: it is already paid, or one last charge went through.
|
||||
const collectUnpaidInvoice = async (stripe: Stripe, record: CloudServer) => {
|
||||
const subscription = await stripe.subscriptions.retrieve(
|
||||
record.stripeSubscriptionId!,
|
||||
{ expand: ["latest_invoice", "customer"] },
|
||||
);
|
||||
if (subscription.status === "active") {
|
||||
// The webhook that resumes the server never arrived.
|
||||
await reactivateCloudServer(record);
|
||||
return true;
|
||||
}
|
||||
|
||||
const invoice = subscription.latest_invoice as Stripe.Invoice | null;
|
||||
if (subscription.status === "canceled" || invoice?.status !== "open") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Checkout keeps the card on the subscription, so one the customer added later is only their account default.
|
||||
const card = (subscription.customer as Stripe.Customer).invoice_settings
|
||||
?.default_payment_method;
|
||||
if (card) {
|
||||
await stripe.subscriptions.update(subscription.id, {
|
||||
default_payment_method: card as string,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Paying moves the subscription back to active, and that webhook resumes the server.
|
||||
return (await stripe.invoices.pay(invoice.id)).status === "paid";
|
||||
} catch (err) {
|
||||
if (err instanceof Stripe.errors.StripeCardError) return false;
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const removeUnpaidCloudServers = async () => {
|
||||
const stripe = getStripeClient();
|
||||
const cutoff = new Date(Date.now() - SUSPENSION_GRACE_DAYS * DAY_MS);
|
||||
|
||||
for (const record of await findSuspendedCloudServersBefore(cutoff)) {
|
||||
try {
|
||||
if (
|
||||
record.stripeSubscriptionId &&
|
||||
(await collectUnpaidInvoice(stripe, record))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
await updateCloudServer(record.cloudServerId, {
|
||||
status: "terminating",
|
||||
});
|
||||
if (record.stripeSubscriptionId) {
|
||||
await cancelCloudServerSubscription(record.stripeSubscriptionId);
|
||||
}
|
||||
await terminateCloudServer(record.cloudServerId);
|
||||
await sendCloudServerDeletedEmail(record).catch(logEmailError(record));
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[cloud-server] failed to remove suspended server ${record.cloudServerId}:`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const getCloudServerCreditCents = async (ownerId: string) => {
|
||||
const owner = await findUserById(ownerId);
|
||||
if (!owner.stripeCustomerId) return 0;
|
||||
|
||||
const customer = await getStripeClient().customers.retrieve(
|
||||
owner.stripeCustomerId,
|
||||
);
|
||||
// Stripe stores credit as a negative balance.
|
||||
return customer.deleted ? 0 : Math.max(0, -customer.balance);
|
||||
};
|
||||
|
||||
export const initCloudServerCrons = () => {
|
||||
scheduleJob("cloud-server-payment-reminders", "0 2 * * *", () =>
|
||||
sendCloudServerPaymentReminders().catch((err) =>
|
||||
console.error("[cloud-server] failed to send payment reminders:", err),
|
||||
),
|
||||
);
|
||||
|
||||
scheduleJob("cloud-server-bandwidth", "0 1 * * *", () =>
|
||||
recordBandwidthAndWarn().catch((err) =>
|
||||
console.error("[cloud-server] failed to record bandwidth:", err),
|
||||
),
|
||||
);
|
||||
|
||||
scheduleJob("cloud-server-suspension-cleanup", "0 * * * *", () =>
|
||||
removeUnpaidCloudServers().catch((err) =>
|
||||
console.error("[cloud-server] failed to remove unpaid servers:", err),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { findOrganizationById } from "@dokploy/server";
|
||||
import CloudServerNoticeEmail from "@dokploy/server/emails/emails/cloud-server-notice";
|
||||
import type { CloudServer } from "@dokploy/server/services/cloud-server";
|
||||
import { EXTRA_BANDWIDTH_CENTS_PER_GB } from "@dokploy/server/utils/digitalocean";
|
||||
import { sendEmail } from "@dokploy/server/verification/send-verification-email";
|
||||
import { render } from "@react-email/components";
|
||||
import { format } from "date-fns";
|
||||
import { WEBSITE_URL } from "@/server/utils/stripe";
|
||||
|
||||
const sendNotice = async (
|
||||
record: CloudServer,
|
||||
content: {
|
||||
subject: string;
|
||||
title: string;
|
||||
message: string;
|
||||
warning?: string;
|
||||
payment?: boolean;
|
||||
},
|
||||
) => {
|
||||
const organization = await findOrganizationById(record.organizationId);
|
||||
if (!organization) return;
|
||||
|
||||
const html = await render(
|
||||
CloudServerNoticeEmail({
|
||||
userName: organization.owner.firstName || "User",
|
||||
title: content.title,
|
||||
message: content.message,
|
||||
warning: content.warning,
|
||||
actionLabel: content.payment
|
||||
? "Update Payment Method"
|
||||
: "View Cloud Servers",
|
||||
// A Stripe portal link carries a secret that logs anyone in, so it never travels by email.
|
||||
actionUrl: content.payment
|
||||
? `${WEBSITE_URL}/dashboard/settings/billing`
|
||||
: `${WEBSITE_URL}/dashboard/settings/cloud-servers`,
|
||||
}),
|
||||
);
|
||||
await sendEmail({
|
||||
email: organization.owner.email,
|
||||
subject: content.subject,
|
||||
text: html,
|
||||
});
|
||||
};
|
||||
|
||||
export const sendCloudServerRenewalEmail = (
|
||||
record: CloudServer,
|
||||
renewsAt: Date,
|
||||
) =>
|
||||
sendNotice(record, {
|
||||
subject: `Action required: update the payment method for ${record.hostname}`,
|
||||
title: "Update your payment method",
|
||||
message: `your cloud server ${record.hostname} renews on ${format(renewsAt, "MMM dd, yyyy")} and its payment method is missing or expires before that date.`,
|
||||
warning:
|
||||
"If the renewal payment fails, the server is powered off and then deleted.",
|
||||
payment: true,
|
||||
});
|
||||
|
||||
export const sendCloudServerPaymentFailedEmail = (
|
||||
record: CloudServer,
|
||||
deletesAt: Date,
|
||||
) =>
|
||||
sendNotice(record, {
|
||||
subject: `Action required: payment failed for ${record.hostname}`,
|
||||
title: "Payment failed",
|
||||
message: `we could not charge the payment for your cloud server ${record.hostname}, so it has been powered off.`,
|
||||
warning: `The server and all its data will be deleted on ${format(deletesAt, "MMM dd, yyyy")} unless the payment is completed.`,
|
||||
payment: true,
|
||||
});
|
||||
|
||||
export const sendCloudServerReactivatedEmail = (record: CloudServer) =>
|
||||
sendNotice(record, {
|
||||
subject: `Your cloud server ${record.hostname} is back online`,
|
||||
title: "Payment received",
|
||||
message: `we received your payment and your cloud server ${record.hostname} has been powered back on.`,
|
||||
});
|
||||
|
||||
export const sendCloudServerDeletedEmail = (record: CloudServer) =>
|
||||
sendNotice(record, {
|
||||
subject: `Your cloud server ${record.hostname} was deleted`,
|
||||
title: "Server deleted",
|
||||
message: `your cloud server ${record.hostname} and all its data were deleted because ${record.status === "suspended" ? "its payment was not completed" : "its subscription was cancelled"}. You will not be charged for it again.`,
|
||||
});
|
||||
|
||||
export const sendCloudServerBandwidthEmail = (
|
||||
record: CloudServer,
|
||||
percent: number,
|
||||
transferTb: number,
|
||||
) =>
|
||||
sendNotice(record, {
|
||||
subject:
|
||||
percent >= 100
|
||||
? `${record.hostname} has used all of its included transfer`
|
||||
: `${record.hostname} has used ${percent}% of its included transfer`,
|
||||
title: "Transfer usage",
|
||||
message: `your cloud server ${record.hostname} has used ${percent}% of the ${transferTb} TB of transfer included in this billing period.`,
|
||||
warning: `Transfer above the included amount is billed at $${(EXTRA_BANDWIDTH_CENTS_PER_GB / 100).toFixed(2)} per GB on the next invoice.`,
|
||||
});
|
||||
+2
-1
@@ -14,7 +14,8 @@
|
||||
"!**/dist",
|
||||
"!**/drizzle/**",
|
||||
"!node_modules/**",
|
||||
"!packages/server/package.json"
|
||||
"!packages/server/package.json",
|
||||
"!packages/server/src/utils/digitalocean-api.ts"
|
||||
],
|
||||
"maxSize": 2097152,
|
||||
"experimentalScannerIgnores": [".next", "node_modules", ".docker", "dist"]
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
"esbuild": "tsx ./esbuild.config.ts && tsc --project tsconfig.server.json --emitDeclarationOnly ",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"dbml:generate": "npx tsx src/db/schema/dbml.ts",
|
||||
"generate:drizzle": "pnpm dlx @better-auth/cli generate --output auth-schema2.ts --config src/lib/auth-cli.ts"
|
||||
"generate:drizzle": "pnpm dlx @better-auth/cli generate --output auth-schema2.ts --config src/lib/auth-cli.ts",
|
||||
"generate:digitalocean": "pnpm dlx openapi-typescript@7.13.0 https://api-engineering.nyc3.cdn.digitaloceanspaces.com/spec-ci/DigitalOcean-public.v2.yaml -o src/utils/digitalocean-api.ts --default-non-nullable=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/anthropic": "^3.0.44",
|
||||
@@ -76,6 +77,7 @@
|
||||
"node-schedule": "2.1.1",
|
||||
"nodemailer": "10.1.4",
|
||||
"octokit": "3.1.2",
|
||||
"openapi-fetch": "0.17.0",
|
||||
"pino": "9.4.0",
|
||||
"pino-pretty": "11.2.2",
|
||||
"postgres": "3.4.4",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { pgEnum, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { bigint, pgEnum, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
import { organization } from "./account";
|
||||
@@ -7,7 +7,6 @@ import { server } from "./server";
|
||||
import { sshKeys } from "./ssh-key";
|
||||
|
||||
export const cloudServerStatus = pgEnum("cloudServerStatus", [
|
||||
"pending",
|
||||
"provisioning",
|
||||
"configuring",
|
||||
"ready",
|
||||
@@ -29,9 +28,9 @@ export const cloudServer = pgTable("cloud_server", {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
plan: text("plan").notNull(),
|
||||
status: cloudServerStatus("status").notNull().default("pending"),
|
||||
status: cloudServerStatus("status").notNull(),
|
||||
providerVmId: text("providerVmId"),
|
||||
providerNetworkId: text("providerNetworkId"),
|
||||
providerVpcId: text("providerVpcId"),
|
||||
providerFirewallId: text("providerFirewallId"),
|
||||
zone: text("zone").notNull(),
|
||||
sshKeyId: text("sshKeyId").references(() => sshKeys.sshKeyId, {
|
||||
@@ -42,6 +41,11 @@ export const cloudServer = pgTable("cloud_server", {
|
||||
stripeSubscriptionId: text("stripeSubscriptionId"),
|
||||
stripeCheckoutSessionId: text("stripeCheckoutSessionId"),
|
||||
suspendedAt: text("suspendedAt"),
|
||||
paymentReminderAt: text("paymentReminderAt"),
|
||||
bandwidthBytes: bigint("bandwidthBytes", { mode: "number" })
|
||||
.notNull()
|
||||
.default(0),
|
||||
bandwidthMeasuredAt: text("bandwidthMeasuredAt"),
|
||||
errorMessage: text("errorMessage"),
|
||||
createdAt: text("createdAt")
|
||||
.notNull()
|
||||
|
||||
@@ -34,7 +34,7 @@ export const AccountDeletionCodeTemplate = ({
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
Body,
|
||||
Button,
|
||||
Container,
|
||||
Head,
|
||||
Heading,
|
||||
Html,
|
||||
Img,
|
||||
Link,
|
||||
Preview,
|
||||
Section,
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
userName: string;
|
||||
title: string;
|
||||
message: string;
|
||||
warning?: string;
|
||||
actionLabel: string;
|
||||
actionUrl: string;
|
||||
};
|
||||
|
||||
export const CloudServerNoticeEmail = ({
|
||||
userName = "User",
|
||||
title = "Payment failed",
|
||||
message = "we could not charge the payment for your cloud server acme-x7k2p9, so it has been powered off.",
|
||||
warning,
|
||||
actionLabel = "Update Payment Method",
|
||||
actionUrl = "https://app.dokploy.com/dashboard/settings/billing",
|
||||
}: TemplateProps) => {
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{title}</Preview>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
className="my-0 mx-auto"
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section className="bg-white px-[40px] py-[32px]">
|
||||
<Heading className="text-[#09090b] text-[22px] font-semibold m-0 mb-[8px]">
|
||||
{title}
|
||||
</Heading>
|
||||
<Text className="text-[#71717a] text-[14px] leading-[22px] m-0 mb-[24px]">
|
||||
Hello {userName}, {message}
|
||||
</Text>
|
||||
|
||||
{warning && (
|
||||
<Section className="bg-[#fefce8] border border-solid border-[#fef08a] rounded-lg px-[20px] py-[16px] mb-[24px]">
|
||||
<Text className="text-[#854d0e] text-[13px] leading-[20px] m-0">
|
||||
{warning}
|
||||
</Text>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section className="text-center mb-[24px]">
|
||||
<Button
|
||||
href={actionUrl}
|
||||
className="bg-[#09090b] rounded-lg text-white text-[14px] font-semibold no-underline text-center px-[24px] py-[12px]"
|
||||
>
|
||||
{actionLabel}
|
||||
</Button>
|
||||
</Section>
|
||||
</Section>
|
||||
|
||||
<Section className="bg-[#fafafa] rounded-b-xl px-[40px] py-[24px] text-center border-t border-solid border-[#e4e4e7]">
|
||||
<Text className="text-[#a1a1aa] text-[12px] leading-[18px] m-0">
|
||||
This is an automated email from{" "}
|
||||
<Link
|
||||
href="https://dokploy.com"
|
||||
className="text-[#71717a] underline"
|
||||
>
|
||||
Dokploy Cloud
|
||||
</Link>
|
||||
. If you have any questions about your billing, please contact
|
||||
our{" "}
|
||||
<Link
|
||||
href="https://discord.gg/2tBnJ3jDJc"
|
||||
className="text-[#71717a] underline"
|
||||
>
|
||||
support team
|
||||
</Link>
|
||||
.
|
||||
</Text>
|
||||
</Section>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
</Html>
|
||||
);
|
||||
};
|
||||
|
||||
export default CloudServerNoticeEmail;
|
||||
@@ -37,7 +37,7 @@ export const InvitationEmail = ({
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -45,7 +45,7 @@ export const InvoiceNotificationEmail = ({
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -50,7 +50,7 @@ export const OnboardingReturnEmail = ({
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -45,7 +45,7 @@ export const PaymentFailedEmail = ({
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -45,7 +45,7 @@ export const ServerSetupFailedEmail = ({
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -47,7 +47,7 @@ export const TrialExpiringEmail = ({
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -34,7 +34,7 @@ export const VerifyEmailTemplate = ({
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/1305b14577d1516a79a2d121e54dc7406a6785d5/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
} from "@dokploy/server/services/server";
|
||||
import {
|
||||
createSshKey,
|
||||
findSSHKeyById,
|
||||
removeSSHKeyById,
|
||||
} from "@dokploy/server/services/ssh-key";
|
||||
import { serverSetup } from "@dokploy/server/setup/server-setup";
|
||||
@@ -33,6 +32,7 @@ import {
|
||||
getDigitalOceanDroplet,
|
||||
getDigitalOceanDropletAction,
|
||||
getDigitalOceanDropletCount,
|
||||
getDigitalOceanDropletOutboundBytes,
|
||||
getDigitalOceanFirewall,
|
||||
getDigitalOceanVpcRange,
|
||||
getPrivateIPv4,
|
||||
@@ -42,23 +42,33 @@ import {
|
||||
updateDigitalOceanFirewall,
|
||||
} from "@dokploy/server/utils/digitalocean";
|
||||
import { generateSSHKey } from "@dokploy/server/utils/filesystem/ssh";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, eq, isNotNull, lt, ne, notInArray, sql } from "drizzle-orm";
|
||||
import { nanoid } from "nanoid";
|
||||
import { Client } from "ssh2";
|
||||
import {
|
||||
and,
|
||||
eq,
|
||||
isNotNull,
|
||||
isNull,
|
||||
lt,
|
||||
ne,
|
||||
notInArray,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import { customAlphabet } from "nanoid";
|
||||
|
||||
export type CloudServer = typeof cloudServer.$inferSelect;
|
||||
|
||||
// Stripe can deliver the same webhook more than once; only the call that inserts the row gets to provision.
|
||||
export const createCloudServer = async (
|
||||
input: typeof cloudServer.$inferInsert,
|
||||
) => {
|
||||
const record = await db
|
||||
return db
|
||||
.insert(cloudServer)
|
||||
.values(input)
|
||||
.onConflictDoNothing()
|
||||
.returning()
|
||||
.then((r) => r[0]);
|
||||
if (!record) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
return record;
|
||||
};
|
||||
|
||||
export const assertCloudServerCapacity = async () => {
|
||||
@@ -159,28 +169,6 @@ export const findCloudServerBySubscriptionId = async (
|
||||
});
|
||||
};
|
||||
|
||||
// Stripe can deliver the same webhook more than once; only the call that flips "pending" gets to provision.
|
||||
export const claimCloudServerForProvisioning = async (
|
||||
cloudServerId: string,
|
||||
stripeSubscriptionId: string,
|
||||
) => {
|
||||
return db
|
||||
.update(cloudServer)
|
||||
.set({
|
||||
status: "provisioning",
|
||||
stripeSubscriptionId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(cloudServer.cloudServerId, cloudServerId),
|
||||
eq(cloudServer.status, "pending"),
|
||||
),
|
||||
)
|
||||
.returning()
|
||||
.then((r) => r[0]);
|
||||
};
|
||||
|
||||
export const claimCloudServerForUpgrade = async (cloudServerId: string) => {
|
||||
return db
|
||||
.update(cloudServer)
|
||||
@@ -199,17 +187,6 @@ export const claimCloudServerForUpgrade = async (cloudServerId: string) => {
|
||||
.then((r) => r[0]);
|
||||
};
|
||||
|
||||
export const deletePendingCloudServer = async (cloudServerId: string) => {
|
||||
return db
|
||||
.delete(cloudServer)
|
||||
.where(
|
||||
and(
|
||||
eq(cloudServer.cloudServerId, cloudServerId),
|
||||
eq(cloudServer.status, "pending"),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const findSuspendedCloudServersBefore = async (cutoff: Date) => {
|
||||
return db.query.cloudServer.findMany({
|
||||
where: and(
|
||||
@@ -219,13 +196,84 @@ export const findSuspendedCloudServersBefore = async (cutoff: Date) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const isNetworkUsedByOthers = async (
|
||||
providerNetworkId: string,
|
||||
export const findReadyCloudServers = async () => {
|
||||
return db.query.cloudServer.findMany({
|
||||
where: and(
|
||||
eq(cloudServer.status, "ready"),
|
||||
isNotNull(cloudServer.stripeSubscriptionId),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
// Every instance runs the reminders cron: only the one that moves the date past dueAt sends the email.
|
||||
export const claimCloudServerPaymentReminder = async (
|
||||
cloudServerId: string,
|
||||
dueAt: Date,
|
||||
) => {
|
||||
const claimed = await db
|
||||
.update(cloudServer)
|
||||
.set({ paymentReminderAt: new Date().toISOString() })
|
||||
.where(
|
||||
and(
|
||||
eq(cloudServer.cloudServerId, cloudServerId),
|
||||
or(
|
||||
isNull(cloudServer.paymentReminderAt),
|
||||
lt(cloudServer.paymentReminderAt, dueAt.toISOString()),
|
||||
),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
return claimed.length > 0;
|
||||
};
|
||||
|
||||
export const recordCloudServersBandwidth = async () => {
|
||||
const servers = await db.query.cloudServer.findMany({
|
||||
where: isNotNull(cloudServer.providerVmId),
|
||||
});
|
||||
|
||||
const measured: { previous: CloudServer; current: CloudServer }[] = [];
|
||||
|
||||
for (const record of servers) {
|
||||
const until = new Date();
|
||||
try {
|
||||
const bytes = await getDigitalOceanDropletOutboundBytes(
|
||||
record.providerVmId!,
|
||||
new Date(record.bandwidthMeasuredAt ?? record.createdAt),
|
||||
until,
|
||||
);
|
||||
// Every instance runs this cron: matching the value we read keeps a second one from adding the same traffic again.
|
||||
const [current] = await db
|
||||
.update(cloudServer)
|
||||
.set({
|
||||
bandwidthBytes: record.bandwidthBytes + bytes,
|
||||
bandwidthMeasuredAt: until.toISOString(),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(cloudServer.cloudServerId, record.cloudServerId),
|
||||
eq(cloudServer.bandwidthBytes, record.bandwidthBytes),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
if (current) measured.push({ previous: record, current });
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[cloud-server] failed to record bandwidth of ${record.cloudServerId}:`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return measured;
|
||||
};
|
||||
|
||||
export const isVpcUsedByOthers = async (
|
||||
providerVpcId: string,
|
||||
cloudServerId: string,
|
||||
) => {
|
||||
const record = await db.query.cloudServer.findFirst({
|
||||
where: and(
|
||||
eq(cloudServer.providerNetworkId, providerNetworkId),
|
||||
eq(cloudServer.providerVpcId, providerVpcId),
|
||||
ne(cloudServer.cloudServerId, cloudServerId),
|
||||
),
|
||||
});
|
||||
@@ -234,42 +282,46 @@ export const isNetworkUsedByOthers = async (
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const createOrgNetwork = async (organizationId: string, zone: string) => {
|
||||
const randomSuffix = customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789", 6);
|
||||
|
||||
// DO only accepts letters, digits, dashes and periods in droplet, firewall and VPC names.
|
||||
const organizationNamePrefix = (organizationId: string) =>
|
||||
`dokploy-${organizationId.replace(/[^a-zA-Z0-9-]/g, "-")}`;
|
||||
|
||||
export const buildCloudServerHostname = (organizationId: string) =>
|
||||
`${organizationNamePrefix(organizationId)}-${randomSuffix()}`;
|
||||
|
||||
const createOrgVpc = async (organizationId: string, zone: string) => {
|
||||
await ensureDigitalOceanDefaultVpc(zone);
|
||||
// DO only accepts letters, digits, dashes and periods in a VPC name.
|
||||
const safeOrgId = organizationId.replace(/[^a-zA-Z0-9-]/g, ".");
|
||||
return createDigitalOceanVpc({
|
||||
name: `dokploy-${safeOrgId}-${zone}-${nanoid(4)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, "x")}`,
|
||||
name: `${organizationNamePrefix(organizationId)}-${zone}-${randomSuffix(4)}`,
|
||||
region: zone,
|
||||
});
|
||||
};
|
||||
|
||||
// Purchases take turns here: DO gives VPCs created at the same moment the same range and
|
||||
// rejects all but one, and two servers of one organization would each create their own VPC.
|
||||
const assignOrgNetwork = (
|
||||
const assignOrgVpc = (
|
||||
cloudServerId: string,
|
||||
organizationId: string,
|
||||
zone: string,
|
||||
) =>
|
||||
db.transaction(async (tx) => {
|
||||
await tx.execute(
|
||||
sql`select pg_advisory_xact_lock(hashtext('cloud-server-network'))`,
|
||||
sql`select pg_advisory_xact_lock(hashtext('cloud-server-vpc'))`,
|
||||
);
|
||||
const sibling = await tx.query.cloudServer.findFirst({
|
||||
where: and(
|
||||
eq(cloudServer.organizationId, organizationId),
|
||||
eq(cloudServer.zone, zone),
|
||||
isNotNull(cloudServer.providerNetworkId),
|
||||
isNotNull(cloudServer.providerVpcId),
|
||||
),
|
||||
});
|
||||
const vpcId =
|
||||
sibling?.providerNetworkId ??
|
||||
(await createOrgNetwork(organizationId, zone));
|
||||
sibling?.providerVpcId ?? (await createOrgVpc(organizationId, zone));
|
||||
await tx
|
||||
.update(cloudServer)
|
||||
.set({ providerNetworkId: vpcId, updatedAt: new Date().toISOString() })
|
||||
.set({ providerVpcId: vpcId, updatedAt: new Date().toISOString() })
|
||||
.where(eq(cloudServer.cloudServerId, cloudServerId));
|
||||
return vpcId;
|
||||
});
|
||||
@@ -288,50 +340,13 @@ const waitForDropletActive = async (
|
||||
throw new Error("Timed out waiting for droplet to become active");
|
||||
};
|
||||
|
||||
const runSshCommand = (host: string, privateKey: string, command: string) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const client = new Client();
|
||||
client
|
||||
.once("ready", () => {
|
||||
client.exec(command, (err, stream) => {
|
||||
if (err) {
|
||||
client.end();
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
stream.on("close", () => {
|
||||
client.end();
|
||||
resolve();
|
||||
});
|
||||
stream.resume();
|
||||
stream.stderr.resume();
|
||||
});
|
||||
})
|
||||
.on("error", (err) => {
|
||||
client.end();
|
||||
reject(err);
|
||||
})
|
||||
.connect({
|
||||
host,
|
||||
port: 22,
|
||||
username: "root",
|
||||
privateKey,
|
||||
readyTimeout: 20_000,
|
||||
});
|
||||
});
|
||||
|
||||
// Fresh droplets accept SSH before cloud-init finishes, and cloud-init/unattended-upgrades hold the apt lock the setup script needs.
|
||||
const waitForBootComplete = async (
|
||||
host: string,
|
||||
privateKey: string,
|
||||
maxAttempts = 30,
|
||||
) => {
|
||||
const waitForBootComplete = async (serverId: string, maxAttempts = 30) => {
|
||||
let lastError: unknown;
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
try {
|
||||
await runSshCommand(
|
||||
host,
|
||||
privateKey,
|
||||
await execAsyncRemote(
|
||||
serverId,
|
||||
"cloud-init status --wait >/dev/null 2>&1; while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do sleep 3; done",
|
||||
);
|
||||
return;
|
||||
@@ -347,10 +362,9 @@ const waitForBootComplete = async (
|
||||
|
||||
// Builds spike RAM for short periods; swap lets them finish slower instead of being OOM-killed.
|
||||
// Recreates the swapfile when its size differs, so the same command works after an upgrade.
|
||||
const ensureSwap = (host: string, privateKey: string, swapGb: number) =>
|
||||
runSshCommand(
|
||||
host,
|
||||
privateKey,
|
||||
const ensureSwap = (serverId: string, swapGb: number) =>
|
||||
execAsyncRemote(
|
||||
serverId,
|
||||
[
|
||||
`want=$((${swapGb}*1024*1024*1024)); cur=$(stat -c %s /swapfile 2>/dev/null || echo 0);`,
|
||||
'if [ "$cur" != "$want" ]; then',
|
||||
@@ -362,6 +376,19 @@ const ensureSwap = (host: string, privateKey: string, swapGb: number) =>
|
||||
].join(" "),
|
||||
);
|
||||
|
||||
// DO answers 404 for a key that a droplet request has just used, and only deletes it some seconds later.
|
||||
const deleteSshKeyWhenFree = async (sshKeyId: number, maxAttempts = 12) => {
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
try {
|
||||
await deleteDigitalOceanSshKey(sshKeyId);
|
||||
return;
|
||||
} catch {
|
||||
await sleep(10_000);
|
||||
}
|
||||
}
|
||||
console.error(`[cloud-server] could not delete DO ssh key ${sshKeyId}`);
|
||||
};
|
||||
|
||||
export const provisionCloudServer = async (params: {
|
||||
cloudServerId: string;
|
||||
organizationId: string;
|
||||
@@ -374,21 +401,7 @@ export const provisionCloudServer = async (params: {
|
||||
params;
|
||||
const { publicKey, privateKey } = await generateSSHKey("rsa");
|
||||
|
||||
const vpcId = await assignOrgNetwork(cloudServerId, organizationId, zone);
|
||||
|
||||
// Created before the droplet so it never boots with every port reachable.
|
||||
const firewallId = await createDigitalOceanFirewall({
|
||||
name: hostname,
|
||||
tag: getCloudServerTag(cloudServerId),
|
||||
inboundRules: toDigitalOceanRules([
|
||||
...getSystemFirewallRules(
|
||||
DEFAULT_MONITORING_PORT,
|
||||
await getDigitalOceanVpcRange(vpcId),
|
||||
),
|
||||
...DEFAULT_FIREWALL_RULES,
|
||||
]),
|
||||
});
|
||||
await updateCloudServer(cloudServerId, { providerFirewallId: firewallId });
|
||||
const vpcId = await assignOrgVpc(cloudServerId, organizationId, zone);
|
||||
|
||||
const providerSshKeyId = await createDigitalOceanSshKey({
|
||||
name: hostname,
|
||||
@@ -415,9 +428,7 @@ export const provisionCloudServer = async (params: {
|
||||
ipAddress = await waitForDropletActive(String(droplet.id));
|
||||
} finally {
|
||||
// The key is only read when the droplet is created, keeping it would just pile up keys in the DO account.
|
||||
await deleteDigitalOceanSshKey(providerSshKeyId).catch((err) =>
|
||||
console.error("[cloud-server] failed to delete DO ssh key:", err),
|
||||
);
|
||||
void deleteSshKeyWhenFree(providerSshKeyId);
|
||||
}
|
||||
|
||||
await updateCloudServer(cloudServerId, {
|
||||
@@ -425,9 +436,6 @@ export const provisionCloudServer = async (params: {
|
||||
status: "configuring",
|
||||
});
|
||||
|
||||
await waitForBootComplete(ipAddress, privateKey);
|
||||
await ensureSwap(ipAddress, privateKey, swapGb);
|
||||
|
||||
const sshKey = await createSshKey({
|
||||
name: hostname,
|
||||
publicKey,
|
||||
@@ -455,11 +463,13 @@ export const provisionCloudServer = async (params: {
|
||||
sshKeyId: sshKey.sshKeyId,
|
||||
});
|
||||
|
||||
await waitForBootComplete(serverRecord.serverId);
|
||||
await ensureSwap(serverRecord.serverId, swapGb);
|
||||
await serverSetup(serverRecord.serverId);
|
||||
await updateCloudServer(cloudServerId, { status: "ready" });
|
||||
};
|
||||
|
||||
const deleteNetworkWhenFree = async (vpcId: string, maxAttempts = 12) => {
|
||||
const deleteVpcWhenFree = async (vpcId: string, maxAttempts = 12) => {
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
try {
|
||||
await deleteDigitalOceanVpc(vpcId);
|
||||
@@ -468,7 +478,6 @@ const deleteNetworkWhenFree = async (vpcId: string, maxAttempts = 12) => {
|
||||
const status = (err as { response?: { status: number } }).response
|
||||
?.status;
|
||||
if (status === 404) return;
|
||||
// DO rejects the delete with 403/409 until the destroyed droplet has fully left the VPC.
|
||||
await sleep(10_000);
|
||||
}
|
||||
}
|
||||
@@ -497,14 +506,13 @@ export const releaseProviderResources = async (record: CloudServer) => {
|
||||
if (err?.response?.status !== 404) throw err;
|
||||
});
|
||||
}
|
||||
// Covers a droplet that was created but whose id never got saved.
|
||||
await deleteDigitalOceanDropletsByTag(
|
||||
getCloudServerTag(record.cloudServerId),
|
||||
);
|
||||
|
||||
const vpcId = record.providerNetworkId;
|
||||
if (vpcId && !(await isNetworkUsedByOthers(vpcId, record.cloudServerId))) {
|
||||
await deleteNetworkWhenFree(vpcId);
|
||||
const vpcId = record.providerVpcId;
|
||||
if (vpcId && !(await isVpcUsedByOthers(vpcId, record.cloudServerId))) {
|
||||
await deleteVpcWhenFree(vpcId);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -513,12 +521,9 @@ const removeLinkedServer = async (record: CloudServer) => {
|
||||
const linkedServer = await findServerById(record.serverId);
|
||||
await removeDeploymentsByServerId(linkedServer);
|
||||
await deleteServer(record.serverId);
|
||||
// The key was generated for this server only, nothing else can use it.
|
||||
if (record.sshKeyId) await removeSSHKeyById(record.sshKeyId);
|
||||
};
|
||||
|
||||
// Only terminations the customer confirmed on a server without services remove it from Dokploy;
|
||||
// automatic ones (non-payment, Stripe cancellation) keep it inactive so its services can still be moved.
|
||||
export const terminateCloudServer = async (
|
||||
cloudServerId: string,
|
||||
options: { removeLinkedServer?: boolean } = {},
|
||||
@@ -610,12 +615,10 @@ export const resizeCloudServerVm = async (
|
||||
await waitForDropletAction(record.providerVmId, resize.id);
|
||||
await powerOnCloudServerVm(record);
|
||||
|
||||
if (!record.ipAddress || !record.sshKeyId) return;
|
||||
// The resize already succeeded at this point; a swap hiccup must not roll the upgrade back.
|
||||
if (!record.serverId) return;
|
||||
try {
|
||||
const sshKey = await findSSHKeyById(record.sshKeyId);
|
||||
await waitForBootComplete(record.ipAddress, sshKey.privateKey);
|
||||
await ensureSwap(record.ipAddress, sshKey.privateKey, swapGb);
|
||||
await waitForBootComplete(record.serverId);
|
||||
await ensureSwap(record.serverId, swapGb);
|
||||
} catch (err) {
|
||||
console.error("[cloud-server] failed to resize swap after upgrade:", err);
|
||||
}
|
||||
@@ -625,8 +628,6 @@ const ANYWHERE = ["0.0.0.0/0", "::/0"];
|
||||
const ALL_PORTS = "1-65535";
|
||||
const DEFAULT_MONITORING_PORT = 4500;
|
||||
|
||||
// Dokploy manages the server over SSH and reads its metrics on the monitoring port, so these can't be closed.
|
||||
// The VPC is per organization, so its range only ever matches the customer's own servers.
|
||||
const getSystemFirewallRules = (
|
||||
monitoringPort: number,
|
||||
vpcRange: string | null,
|
||||
@@ -652,7 +653,7 @@ const toDigitalOceanRules = (
|
||||
): DigitalOceanInboundRule[] =>
|
||||
rules.map((rule) => ({
|
||||
protocol: rule.protocol,
|
||||
...(rule.protocol === "icmp" ? {} : { ports: rule.ports }),
|
||||
ports: rule.protocol === "icmp" ? "0" : rule.ports,
|
||||
sources: { addresses: rule.sources },
|
||||
}));
|
||||
|
||||
@@ -687,9 +688,7 @@ const getMonitoringPort = async (record: CloudServer) => {
|
||||
const getSystemRules = async (record: CloudServer) => {
|
||||
const [monitoringPort, vpcRange] = await Promise.all([
|
||||
getMonitoringPort(record),
|
||||
record.providerNetworkId
|
||||
? getDigitalOceanVpcRange(record.providerNetworkId)
|
||||
: null,
|
||||
record.providerVpcId ? getDigitalOceanVpcRange(record.providerVpcId) : null,
|
||||
]);
|
||||
return getSystemFirewallRules(monitoringPort, vpcRange);
|
||||
};
|
||||
@@ -708,7 +707,6 @@ const withoutSystemRules = (
|
||||
(rule) => !systemRules.some((system) => isSameRule(rule, system)),
|
||||
);
|
||||
|
||||
// Every server starts with a firewall; removing it leaves the droplet like a regular VPS with every port open.
|
||||
export const getCloudServerFirewall = async (record: CloudServer) => {
|
||||
getProvisionedVmId(record);
|
||||
const systemRules = await getSystemRules(record);
|
||||
@@ -728,7 +726,7 @@ export const getCloudServerFirewall = async (record: CloudServer) => {
|
||||
status: firewall.status,
|
||||
systemRules,
|
||||
rules: withoutSystemRules(
|
||||
fromDigitalOceanRules(firewall.inbound_rules),
|
||||
fromDigitalOceanRules(firewall.inbound_rules ?? []),
|
||||
systemRules,
|
||||
),
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,6 @@
|
||||
const DIGITALOCEAN_BASE = "https://api.digitalocean.com/v2";
|
||||
import createClient from "openapi-fetch";
|
||||
import type { components, paths } from "./digitalocean-api";
|
||||
|
||||
const DROPLET_IMAGE = "ubuntu-24-04-x64";
|
||||
|
||||
export interface DokployPlan {
|
||||
@@ -9,9 +11,12 @@ export interface DokployPlan {
|
||||
cpus: number;
|
||||
memoryGb: number;
|
||||
storageGb: number;
|
||||
transferTb: number;
|
||||
}
|
||||
|
||||
// Sized by RAM since builds are the main consumer. Region availability differs per size family; "-intel" covers the widest set (incl. fra1).
|
||||
export const EXTRA_BANDWIDTH_CENTS_PER_GB = 3;
|
||||
|
||||
export const DOKPLOY_PLANS: DokployPlan[] = [
|
||||
{
|
||||
id: "hobby",
|
||||
@@ -21,6 +26,7 @@ export const DOKPLOY_PLANS: DokployPlan[] = [
|
||||
cpus: 1,
|
||||
memoryGb: 2,
|
||||
storageGb: 50,
|
||||
transferTb: 2,
|
||||
},
|
||||
{
|
||||
id: "starter",
|
||||
@@ -30,6 +36,7 @@ export const DOKPLOY_PLANS: DokployPlan[] = [
|
||||
cpus: 2,
|
||||
memoryGb: 4,
|
||||
storageGb: 80,
|
||||
transferTb: 4,
|
||||
},
|
||||
{
|
||||
id: "pro",
|
||||
@@ -39,6 +46,7 @@ export const DOKPLOY_PLANS: DokployPlan[] = [
|
||||
cpus: 4,
|
||||
memoryGb: 8,
|
||||
storageGb: 160,
|
||||
transferTb: 5,
|
||||
},
|
||||
{
|
||||
id: "business",
|
||||
@@ -48,54 +56,39 @@ export const DOKPLOY_PLANS: DokployPlan[] = [
|
||||
cpus: 8,
|
||||
memoryGb: 16,
|
||||
storageGb: 320,
|
||||
transferTb: 6,
|
||||
},
|
||||
];
|
||||
|
||||
function getHeaders() {
|
||||
const token = process.env.DIGITALOCEAN_TOKEN;
|
||||
if (!token) throw new Error("DIGITALOCEAN_TOKEN is not set");
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
};
|
||||
}
|
||||
const digitalOcean = createClient<paths>({
|
||||
baseUrl: "https://api.digitalocean.com",
|
||||
fetch: (request) => fetch(request),
|
||||
});
|
||||
|
||||
async function digitalOceanFetch<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const res = await fetch(`${DIGITALOCEAN_BASE}${path}`, {
|
||||
...options,
|
||||
headers: { ...getHeaders(), ...(options.headers ?? {}) },
|
||||
}).catch((err: unknown) => {
|
||||
throw new Error(
|
||||
digitalOcean.use({
|
||||
onRequest({ request }) {
|
||||
const token = process.env.DIGITALOCEAN_TOKEN;
|
||||
if (!token) throw new Error("DIGITALOCEAN_TOKEN is not set");
|
||||
request.headers.set("Authorization", `Bearer ${token}`);
|
||||
return request;
|
||||
},
|
||||
onError: ({ error }) =>
|
||||
new Error(
|
||||
"Couldn't reach DigitalOcean, check the network connection and try again",
|
||||
{ cause: err },
|
||||
{ cause: error },
|
||||
),
|
||||
async onResponse({ request, response }) {
|
||||
if (response.ok) return;
|
||||
const data = await response.json().catch(() => null);
|
||||
const { pathname } = new URL(request.url);
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
`DigitalOcean ${request.method} ${pathname} failed (${response.status}): ${data?.message ?? response.statusText}`,
|
||||
),
|
||||
{ response: { status: response.status, data } },
|
||||
);
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
body = await res.text();
|
||||
}
|
||||
const detail =
|
||||
typeof body === "object" && body && "message" in body
|
||||
? String(body.message)
|
||||
: JSON.stringify(body);
|
||||
const err = new Error(
|
||||
`DigitalOcean ${options.method ?? "GET"} ${path.split("?")[0]} failed (${res.status}): ${detail}`,
|
||||
) as Error & { response: { status: number; data: unknown } };
|
||||
err.response = { status: res.status, data: body };
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export type DigitalOceanRegionContinent =
|
||||
| "Europe"
|
||||
@@ -134,16 +127,11 @@ export function getRegionInfo(slug: string) {
|
||||
}
|
||||
|
||||
export async function getDigitalOceanRegions(): Promise<DigitalOceanRegion[]> {
|
||||
const data = await digitalOceanFetch<{
|
||||
regions: {
|
||||
slug: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
sizes: string[];
|
||||
}[];
|
||||
}>("/regions?per_page=200");
|
||||
const { data } = await digitalOcean.GET("/v2/regions", {
|
||||
params: { query: { per_page: 200 } },
|
||||
});
|
||||
|
||||
return data.regions
|
||||
return data!.regions
|
||||
.filter((r) => r.available && r.slug in REGIONS)
|
||||
.map((r) => ({
|
||||
id: r.slug,
|
||||
@@ -162,75 +150,63 @@ export async function getDigitalOceanRegions(): Promise<DigitalOceanRegion[]> {
|
||||
);
|
||||
}
|
||||
|
||||
export interface DigitalOceanDroplet {
|
||||
id: number;
|
||||
name: string;
|
||||
status: "new" | "active" | "off" | "archive";
|
||||
created_at: string;
|
||||
region: { slug: string; name: string };
|
||||
image: { distribution: string; name: string };
|
||||
size_slug: string;
|
||||
vpc_uuid: string;
|
||||
networks: {
|
||||
v4: Array<{ ip_address: string; type: "public" | "private" }>;
|
||||
};
|
||||
}
|
||||
export type DigitalOceanDroplet = components["schemas"]["droplet"];
|
||||
|
||||
export async function createDigitalOceanSshKey(params: {
|
||||
name: string;
|
||||
publicKey: string;
|
||||
}): Promise<number> {
|
||||
const data = await digitalOceanFetch<{ ssh_key: { id: number } }>(
|
||||
"/account/keys",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ name: params.name, public_key: params.publicKey }),
|
||||
},
|
||||
);
|
||||
return data.ssh_key.id;
|
||||
const { data } = await digitalOcean.POST("/v2/account/keys", {
|
||||
body: { name: params.name, public_key: params.publicKey },
|
||||
});
|
||||
return data!.ssh_key!.id!;
|
||||
}
|
||||
|
||||
export async function deleteDigitalOceanSshKey(id: number): Promise<void> {
|
||||
await digitalOceanFetch(`/account/keys/${id}`, { method: "DELETE" });
|
||||
await digitalOcean.DELETE("/v2/account/keys/{ssh_key_identifier}", {
|
||||
params: { path: { ssh_key_identifier: id } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createDigitalOceanVpc(params: {
|
||||
name: string;
|
||||
region: string;
|
||||
}): Promise<string> {
|
||||
const data = await digitalOceanFetch<{ vpc: { id: string } }>("/vpcs", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
const { data } = await digitalOcean.POST("/v2/vpcs", {
|
||||
body: {
|
||||
name: params.name,
|
||||
region: params.region,
|
||||
description: "Dokploy cloud servers",
|
||||
}),
|
||||
},
|
||||
});
|
||||
return data.vpc.id;
|
||||
return data!.vpc!.id!;
|
||||
}
|
||||
|
||||
// DO makes the first VPC created in a region its default, and a default VPC can never be deleted.
|
||||
export async function ensureDigitalOceanDefaultVpc(region: string) {
|
||||
const perPage = 200;
|
||||
for (let page = 1; ; page++) {
|
||||
const data = await digitalOceanFetch<{
|
||||
vpcs: { region: string; default: boolean }[];
|
||||
links?: { pages?: { next?: string } };
|
||||
}>(`/vpcs?per_page=200&page=${page}`);
|
||||
if (data.vpcs.some((v) => v.region === region && v.default)) return;
|
||||
if (!data.links?.pages?.next) break;
|
||||
const { data } = await digitalOcean.GET("/v2/vpcs", {
|
||||
params: { query: { per_page: perPage, page } },
|
||||
});
|
||||
const vpcs = data?.vpcs ?? [];
|
||||
if (vpcs.some((v) => v.region === region && v.default)) return;
|
||||
if (vpcs.length < perPage) break;
|
||||
}
|
||||
await createDigitalOceanVpc({ name: `default-${region}`, region });
|
||||
}
|
||||
|
||||
export async function getDigitalOceanVpcRange(id: string): Promise<string> {
|
||||
const data = await digitalOceanFetch<{ vpc: { ip_range: string } }>(
|
||||
`/vpcs/${id}`,
|
||||
);
|
||||
return data.vpc.ip_range;
|
||||
const { data } = await digitalOcean.GET("/v2/vpcs/{vpc_id}", {
|
||||
params: { path: { vpc_id: id } },
|
||||
});
|
||||
return data!.vpc!.ip_range!;
|
||||
}
|
||||
|
||||
export async function deleteDigitalOceanVpc(id: string): Promise<void> {
|
||||
await digitalOceanFetch(`/vpcs/${id}`, { method: "DELETE" });
|
||||
await digitalOcean.DELETE("/v2/vpcs/{vpc_id}", {
|
||||
params: { path: { vpc_id: id } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createDigitalOceanDroplet(params: {
|
||||
@@ -242,59 +218,88 @@ export async function createDigitalOceanDroplet(params: {
|
||||
organizationId: string;
|
||||
cloudServerId: string;
|
||||
}): Promise<DigitalOceanDroplet> {
|
||||
const data = await digitalOceanFetch<{ droplet: DigitalOceanDroplet }>(
|
||||
"/droplets",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: params.name,
|
||||
region: params.region,
|
||||
size: params.size,
|
||||
image: DROPLET_IMAGE,
|
||||
vpc_uuid: params.vpcId,
|
||||
ssh_keys: [params.sshKeyId],
|
||||
monitoring: true,
|
||||
tags: [
|
||||
"dokploy-managed",
|
||||
`org:${params.organizationId}`,
|
||||
getCloudServerTag(params.cloudServerId),
|
||||
],
|
||||
}),
|
||||
const { data } = await digitalOcean.POST("/v2/droplets", {
|
||||
body: {
|
||||
name: params.name,
|
||||
region: params.region,
|
||||
size: params.size,
|
||||
image: DROPLET_IMAGE,
|
||||
vpc_uuid: params.vpcId,
|
||||
ssh_keys: [params.sshKeyId],
|
||||
monitoring: true,
|
||||
tags: [
|
||||
"dokploy-managed",
|
||||
`org:${params.organizationId}`,
|
||||
getCloudServerTag(params.cloudServerId),
|
||||
],
|
||||
},
|
||||
);
|
||||
await assignDropletToProject(data.droplet.id);
|
||||
return data.droplet;
|
||||
});
|
||||
const { droplet } = data as { droplet: DigitalOceanDroplet };
|
||||
await assignDropletToProject(droplet.id);
|
||||
return droplet;
|
||||
}
|
||||
|
||||
async function assignDropletToProject(dropletId: number | string) {
|
||||
async function assignDropletToProject(dropletId: number) {
|
||||
const projectId = process.env.DIGITALOCEAN_PROJECT_ID;
|
||||
if (!projectId) return;
|
||||
await digitalOceanFetch(`/projects/${projectId}/resources`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ resources: [`do:droplet:${dropletId}`] }),
|
||||
}).catch((err) =>
|
||||
console.error("[cloud-server] failed to assign droplet to project:", err),
|
||||
);
|
||||
await digitalOcean
|
||||
.POST("/v2/projects/{project_id}/resources", {
|
||||
params: { path: { project_id: projectId } },
|
||||
body: { resources: [`do:droplet:${dropletId}`] },
|
||||
})
|
||||
.catch((err) =>
|
||||
console.error("[cloud-server] failed to assign droplet to project:", err),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDigitalOceanDroplet(
|
||||
id: string,
|
||||
): Promise<DigitalOceanDroplet> {
|
||||
const data = await digitalOceanFetch<{ droplet: DigitalOceanDroplet }>(
|
||||
`/droplets/${id}`,
|
||||
);
|
||||
return data.droplet;
|
||||
const { data } = await digitalOcean.GET("/v2/droplets/{droplet_id}", {
|
||||
params: { path: { droplet_id: Number(id) } },
|
||||
});
|
||||
return data!.droplet!;
|
||||
}
|
||||
|
||||
export async function getDigitalOceanDropletCount(): Promise<number> {
|
||||
const data = await digitalOceanFetch<{ meta: { total: number } }>(
|
||||
"/droplets?per_page=1",
|
||||
);
|
||||
return data.meta.total;
|
||||
const { data } = await digitalOcean.GET("/v2/droplets", {
|
||||
params: { query: { per_page: 1 } },
|
||||
});
|
||||
return data!.meta.total!;
|
||||
}
|
||||
|
||||
export async function deleteDigitalOceanDroplet(id: string): Promise<void> {
|
||||
await digitalOceanFetch(`/droplets/${id}`, { method: "DELETE" });
|
||||
await digitalOcean.DELETE("/v2/droplets/{droplet_id}", {
|
||||
params: { path: { droplet_id: Number(id) } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getDigitalOceanDropletOutboundBytes(
|
||||
dropletId: string,
|
||||
start: Date,
|
||||
end: Date,
|
||||
) {
|
||||
const { data } = await digitalOcean.GET(
|
||||
"/v2/monitoring/metrics/droplet/bandwidth",
|
||||
{
|
||||
params: {
|
||||
query: {
|
||||
host_id: dropletId,
|
||||
interface: "public",
|
||||
direction: "outbound",
|
||||
start: String(Math.floor(start.getTime() / 1000)),
|
||||
end: String(Math.floor(end.getTime() / 1000)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const samples = data!.data.result[0]?.values ?? [];
|
||||
let megabits = 0;
|
||||
for (let i = 1; i < samples.length; i++) {
|
||||
const seconds = Number(samples[i]![0]) - Number(samples[i - 1]![0]);
|
||||
megabits += Number(samples[i]![1]) * seconds;
|
||||
}
|
||||
return Math.round((megabits * 1_000_000) / 8);
|
||||
}
|
||||
|
||||
export function getCloudServerTag(cloudServerId: string) {
|
||||
@@ -304,21 +309,21 @@ export function getCloudServerTag(cloudServerId: string) {
|
||||
export async function deleteDigitalOceanDropletsByTag(
|
||||
tag: string,
|
||||
): Promise<void> {
|
||||
await digitalOceanFetch(`/droplets?tag_name=${encodeURIComponent(tag)}`, {
|
||||
method: "DELETE",
|
||||
await digitalOcean.DELETE("/v2/droplets", {
|
||||
params: { query: { tag_name: tag } },
|
||||
});
|
||||
}
|
||||
|
||||
export function getPrivateIPv4(
|
||||
droplet: DigitalOceanDroplet,
|
||||
): string | undefined {
|
||||
return droplet.networks.v4.find((ip) => ip.type === "private")?.ip_address;
|
||||
return droplet.networks.v4?.find((ip) => ip.type === "private")?.ip_address;
|
||||
}
|
||||
|
||||
export function getPublicIPv4(
|
||||
droplet: DigitalOceanDroplet,
|
||||
): string | undefined {
|
||||
return droplet.networks.v4.find((ip) => ip.type === "public")?.ip_address;
|
||||
return droplet.networks.v4?.find((ip) => ip.type === "public")?.ip_address;
|
||||
}
|
||||
|
||||
export type DropletPowerAction =
|
||||
@@ -327,60 +332,58 @@ export type DropletPowerAction =
|
||||
| "power_on"
|
||||
| "power_off";
|
||||
|
||||
export interface DigitalOceanAction {
|
||||
id: number;
|
||||
status: "in-progress" | "completed" | "errored";
|
||||
type: string;
|
||||
}
|
||||
const toAction = (action: components["schemas"]["action"]) => ({
|
||||
...action,
|
||||
id: action.id!,
|
||||
});
|
||||
|
||||
export async function runDigitalOceanDropletAction(
|
||||
const postDropletAction = async (
|
||||
dropletId: string,
|
||||
body: { type: DropletPowerAction | "resize"; size?: string; disk?: boolean },
|
||||
) => {
|
||||
const { data } = await digitalOcean.POST(
|
||||
"/v2/droplets/{droplet_id}/actions",
|
||||
{
|
||||
params: { path: { droplet_id: Number(dropletId) } },
|
||||
// The generated type loses the action types the spec maps through a discriminator (reboot, resize...).
|
||||
body: body as never,
|
||||
},
|
||||
);
|
||||
return toAction(data!.action!);
|
||||
};
|
||||
|
||||
export const runDigitalOceanDropletAction = (
|
||||
dropletId: string,
|
||||
type: DropletPowerAction,
|
||||
): Promise<DigitalOceanAction> {
|
||||
const data = await digitalOceanFetch<{ action: DigitalOceanAction }>(
|
||||
`/droplets/${dropletId}/actions`,
|
||||
{ method: "POST", body: JSON.stringify({ type }) },
|
||||
);
|
||||
return data.action;
|
||||
}
|
||||
) => postDropletAction(dropletId, { type });
|
||||
|
||||
export async function getDigitalOceanDropletAction(
|
||||
dropletId: string,
|
||||
actionId: number,
|
||||
): Promise<DigitalOceanAction> {
|
||||
const data = await digitalOceanFetch<{ action: DigitalOceanAction }>(
|
||||
`/droplets/${dropletId}/actions/${actionId}`,
|
||||
) {
|
||||
const { data } = await digitalOcean.GET(
|
||||
"/v2/droplets/{droplet_id}/actions/{action_id}",
|
||||
{
|
||||
params: {
|
||||
path: { droplet_id: Number(dropletId), action_id: actionId },
|
||||
},
|
||||
},
|
||||
);
|
||||
return data.action;
|
||||
return toAction(data!.action!);
|
||||
}
|
||||
|
||||
// disk: true also grows the disk to match the plan; DO can't shrink it back, so plans can only go up.
|
||||
export async function resizeDigitalOceanDroplet(
|
||||
dropletId: string,
|
||||
size: string,
|
||||
): Promise<DigitalOceanAction> {
|
||||
const data = await digitalOceanFetch<{ action: DigitalOceanAction }>(
|
||||
`/droplets/${dropletId}/actions`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ type: "resize", size, disk: true }),
|
||||
},
|
||||
);
|
||||
return data.action;
|
||||
}
|
||||
export const resizeDigitalOceanDroplet = (dropletId: string, size: string) =>
|
||||
postDropletAction(dropletId, { type: "resize", size, disk: true });
|
||||
|
||||
type FirewallProtocol = "tcp" | "udp" | "icmp";
|
||||
|
||||
export interface DigitalOceanInboundRule {
|
||||
protocol: FirewallProtocol;
|
||||
ports?: string;
|
||||
sources: { addresses?: string[] };
|
||||
}
|
||||
export type DigitalOceanInboundRule = NonNullable<
|
||||
components["schemas"]["firewall_rules"]["inbound_rules"]
|
||||
>[number];
|
||||
|
||||
const ALLOW_ALL_OUTBOUND = (["tcp", "udp", "icmp"] as const).map(
|
||||
(protocol) => ({
|
||||
protocol,
|
||||
...(protocol === "icmp" ? {} : { ports: "all" }),
|
||||
ports: protocol === "icmp" ? "0" : "all",
|
||||
destinations: { addresses: ["0.0.0.0/0", "::/0"] },
|
||||
}),
|
||||
);
|
||||
@@ -389,20 +392,16 @@ const firewallBody = (params: {
|
||||
name: string;
|
||||
tag: string;
|
||||
inboundRules: DigitalOceanInboundRule[];
|
||||
}) =>
|
||||
JSON.stringify({
|
||||
name: params.name,
|
||||
tags: [params.tag],
|
||||
inbound_rules: params.inboundRules,
|
||||
outbound_rules: ALLOW_ALL_OUTBOUND,
|
||||
});
|
||||
}) => ({
|
||||
name: params.name,
|
||||
tags: [params.tag],
|
||||
inbound_rules: params.inboundRules,
|
||||
outbound_rules: ALLOW_ALL_OUTBOUND,
|
||||
});
|
||||
|
||||
// DO only creates a tag implicitly when a droplet uses it; firewalls reject tags that don't exist yet.
|
||||
async function ensureDigitalOceanTag(name: string) {
|
||||
await digitalOceanFetch("/tags", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
await digitalOcean.POST("/v2/tags", { body: { name } });
|
||||
}
|
||||
|
||||
export async function createDigitalOceanFirewall(params: {
|
||||
@@ -411,23 +410,17 @@ export async function createDigitalOceanFirewall(params: {
|
||||
inboundRules: DigitalOceanInboundRule[];
|
||||
}): Promise<string> {
|
||||
await ensureDigitalOceanTag(params.tag);
|
||||
const data = await digitalOceanFetch<{ firewall: { id: string } }>(
|
||||
"/firewalls",
|
||||
{ method: "POST", body: firewallBody(params) },
|
||||
);
|
||||
return data.firewall.id;
|
||||
const { data } = await digitalOcean.POST("/v2/firewalls", {
|
||||
body: firewallBody(params),
|
||||
});
|
||||
return data!.firewall!.id!;
|
||||
}
|
||||
|
||||
export async function getDigitalOceanFirewall(id: string) {
|
||||
const data = await digitalOceanFetch<{
|
||||
firewall: {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "waiting" | "succeeded" | "failed";
|
||||
inbound_rules: DigitalOceanInboundRule[];
|
||||
};
|
||||
}>(`/firewalls/${id}`);
|
||||
return data.firewall;
|
||||
const { data } = await digitalOcean.GET("/v2/firewalls/{firewall_id}", {
|
||||
params: { path: { firewall_id: id } },
|
||||
});
|
||||
return data!.firewall!;
|
||||
}
|
||||
|
||||
// DO replaces the whole firewall on PUT, so name, tags and outbound rules have to be sent again.
|
||||
@@ -439,12 +432,14 @@ export async function updateDigitalOceanFirewall(
|
||||
inboundRules: DigitalOceanInboundRule[];
|
||||
},
|
||||
) {
|
||||
await digitalOceanFetch(`/firewalls/${id}`, {
|
||||
method: "PUT",
|
||||
await digitalOcean.PUT("/v2/firewalls/{firewall_id}", {
|
||||
params: { path: { firewall_id: id } },
|
||||
body: firewallBody(params),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteDigitalOceanFirewall(id: string): Promise<void> {
|
||||
await digitalOceanFetch(`/firewalls/${id}`, { method: "DELETE" });
|
||||
await digitalOcean.DELETE("/v2/firewalls/{firewall_id}", {
|
||||
params: { path: { firewall_id: id } },
|
||||
});
|
||||
}
|
||||
|
||||
Generated
+62
@@ -761,6 +761,9 @@ importers:
|
||||
octokit:
|
||||
specifier: 3.1.2
|
||||
version: 3.1.2
|
||||
openapi-fetch:
|
||||
specifier: 0.17.0
|
||||
version: 0.17.0
|
||||
pino:
|
||||
specifier: 9.4.0
|
||||
version: 9.4.0
|
||||
@@ -1371,24 +1374,28 @@ packages:
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@biomejs/cli-linux-arm64@2.5.7':
|
||||
resolution: {integrity: sha512-rR2QE0yF2GYSuYuKIa7pKvODGJqnOH+2eDREAM8wV+mWKSkMQKdAp4zXEZfTaxY8PMoNONnpgSWcBCyLDPDOKg==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@biomejs/cli-linux-x64-musl@2.5.7':
|
||||
resolution: {integrity: sha512-rE5VZi+qtmPgQH+l7jVxYoZ18b/TiHEhulhMpjmCZH1PltSbjRcxNWywC3HZ9tYottG7ORkeTtoscBilKSBm0g==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@biomejs/cli-linux-x64@2.5.7':
|
||||
resolution: {integrity: sha512-FQgqJhscrqJUFptGaRSUJWlXAExwWcDwLuK49dvKfkQ1bB5SEEyFssnsxQY83Xm6jR0EbbX3+8+D5bfvYqUG2Q==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@biomejs/cli-win32-arm64@2.5.7':
|
||||
resolution: {integrity: sha512-Oq4x0CCwP4jirrcTywXs5kOGZ4v5vuEP+gWrbtjApOA2CL9F3F9GlIdQIci8AKSCa/zURanMRpX/4wQ7Am6hHg==}
|
||||
@@ -1755,89 +1762,105 @@ packages:
|
||||
resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linux-arm@1.3.4':
|
||||
resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linux-ppc64@1.3.4':
|
||||
resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linux-riscv64@1.3.4':
|
||||
resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linux-s390x@1.3.4':
|
||||
resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linux-x64@1.3.4':
|
||||
resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-libvips-linuxmusl-arm64@1.3.4':
|
||||
resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/sharp-libvips-linuxmusl-x64@1.3.4':
|
||||
resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/sharp-linux-arm64@0.35.5':
|
||||
resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linux-arm@0.35.5':
|
||||
resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linux-ppc64@0.35.5':
|
||||
resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linux-riscv64@0.35.5':
|
||||
resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linux-s390x@0.35.5':
|
||||
resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linux-x64@0.35.5':
|
||||
resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/sharp-linuxmusl-arm64@0.35.5':
|
||||
resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/sharp-linuxmusl-x64@0.35.5':
|
||||
resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/sharp-wasm32@0.35.5':
|
||||
resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
|
||||
@@ -2109,6 +2132,7 @@ packages:
|
||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@next/env@16.4.6':
|
||||
resolution: {integrity: sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==}
|
||||
@@ -2130,24 +2154,28 @@ packages:
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@next/swc-linux-arm64-musl@16.4.6':
|
||||
resolution: {integrity: sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@next/swc-linux-x64-gnu@16.4.6':
|
||||
resolution: {integrity: sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@next/swc-linux-x64-musl@16.4.6':
|
||||
resolution: {integrity: sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@next/swc-win32-arm64-msvc@16.4.6':
|
||||
resolution: {integrity: sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==}
|
||||
@@ -4004,71 +4032,85 @@ packages:
|
||||
resolution: {integrity: sha512-W1vUprf09RWaVWnsFP1vlUkEWJzTZlpObOEAYZXt9Fq0UVAOYEkeGr7wBX7McKqqIQskXdBnpiOMgwPujordgA==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-arm-musleabihf@4.65.0':
|
||||
resolution: {integrity: sha512-s8QTcZWgrl9haFzEGIqyE5BWyo89pFDGLMBFZ752WYxk8DJwNU/O1X6pZgPw829d9/sm6CCHyrMP3aurt76p1Q==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-arm64-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-ke1f6dLRzkqveyjjF2fkEwQYZvxHtNNwjegY8nJrwcO0Bdqr8CzFO/pKE0Bns13cx0qz2Ba2Y0Hs3dSwMdnHxA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-arm64-musl@4.65.0':
|
||||
resolution: {integrity: sha512-926SMeUcy4y18Rz/w2aJiUKOnyAnm6czg72bXkQEaeemsll+Wr0hnsjb2BGRpHvWgwAMYy5ACJCotbvfLCfj0A==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-loong64-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-6T7JNRP1hc4hqF2dUsEoVLOt9K8tmODoCLldtQRYnrddGGQY8Gqe2pM/qMMUo7EMowpP7oa2N95k0/8sYK/ipw==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-loong64-musl@4.65.0':
|
||||
resolution: {integrity: sha512-SImGFl1Je5kpyAgOCPONVT7h6ASV8mAUwGRjY7eZvVjPg//PfHOXgI+P241RF/+HqsA4PP3qD527ysWFKNQyhQ==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-ppc64-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-XeDTbmPF1Yu5asfXGPrMkWoxTDhgryQbmw5Q1+R582O51VNCk23J6f2pDrsAp5YkneBVBwtExx6ZGOb9D2aQ6A==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-ppc64-musl@4.65.0':
|
||||
resolution: {integrity: sha512-VS55JUI/1nsljmV/jfqNkLZXFw8uMO8nNlfoHmSevNf6fO3neuhyDvx9dv3c/Ytt8r/431SL8Qax1dpYvOMZTg==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-riscv64-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-Vblw84TbX7RS4la1Y4+yQ7aore/oSyaNtFbppuBr5Vs/4LfBeXKq9dIfoExw6zOvRERqd2rRAjnZRaMhH/0x5w==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-riscv64-musl@4.65.0':
|
||||
resolution: {integrity: sha512-7+gHjtONvKgwR9InTKFaLq53f6YzBJkgeMRBENdWTsQr+spahGqQm8HF5aXpq8i4JaRrOqYyv6Zn1WltDTxaZQ==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-s390x-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-KvNDC0J6s4vVHhtJ6KrDXU0Er0au/hmRIBq/+1maCV8TseGupeKizq0bWcrbp2HE1T8xoknvN0Q/KZ/YF0qX3w==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-x64-gnu@4.6.1':
|
||||
resolution: {integrity: sha512-DNGZvZDO5YF7jN5fX8ZqmGLjZEXIJRdJEdTFMhiyXqyXubBa0WVLDWSNlQ5JR2PNgDbEV1VQowhVRUh+74D+RA==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-x64-gnu@4.65.0':
|
||||
resolution: {integrity: sha512-GExdD15WPvu/x/drELjVam7vX8EsPgvTMOa/iJL/p/4m/oOqzbb7JXZg8fXR4hlXtg/sF2zyTZ3bR0AEtEMlhQ==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-x64-musl@4.65.0':
|
||||
resolution: {integrity: sha512-8sT9PemIZfIMED4Vd4KGoOXVDj5CMSWNcGdbheRUx9TYS03yOWdT2Q0lXPyEyNBB9YTilwewIQKNIBk6Nxi0Kg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-openbsd-x64@4.65.0':
|
||||
resolution: {integrity: sha512-pO6Ehi0jo5yE0R6PltKhJhv9mlIiyzBJk5N5NUF2OF6xtVKI+1bdXxj/rb0jGXy3hck1ELVT0QPY3tzkAm360w==}
|
||||
@@ -4361,24 +4403,28 @@ packages:
|
||||
engines: {node: '>= 20'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tailwindcss/oxide-linux-arm64-musl@4.3.1':
|
||||
resolution: {integrity: sha512-Bwv9KwOvE0VKa86xPFif9b9c3Y1NxOV1P0gLti/IYaWEsQYZXDlxfGEtA8mdDZ7SG3wyNXAWYT5SIn3giL57oA==}
|
||||
engines: {node: '>= 20'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tailwindcss/oxide-linux-x64-gnu@4.3.1':
|
||||
resolution: {integrity: sha512-Ymi8O8T15HYQdOUWUtTI6ldN0neHP85FC+Qz32xTcZ7iJXtem/x8ITev0o1e9e5rkqj4lONZfTRLvkmin1+tKg==}
|
||||
engines: {node: '>= 20'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tailwindcss/oxide-linux-x64-musl@4.3.1':
|
||||
resolution: {integrity: sha512-M+P/91qJ6uILLw4k2G93GMDRAXj61SMvFQYt39AqvUqYgExXpLL5aepfns7sj4HiAQeolirQF9E0lzRvdf4zPQ==}
|
||||
engines: {node: '>= 20'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tailwindcss/oxide-wasm32-wasi@4.3.1':
|
||||
resolution: {integrity: sha512-zsM8uOeqvVGHsAXsJxsT28ttosFahLJKCLOTUBqRAtKnVgGSRitds9T432QiT8b77Yga7JIBkulIRRlJPtYhRA==}
|
||||
@@ -6883,24 +6929,28 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
lightningcss-linux-arm64-musl@1.32.0:
|
||||
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
lightningcss-linux-x64-gnu@1.32.0:
|
||||
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
lightningcss-linux-x64-musl@1.32.0:
|
||||
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
lightningcss-win32-arm64-msvc@1.32.0:
|
||||
resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
|
||||
@@ -7514,6 +7564,9 @@ packages:
|
||||
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
openapi-fetch@0.17.0:
|
||||
resolution: {integrity: sha512-PsbZR1wAPcG91eEthKhN+Zn92FMHxv+/faECIwjXdxfTODGSGegYv0sc1Olz+HYPvKOuoXfp+0pA2XVt2cI0Ig==}
|
||||
|
||||
openapi-path-templating@2.2.1:
|
||||
resolution: {integrity: sha512-eN14VrDvl/YyGxxrkGOHkVkWEoPyhyeydOUrbvjoz8K5eIGgELASwN1eqFOJ2CTQMGCy2EntOK1KdtJ8ZMekcg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
@@ -7522,6 +7575,9 @@ packages:
|
||||
resolution: {integrity: sha512-DPlCms3KKEbjVQb0spV6Awfn6UWNheuG/+folQPzh/wUaKwuqvj8zt5gagD7qoyxtE03cIiKPgLFS3Q8Bz00uQ==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
openapi-typescript-helpers@0.1.0:
|
||||
resolution: {integrity: sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw==}
|
||||
|
||||
openapi3-ts@4.4.0:
|
||||
resolution: {integrity: sha512-9asTNB9IkKEzWMcHmVZE7Ts3kC9G7AFHfs8i7caD8HbI76gEjdkId4z/AkP83xdZsH7PLAnnbl47qZkXuxpArw==}
|
||||
|
||||
@@ -16872,6 +16928,10 @@ snapshots:
|
||||
is-docker: 2.2.1
|
||||
is-wsl: 2.2.0
|
||||
|
||||
openapi-fetch@0.17.0:
|
||||
dependencies:
|
||||
openapi-typescript-helpers: 0.1.0
|
||||
|
||||
openapi-path-templating@2.2.1:
|
||||
dependencies:
|
||||
apg-lite: 1.0.5
|
||||
@@ -16880,6 +16940,8 @@ snapshots:
|
||||
dependencies:
|
||||
apg-lite: 1.0.5
|
||||
|
||||
openapi-typescript-helpers@0.1.0: {}
|
||||
|
||||
openapi3-ts@4.4.0:
|
||||
dependencies:
|
||||
yaml: 2.8.3
|
||||
|
||||
Reference in New Issue
Block a user