Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,47 @@ Response:
| `DEFAULT_ADMIN_TOKEN` | *(auto)* | Master cluster administrator token |
| `MAX_ARTIFACT_SIZE_BYTES`| `2147483648` (2GB) | Maximum single artifact size |
| `COMPUTE_COST_PER_HOUR_USD`| `0.08` | Runner cost per hour for ROI calculation |
| `DODO_WEBHOOK_SECRET` | *(none)* | Webhook secret for automated subscription fulfillment |

---

## 💎 Remote Cache Storage Tiers & Commercial Billing

`poly-cloud-api` provides a turnkey remote caching service with self-serve subscription billing powered by **Dodo Payments**:

| Tier | Price | Cache Quota | Retention | Max Artifact | Ideal For |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **Developer Free** | **$0** / mo | **1 GB** | 7 Days | 100 MB | Individual open-source developers |
| **Pro Team** | **$29** / mo | **50 GB** | 30 Days | 500 MB | High-velocity engineering teams & CI/CD |
| **Enterprise Cloud** | **$199** / mo | **500 GB** | 90 Days | 2 GB | Large monorepos with multi-runner matrix pipelines |

### 🚀 Automatic Paywall & Quota Enforcement
When a workspace on the Free tier exhausts its storage quota, `PUT /v8/artifacts/:hash` returns `HTTP 402 Payment Required` along with an `X-Poly-Upgrade-Url` header:

```json
{
"error": "Payment Required",
"code": "QUOTA_EXCEEDED",
"message": "Storage quota of 1.00 GB exceeded for workspace 'acme-corp' on free tier. Upgrade to Pro (50 GB) to continue caching.",
"tier": "free",
"currentUsageBytes": 1094000000,
"quotaBytes": 1073741824,
"upgradeUrl": "https://checkout.dodopayments.com/buy/pdt_0NpjONNytUpW7gzjoDlYW?quantity=1&metadata.workspace=acme-corp&metadata.tier=pro"
}
```

### 💳 Billing & Webhook API Endpoints
- `GET /api/v1/billing/tiers`: Returns all tier specifications, limits, and pricing.
- `POST /api/v1/billing/checkout`: Generates a Dodo Payments checkout session for workspace upgrades (`{ workspaceSlug, tier }`).
- `POST /api/v1/billing/webhooks/dodo`: Listens for `payment.succeeded`, `subscription.active`, and `subscription.cancelled` events with HMAC-SHA256 signature verification to update workspace tier and quota in real time.
- `GET /api/v1/workspaces/:slug/billing`: Inspects current workspace tier, quota, usage percentage, and subscription renewal status.

---

## 🧪 Testing & Verification

```bash
# Run unit & integration test suite (94 tests)
# Run unit & integration test suite (101 tests)
npm test

# Run Biome formatting & linter verification
Expand Down
68 changes: 68 additions & 0 deletions src/billing/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { WorkspaceTier } from "../metadata/types.js";

export interface TierConfig {
tier: WorkspaceTier;
name: string;
priceMonthlyUsd: number;
quotaBytes: number;
quotaLabel: string;
maxArtifactSizeBytes: number;
defaultTtlSeconds: number;
dodoProductId?: string;
checkoutUrl?: string;
features: string[];
}

export const TIER_CONFIGS: Record<WorkspaceTier, TierConfig> = {
free: {
tier: "free",
name: "Developer Free Tier",
priceMonthlyUsd: 0,
quotaBytes: 1 * 1024 * 1024 * 1024, // 1 GB
quotaLabel: "1 GB",
maxArtifactSizeBytes: 100 * 1024 * 1024, // 100 MB
defaultTtlSeconds: 7 * 86400, // 7 days
features: [
"1 GB remote build cache storage",
"Turborepo & Poly CLI protocol support",
"7-day cache retention",
"Community GitHub support"
]
},
pro: {
tier: "pro",
name: "Pro Team Cloud Cache",
priceMonthlyUsd: 29,
quotaBytes: 50 * 1024 * 1024 * 1024, // 50 GB
quotaLabel: "50 GB",
maxArtifactSizeBytes: 500 * 1024 * 1024, // 500 MB
defaultTtlSeconds: 30 * 86400, // 30 days
dodoProductId: "pdt_0NpjONNytUpW7gzjoDlYW",
checkoutUrl: "https://checkout.dodopayments.com/buy/pdt_0NpjONNytUpW7gzjoDlYW",
features: [
"50 GB high-speed global remote cache",
"30-day cache retention with deduplication",
"GitHub Actions OIDC zero-secret authentication",
"Sub-15ms cache hits via Cloudflare R2 / S3",
"Priority developer support"
]
},
enterprise: {
tier: "enterprise",
name: "Enterprise Dedicated Cloud",
priceMonthlyUsd: 199,
quotaBytes: 500 * 1024 * 1024 * 1024, // 500 GB
quotaLabel: "500 GB",
maxArtifactSizeBytes: 2 * 1024 * 1024 * 1024, // 2 GB
defaultTtlSeconds: 90 * 86400, // 90 days
dodoProductId: "pdt_0NrFSmrXT8zU2u5BKGJ7y",
checkoutUrl: "https://checkout.dodopayments.com/buy/pdt_0NrFSmrXT8zU2u5BKGJ7y",
features: [
"500 GB dedicated enterprise cache",
"90-day retention with LRU watermark auto-eviction",
"Cryptographic SLSA Provenance & Ed25519 in-toto verification",
"Role-Based Team Tokens & SSO Integration",
"99.99% uptime SLA"
]
}
};
65 changes: 65 additions & 0 deletions src/metadata/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
TokenRole,
Workspace,
WorkspaceStats,
WorkspaceTier,
} from "./types.js";

function hashToken(rawToken: string): string {
Expand Down Expand Up @@ -45,6 +46,7 @@ export class MemoryMetadataStore implements MetadataStore {
slug: string,
name?: string,
quotaBytes = 107374182400,
tier: WorkspaceTier = "free",
): Promise<Workspace> {
const existing = await this.getWorkspaceBySlug(slug);
if (existing) return existing;
Expand All @@ -55,6 +57,7 @@ export class MemoryMetadataStore implements MetadataStore {
slug,
name: name || slug,
quotaBytes, // Default 100GB
tier,
defaultTtlSeconds: 604800, // 7 days
createdAt: new Date().toISOString(),
};
Expand All @@ -63,6 +66,20 @@ export class MemoryMetadataStore implements MetadataStore {
return ws;
}

async updateWorkspace(
id: string,
updates: Partial<Pick<Workspace, "name" | "quotaBytes" | "tier" | "subscriptionId" | "subscriptionStatus" | "subscriptionExpiresAt" | "defaultTtlSeconds">>
): Promise<Workspace | null> {
const ws = this.workspaces.get(id);
if (!ws) return null;
const updated: Workspace = { ...ws, ...updates };
this.workspaces.set(id, updated);
if (updated.slug) {
this.workspacesBySlug.set(updated.slug, id);
}
return updated;
}

async listWorkspaces(): Promise<Workspace[]> {
return Array.from(this.workspaces.values());
}
Expand Down Expand Up @@ -486,6 +503,18 @@ export class SqliteMetadataStore extends MemoryMetadataStore {
try {
db.exec("ALTER TABLE artifacts ADD COLUMN sha256 TEXT;");
} catch {}
try {
db.exec("ALTER TABLE workspaces ADD COLUMN tier TEXT;");
} catch {}
try {
db.exec("ALTER TABLE workspaces ADD COLUMN subscription_id TEXT;");
} catch {}
try {
db.exec("ALTER TABLE workspaces ADD COLUMN subscription_status TEXT;");
} catch {}
try {
db.exec("ALTER TABLE workspaces ADD COLUMN subscription_expires_at TEXT;");
} catch {}
try {
db.exec("ALTER TABLE artifacts ADD COLUMN is_attested INTEGER;");
} catch {}
Expand Down Expand Up @@ -529,6 +558,10 @@ export class SqliteMetadataStore extends MemoryMetadataStore {
slug: r.slug,
name: r.name,
quotaBytes: r.quota_bytes,
tier: (r as any).tier || "free",
subscriptionId: (r as any).subscription_id,
subscriptionStatus: (r as any).subscription_status,
subscriptionExpiresAt: (r as any).subscription_expires_at,
defaultTtlSeconds: r.default_ttl_seconds,
createdAt: r.created_at,
};
Expand Down Expand Up @@ -564,6 +597,38 @@ export class SqliteMetadataStore extends MemoryMetadataStore {
}
}

override async updateWorkspace(
id: string,
updates: Partial<Pick<Workspace, "name" | "quotaBytes" | "tier" | "subscriptionId" | "subscriptionStatus" | "subscriptionExpiresAt" | "defaultTtlSeconds">>
): Promise<Workspace | null> {
const updated = await super.updateWorkspace(id, updates);
if (!updated || !this.db) return updated;
try {
const db = this.db as any;
db.prepare(`
UPDATE workspaces SET
name = COALESCE(?, name),
quota_bytes = COALESCE(?, quota_bytes),
tier = COALESCE(?, tier),
subscription_id = COALESCE(?, subscription_id),
subscription_status = COALESCE(?, subscription_status),
subscription_expires_at = COALESCE(?, subscription_expires_at),
default_ttl_seconds = COALESCE(?, default_ttl_seconds)
WHERE id = ?
`).run(
updates.name ?? null,
updates.quotaBytes ?? null,
updates.tier ?? null,
updates.subscriptionId ?? null,
updates.subscriptionStatus ?? null,
updates.subscriptionExpiresAt ?? null,
updates.defaultTtlSeconds ?? null,
id
);
} catch {}
return updated;
}

override async close(): Promise<void> {
if (this.db && typeof (this.db as { close?: () => void }).close === "function") {
(this.db as { close: () => void }).close();
Expand Down
12 changes: 11 additions & 1 deletion src/metadata/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import type { DsseEnvelope, InTotoStatement } from "../attestation/types.js";

export type WorkspaceTier = "free" | "pro" | "enterprise";

export interface Workspace {
id: string;
slug: string;
name: string;
quotaBytes: number;
tier?: WorkspaceTier;
subscriptionId?: string;
subscriptionStatus?: string;
subscriptionExpiresAt?: string;
defaultTtlSeconds: number;
createdAt: string;
}
Expand Down Expand Up @@ -76,7 +82,11 @@ export interface MetadataStore {
// Workspaces
getWorkspaceBySlug(slug: string): Promise<Workspace | null>;
getWorkspaceById(id: string): Promise<Workspace | null>;
ensureWorkspace(slug: string, name?: string, quotaBytes?: number): Promise<Workspace>;
ensureWorkspace(slug: string, name?: string, quotaBytes?: number, tier?: WorkspaceTier): Promise<Workspace>;
updateWorkspace(
id: string,
updates: Partial<Pick<Workspace, "name" | "quotaBytes" | "tier" | "subscriptionId" | "subscriptionStatus" | "subscriptionExpiresAt" | "defaultTtlSeconds">>
): Promise<Workspace | null>;
listWorkspaces(): Promise<Workspace[]>;

// Tokens
Expand Down
47 changes: 47 additions & 0 deletions src/routes/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import crypto from "node:crypto";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import type { CorporateAttestationPolicy, DsseEnvelope } from "../attestation/types.js";
import { AttestationVerifier } from "../attestation/verifier.js";
import { TIER_CONFIGS } from "../billing/types.js";
import type { PolyCloudConfig } from "../config.js";
import type { MetadataStore } from "../metadata/types.js";
import { createAuthHook } from "../middleware/auth.js";
Expand Down Expand Up @@ -194,6 +195,28 @@ export async function registerArtifactRoutes(
});
}

// Quota and tier enforcement check
if (workspace.quotaBytes > 0) {
const stats = await store.getWorkspaceStats(workspace.slug);
const incoming = sizeBytes || 0;
if (stats.totalSizeBytes + incoming > workspace.quotaBytes) {
const tier = workspace.tier || "free";
const proConfig = TIER_CONFIGS.pro;
const upgradeUrl = `${proConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent(
workspace.slug,
)}&metadata.tier=pro`;

reply.header("X-Poly-Upgrade-Url", upgradeUrl);
return reply.code(402).send({
error: "Payment Required",
code: "QUOTA_EXCEEDED",
message: `Storage quota exceeded for workspace '${workspace.slug}' on ${tier} tier. Upgrade to Pro to continue caching.`,
tier,
upgradeUrl,
});
}
}

const uploadUrl = await storage.getPresignedPutUrl(storageKey, {
expiresInSeconds: config.presignedExpirySeconds,
sizeBytes,
Expand Down Expand Up @@ -394,6 +417,30 @@ export async function registerArtifactRoutes(
});
}

// Quota and tier enforcement check
if (workspace.quotaBytes > 0) {
const stats = await store.getWorkspaceStats(workspace.slug);
const incoming = contentLength || 0;
if (stats.totalSizeBytes + incoming > workspace.quotaBytes) {
const tier = workspace.tier || "free";
const proConfig = TIER_CONFIGS.pro;
const upgradeUrl = `${proConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent(
workspace.slug,
)}&metadata.tier=pro`;

reply.header("X-Poly-Upgrade-Url", upgradeUrl);
return reply.code(402).send({
error: "Payment Required",
code: "QUOTA_EXCEEDED",
message: `Storage quota of ${(workspace.quotaBytes / (1024 * 1024 * 1024)).toFixed(2)} GB exceeded for workspace '${workspace.slug}' on ${tier} tier. Upgrade to Pro (50 GB) to continue caching.`,
tier,
currentUsageBytes: stats.totalSizeBytes,
quotaBytes: workspace.quotaBytes,
upgradeUrl,
});
}
}

const putResult = await storage.put(storageKey, bodyData, contentLength);
const payloadSha256 = putResult.sha256 || "";

Expand Down
Loading
Loading