Skip to content
Draft
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
4 changes: 4 additions & 0 deletions packages/deploy-cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
".": {
"types": "./dist/index.d.mts",
"import": "./dist/index.mjs"
},
"./flagship": {
"types": "./dist/flagship.d.mts",
"import": "./dist/flagship.mjs"
}
},
"publishConfig": {
Expand Down
86 changes: 86 additions & 0 deletions packages/deploy-cloudflare/src/flagship.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { isFlagshipFlagKey, isRecord } from '@void/deploy-core';

type FlagDefinition = Readonly<{
key: string;
type: string;
default_variation: string;
variations: Readonly<Record<string, unknown>>;
enabled: boolean;
rules: ReadonlyArray<unknown>;
description?: string;
metadata?: Readonly<Record<string, boolean | string | number>>;
}>;

type FlagRequest = (path: string, init?: RequestInit) => Promise<FlagDefinition>;

function booleanDefault(flag: FlagDefinition, key: string): boolean {
if (flag?.key === key && flag.type === 'boolean' && isRecord(flag.variations)) {
const value = flag.variations[flag.default_variation];
if (typeof value === 'boolean') {
return value;
}
}
throw new Error(`Flagship flag "${key}" must have a Boolean default variation.`);
}

function verifyDefault(flag: FlagDefinition, key: string, value: boolean): void {
if (booleanDefault(flag, key) !== value) {
throw new Error(`Cloudflare returned a different default for Flagship flag "${key}".`);
}
}

export async function setFlagshipBoolean(
request: FlagRequest,
key: string,
value: boolean,
): Promise<void> {
if (!isFlagshipFlagKey(key)) {
throw new Error('Invalid Flagship flag key.');
}
const path = `/flags/${key}`;
const flag = await request(path).catch(async (error: unknown) => {
if (!isRecord(error) || error.status !== 404) {
throw error;
}
try {
const created = await request('/flags', {
method: 'POST',
body: JSON.stringify({
key,
enabled: true,
rules: [],
variations: { on: true, off: false },
default_variation: value ? 'on' : 'off',
}),
});
verifyDefault(created, key, value);
return created;
} catch (createError) {
if (!isRecord(createError) || createError.status !== 409) {
throw createError;
}
return request(path);
}
});

if (booleanDefault(flag, key) === value) {
return;
}
const variation = Object.keys(flag.variations).find((name) => flag.variations[name] === value);
if (variation === undefined) {
throw new Error(`Flagship flag "${key}" has no variation for ${value}.`);
}
const updated = await request(path, {
method: 'PUT',
body: JSON.stringify({
key: flag.key,
enabled: flag.enabled,
rules: flag.rules,
variations: flag.variations,
default_variation: variation,
description: flag.description,
metadata: flag.metadata,
}),
});
verifyDefault(updated, key, value);
}
72 changes: 72 additions & 0 deletions packages/deploy-cloudflare/test/unit/flagship.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { expect, it, vi } from 'vite-plus/test';
import { setFlagshipBoolean } from '../../src/flagship.ts';

const flag = {
key: 'probe',
type: 'boolean',
default_variation: 'off',
variations: { canary: true, off: false },
enabled: false,
rules: [{ priority: 1, conditions: [], serve_variation: 'off' }],
description: 'Probe targeting rule',
metadata: { example: true },
updated_at: '2026-12-01T00:00:00Z',
};

function providerError(status: number) {
return Object.assign(new Error(`Provider ${status}`), { status });
}

it('Flagship leaves a matching Boolean default and its targeting rules alone', async () => {
const request = vi.fn().mockResolvedValue(flag);
await setFlagshipBoolean(request, 'probe', false);
expect(request.mock.calls).toEqual([['/flags/probe']]);
});

it('Flagship rereads after a concurrent create and replaces the flag with a new default', async () => {
const request = vi
.fn()
.mockRejectedValueOnce(providerError(404))
.mockRejectedValueOnce(providerError(409))
.mockResolvedValueOnce(flag)
.mockResolvedValueOnce({ ...flag, default_variation: 'canary' });
await setFlagshipBoolean(request, 'probe', true);
expect(request.mock.calls).toEqual([
['/flags/probe'],
['/flags', { method: 'POST', body: expect.any(String) }],
['/flags/probe'],
['/flags/probe', { method: 'PUT', body: expect.any(String) }],
]);
expect(JSON.parse(String(request.mock.calls[3]?.[1]?.body))).toEqual({
key: 'probe',
enabled: false,
rules: [{ priority: 1, conditions: [], serve_variation: 'off' }],
variations: { canary: true, off: false },
default_variation: 'canary',
description: 'Probe targeting rule',
metadata: { example: true },
});
});

it('Flagship rejects an incompatible flag before any write', async () => {
const request = vi.fn().mockResolvedValue({ ...flag, type: 'string' });
await expect(setFlagshipBoolean(request, 'probe', true)).rejects.toThrow('Boolean default');
expect(request).toHaveBeenCalledOnce();
});

it('Flagship fails from the update response even when a reread would return the desired value', async () => {
const request = vi
.fn()
.mockResolvedValueOnce(flag)
.mockResolvedValueOnce(flag)
.mockResolvedValue({ ...flag, default_variation: 'canary' });
await expect(setFlagshipBoolean(request, 'probe', true)).rejects.toThrow('different default');
expect(request).toHaveBeenCalledTimes(2);
});

it('Flagship preserves provider denial before attempting a create', async () => {
const denied = providerError(403);
const request = vi.fn().mockRejectedValue(denied);
await expect(setFlagshipBoolean(request, 'probe', false)).rejects.toBe(denied);
expect(request).toHaveBeenCalledOnce();
});
10 changes: 10 additions & 0 deletions packages/deploy-cloudflare/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from 'vite-plus';

export default defineConfig({
pack: {
entry: ['src/index.ts', 'src/flagship.ts'],
format: 'esm',
dts: true,
clean: true,
},
});
21 changes: 21 additions & 0 deletions packages/deploy-core/src/flagship.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { isRecord } from './is-record.ts';
import { FLAGSHIP_MANIFEST_VERSION } from './manifest-version.ts';

export const FLAGSHIP_BINDING = 'FLAGS';
export const FLAGSHIP_FALLBACK_BINDING = '__VOID_FLAGS_FALLBACK';

export function isFlagshipWorkerManifest(manifest: unknown): boolean {
return (
isRecord(manifest) &&
manifest.version === FLAGSHIP_MANIFEST_VERSION &&
manifest.type !== 'static' &&
manifest.type !== 'spa' &&
manifest.static === undefined &&
isRecord(manifest.bindings) &&
manifest.bindings.flagship === true
);
}

export function isFlagshipFlagKey(key: unknown): key is string {
return typeof key === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(key);
}
10 changes: 10 additions & 0 deletions packages/deploy-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,19 @@ export {
export {
BROWSER_MANIFEST_VERSION,
DURABLE_OBJECTS_MANIFEST_VERSION,
FLAGSHIP_MANIFEST_VERSION,
STORAGE_MANIFEST_VERSION,
WORKFLOWS_MANIFEST_VERSION,
SUPPORTED_MANIFEST_VERSIONS,
} from './manifest-version.ts';

export {
FLAGSHIP_BINDING,
FLAGSHIP_FALLBACK_BINDING,
isFlagshipFlagKey,
isFlagshipWorkerManifest,
} from './flagship.ts';

export type MigrationMeta = {
name: string;
destructive: boolean;
Expand Down Expand Up @@ -287,6 +295,8 @@ export type DeployManifest = {
hyperdrive?: Array<string>;
/** Browser Run binding name. Requires manifest version 6 or later. */
browser?: string;
/** Provisions the FLAGS binding on a manifest v8 Worker. */
flagship?: true;
};
migrations?: {
dialect: 'sqlite' | 'postgresql' | 'mysql';
Expand Down
5 changes: 4 additions & 1 deletion packages/deploy-core/src/manifest-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* the manifest and silently ignore the field. The new version makes that
* platform reject the deployment instead.
*/
export const SUPPORTED_MANIFEST_VERSIONS: ReadonlyArray<number> = [3, 4, 5, 6, 7];
export const SUPPORTED_MANIFEST_VERSIONS: ReadonlyArray<number> = [3, 4, 5, 6, 7, 8];

/** The first version that can declare custom Durable Objects. */
export const DURABLE_OBJECTS_MANIFEST_VERSION = 4;
Expand All @@ -21,6 +21,9 @@ export const BROWSER_MANIFEST_VERSION = 6;
/** The first version that provisions application Workflows. */
export const WORKFLOWS_MANIFEST_VERSION = 7;

/** The first version that provisions a Flagship binding. */
export const FLAGSHIP_MANIFEST_VERSION = 8;

export function isSupportedManifestVersion(version: unknown): version is number {
return typeof version === 'number' && SUPPORTED_MANIFEST_VERSIONS.includes(version);
}
Expand Down
8 changes: 7 additions & 1 deletion packages/deploy-core/src/resource-plan.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { FLAGSHIP_BINDING, isFlagshipWorkerManifest } from './flagship.ts';
import type { DeployManifest, QueueMeta } from './index.ts';

export type DeployResource =
| { type: 'd1'; bindingName: string; readReplication?: boolean }
| { type: 'kv'; bindingName: string }
| { type: 'r2'; bindingName: string }
| { type: 'queue'; bindingName: string; resourceName: string; consumer: QueueMeta }
| { type: 'hyperdrive'; bindingName: string };
| { type: 'hyperdrive'; bindingName: string }
| { type: 'flagship'; bindingName: typeof FLAGSHIP_BINDING };

export type DeployResourcePlan = {
resources: Array<DeployResource>;
Expand Down Expand Up @@ -54,6 +56,10 @@ export function createDeployResourcePlan(manifest: DeployManifest): DeployResour
resources.push({ type: 'hyperdrive', bindingName });
}

if (isFlagshipWorkerManifest(manifest)) {
resources.push({ type: 'flagship', bindingName: FLAGSHIP_BINDING });
}

return {
resources,
runtime: {
Expand Down
40 changes: 40 additions & 0 deletions packages/deploy-core/src/validate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import {
FLAGSHIP_BINDING,
FLAGSHIP_FALLBACK_BINDING,
isFlagshipWorkerManifest,
} from './flagship.ts';
import { isRecord } from './is-record.ts';
import {
BROWSER_MANIFEST_VERSION,
DURABLE_OBJECTS_MANIFEST_VERSION,
FLAGSHIP_MANIFEST_VERSION,
WORKFLOWS_MANIFEST_VERSION,
STORAGE_MANIFEST_VERSION,
isSupportedManifestVersion,
Expand Down Expand Up @@ -707,6 +713,40 @@ export function validateManifestShape(manifest: unknown): string | null {
classes.add(binding.className);
}
}
if (version === FLAGSHIP_MANIFEST_VERSION && bindings.flagship !== undefined) {
if (bindings.flagship !== true) {
return 'invalid manifest shape: bindings.flagship must be true';
}
if (!isFlagshipWorkerManifest(manifest)) {
return 'invalid manifest shape: Flagship requires a Worker deployment';
}
const names = otherBindingNames(manifest, bindings);
if (isRecord(manifest.sandbox)) {
names.add(manifest.sandbox.bindingName);
}
const durable = isRecord(manifest.durableObjects) ? manifest.durableObjects.bindings : [];
for (const entries of [durable, manifest.workflows]) {
for (const entry of Array.isArray(entries) ? entries : []) {
if (isRecord(entry)) {
names.add(entry.bindingName);
}
}
}
if (isRecord(manifest.websocket) && Array.isArray(manifest.websocket.classes)) {
const routes = Array.isArray(manifest.websocket.routes) ? manifest.websocket.routes : [];
const bound = new Set(routes.map((route) => (isRecord(route) ? route.className : undefined)));
for (const className of manifest.websocket.classes) {
if (!bound.has(className)) {
names.add(className);
}
}
}
for (const name of [FLAGSHIP_BINDING, FLAGSHIP_FALLBACK_BINDING]) {
if (names.has(name)) {
return `invalid manifest shape: ${name} is reserved for Flagship`;
}
}
}
return null;
}

Expand Down
1 change: 1 addition & 0 deletions packages/platform/scripts/build-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const workers = [
['dispatch', join(repositoryRoot, 'platform', 'packages', 'dispatch', 'src', 'index.ts')],
];
const sourceAliases = {
'@void/deploy-cloudflare/flagship': join(packageRoot, '..', 'deploy-cloudflare/src/flagship.ts'),
'@void/deploy-core': join(repositoryRoot, 'packages', 'deploy-core', 'src', 'index.ts'),
'@void/edge': join(repositoryRoot, 'packages', 'edge', 'src', 'index.ts'),
'@void/isr': join(repositoryRoot, 'packages', 'isr', 'src', 'index.ts'),
Expand Down
1 change: 1 addition & 0 deletions packages/platform/src/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ export function parsePlatformDiscoveryDocument(value: unknown): PlatformDiscover
managedBuilds: readCapability('managedBuilds'),
sandbox: readCapability('sandbox'),
securityAudits: readCapability('securityAudits'),
flagship: readCapability('flagship'),
};
const providers = document.authenticationProviders;
if (
Expand Down
9 changes: 6 additions & 3 deletions packages/platform/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type PlatformCapabilities = Readonly<{
* missing means `false`. `true` requires deployment schema version 7.
*/
securityAudits: boolean;
flagship?: boolean;
}>;

export type PlatformControlPlane = Readonly<{
Expand Down Expand Up @@ -133,12 +134,14 @@ const CORE_CAPABILITIES: PlatformCapabilities = {
managedBuilds: false,
sandbox: false,
securityAudits: false,
flagship: false,
};

/** Capabilities that older documents may omit; a missing value means `false`. */
const OPTIONAL_CAPABILITIES = new Set<string>(['securityAudits'] satisfies ReadonlyArray<
keyof PlatformCapabilities
>);
const OPTIONAL_CAPABILITIES = new Set<string>([
'securityAudits',
'flagship',
] satisfies ReadonlyArray<keyof PlatformCapabilities>);

/**
* Reads one capability from an untrusted record. An optional capability that
Expand Down
11 changes: 11 additions & 0 deletions packages/platform/test/unit/application.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ describe('platform application addressing', () => {
});
expect(document.schemaVersion).toBe(2);
expect(parsePlatformDiscoveryDocument(document)).toEqual(document);
const { flagship: _flagship, ...legacyCapabilities } = document.capabilities;
expect(
parsePlatformDiscoveryDocument({ ...document, capabilities: legacyCapabilities }).capabilities
.flagship,
).toBe(false);
expect(
parsePlatformDiscoveryDocument({
...document,
capabilities: { ...document.capabilities, flagship: true },
}).capabilities.flagship,
).toBe(true);
expect(() => parsePlatformDiscoveryDocument({ ...document, installationId: 'other' })).toThrow(
'installation identity',
);
Expand Down
Loading