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
5 changes: 5 additions & 0 deletions .changeset/clever-sandboxes-label.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@cloudflare/sandbox': patch
---

Add `labels` to `SandboxOptions` so `getSandbox()` can attach Cloudflare Container labels for analytics and observability. Labels are applied on container start; updates while running apply on the next start.
20 changes: 20 additions & 0 deletions packages/sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@ export default {
};
```

## Sandbox options

Pass options as the third argument to `getSandbox()` to configure sandbox
lifetime and container startup metadata:

```ts
const sandbox = getSandbox(env.Sandbox, 'tenant-workspace', {
sleepAfter: '30m',
labels: {
tenantId: 'tenant_123',
workload: 'code-workspace'
}
});
```

Container labels are attached to the underlying Cloudflare Container for
analytics and observability. Labels are applied when the container starts; if
labels are changed while a container is already running, the new labels apply
the next time the container starts.

## Quick tunnels

`sandbox.tunnels.get(port)` exposes a service running inside the
Expand Down
69 changes: 68 additions & 1 deletion packages/sandbox/src/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ type SandboxConfiguration = {
keepAlive?: boolean;
containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
transport?: SandboxTransport;
labels?: NonNullable<SandboxOptions['labels']>;
};

type CachedSandboxConfiguration = {
Expand All @@ -226,6 +227,7 @@ type CachedSandboxConfiguration = {
keepAlive?: boolean;
containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
transport?: SandboxTransport;
labels?: NonNullable<SandboxOptions['labels']>;
};

type EgressContainerState = DurableObjectState<{}> & {
Expand Down Expand Up @@ -347,6 +349,7 @@ type ConfigurableSandboxStub = {
timeouts: NonNullable<SandboxOptions['containerTimeouts']>
) => Promise<void>;
setTransport?: (transport: SandboxTransport) => Promise<void>;
setLabels?: (labels: Record<string, string>) => Promise<void>;
};

type SandboxProxyStub = ConfigurableSandboxStub & {
Expand Down Expand Up @@ -504,6 +507,28 @@ function sameContainerTimeouts(
);
}

function sameLabels(
left?: Record<string, string>,
right?: Record<string, string>
): boolean {
if (left === right) return true;
if (!left || !right) return false;

const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) return false;

for (const [key, value] of leftEntries) {
if (right[key] !== value) return false;
}

return true;
}

function cloneLabels(labels: Record<string, string>): Record<string, string> {
return { ...labels };
}

function buildSandboxConfiguration(
effectiveId: string,
options: SandboxOptions | undefined,
Expand Down Expand Up @@ -549,6 +574,13 @@ function buildSandboxConfiguration(
configuration.transport = options.transport;
}

if (
options?.labels !== undefined &&
!sameLabels(cached?.labels, options.labels)
) {
configuration.labels = cloneLabels(options.labels);
}

return configuration;
}

Expand All @@ -558,7 +590,8 @@ function hasSandboxConfiguration(configuration: SandboxConfiguration): boolean {
configuration.sleepAfter !== undefined ||
configuration.keepAlive !== undefined ||
configuration.containerTimeouts !== undefined ||
configuration.transport !== undefined
configuration.transport !== undefined ||
configuration.labels !== undefined
);
}

Expand All @@ -583,6 +616,9 @@ function mergeSandboxConfiguration(
}),
...(configuration.transport !== undefined && {
transport: configuration.transport
}),
...(configuration.labels !== undefined && {
labels: cloneLabels(configuration.labels)
})
};
}
Expand Down Expand Up @@ -631,6 +667,12 @@ function applySandboxConfiguration(
);
}

if (configuration.labels !== undefined) {
operations.push(
stub.setLabels?.(configuration.labels) ?? Promise.resolve()
);
}

return Promise.all(operations).then(() => undefined);
}

Expand Down Expand Up @@ -1368,6 +1410,12 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
this.hasStoredTransport = true;
}

const storedLabels =
await this.ctx.storage.get<Record<string, string>>('labels');
if (storedLabels !== undefined && storedLabels !== null) {
this.labels = cloneLabels(storedLabels);
}

if (this.interceptHttps) {
this.envVars = { ...this.envVars, SANDBOX_INTERCEPT_HTTPS: '1' };
}
Expand Down Expand Up @@ -1418,6 +1466,10 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
if (configuration.transport !== undefined) {
await this.setTransport(configuration.transport);
}

if (configuration.labels !== undefined) {
await this.setLabels(configuration.labels);
}
}

// RPC method to set the sleep timeout. Idempotent: re-applying the same
Expand Down Expand Up @@ -1572,6 +1624,21 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
this.logger.debug('Transport updated', { transport });
}

async setLabels(labels: Record<string, string>): Promise<void> {
const nextLabels = cloneLabels(labels);

if (sameLabels(this.labels, nextLabels)) return;

await this.ctx.storage.put('labels', nextLabels);
this.labels = nextLabels;

if (this.ctx.container?.running === true) {
this.logger.warn(
'Container labels updated while container is running; new labels apply on the next container start'
);
}
}

private validateTimeout(
value: number,
name: string,
Expand Down
109 changes: 108 additions & 1 deletion packages/sandbox/tests/get-sandbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ describe('getSandbox', () => {
setSleepAfter: vi.fn((value: string | number) => {
mockStub.sleepAfter = value;
}),
setKeepAlive: vi.fn()
setKeepAlive: vi.fn(),
setLabels: vi.fn()
};

// Mock getContainer to return our stub
Expand Down Expand Up @@ -333,6 +334,112 @@ describe('getSandbox', () => {
});
});

it('should apply labels option', () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
labels: {
tenantId: 'tenant_123',
workload: 'code-workspace'
}
});

expect(mockStub.configure).toHaveBeenCalledWith({
sandboxName: {
name: 'test-sandbox',
normalizeId: undefined
},
labels: {
tenantId: 'tenant_123',
workload: 'code-workspace'
}
});
});

it('should apply labels alongside other options', () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
sleepAfter: '5m',
keepAlive: true,
transport: 'websocket',
labels: { workload: 'code-workspace' }
});

expect(mockStub.configure).toHaveBeenCalledWith({
sandboxName: {
name: 'test-sandbox',
normalizeId: undefined
},
sleepAfter: '5m',
keepAlive: true,
transport: 'websocket',
labels: { workload: 'code-workspace' }
});
});

it('should skip repeated labels configuration for the same sandbox', async () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_123' }
});
await Promise.resolve();

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_123' }
});

expect(mockStub.configure).toHaveBeenCalledTimes(1);
});

it('should treat labels with the same key-values as identical regardless of insertion order', async () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_123', workload: 'code-workspace' }
});
await Promise.resolve();

getSandbox(mockNamespace, 'test-sandbox', {
labels: { workload: 'code-workspace', tenantId: 'tenant_123' }
});

expect(mockStub.configure).toHaveBeenCalledTimes(1);
});

it('should reconfigure when labels change', async () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_123' }
});
await Promise.resolve();

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_456' }
});

expect(mockStub.configure).toHaveBeenCalledTimes(2);
expect(mockStub.configure).toHaveBeenNthCalledWith(2, {
labels: { tenantId: 'tenant_456' }
});
});

it('should allow empty labels to clear configured labels for future starts', async () => {
const mockNamespace = {} as any;

getSandbox(mockNamespace, 'test-sandbox', {
labels: { tenantId: 'tenant_123' }
});
await Promise.resolve();

getSandbox(mockNamespace, 'test-sandbox', { labels: {} });

expect(mockStub.configure).toHaveBeenCalledTimes(2);
expect(mockStub.configure).toHaveBeenNthCalledWith(2, { labels: {} });
});

describe('proxy method routing', () => {
it('should preserve this binding for fetch()', async () => {
// fetch() is a native DurableObjectStub method that requires correct
Expand Down
Loading
Loading