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
4 changes: 4 additions & 0 deletions .claude/rules/06-api-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ app.use('*', async (c, next) => {

Throw `AppError` (from `@simple-agent-manager/worker-core`, re-exported by `middleware/error.ts`) in route handlers — the global `app.onError()` handler catches them.

Expected domain rejections from services also need the `AppError` contract. Preserve
exception names used by recovery callers, and test the real route with the production
`handleAppError` handler plus an unrelated-error control when changing classification.

## Hono Middleware Scoping (CRITICAL)

**NEVER use wildcard `use('/*', ...)` middleware on subrouters that share a base path with other subrouters using different auth models.** Hono's `app.route('/', subRouter)` merges routes — wildcard middleware from one subrouter leaks to ALL sibling subrouters mounted at the same path.
Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/api-reference/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ The old `POST /api/sam/chat` inference path is closed: enabled clients receive `

## Node Management

- `POST /api/nodes` — Create node
- `POST /api/nodes` — Create node (`201`). At the caller's per-person managed workspace-node limit in the selected pool, returns `409 CAPACITY_POOL_NODE_LIMIT` with guidance to delete an idle node or ask the pool owner to raise the limit in Infrastructure; no node is created or provisioning scheduled (`services/nodes.ts:createNodeRecord`, `routes/nodes.ts`).
- `GET /api/nodes` — List user's nodes
- `GET /api/nodes/:id` — Get node details
- `POST /api/nodes/:id/stop` — Stop node
Expand Down
10 changes: 8 additions & 2 deletions apps/api/src/services/nodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
type CapacityPlacementSnapshot,
type CredentialSource,
} from '@simple-agent-manager/shared';
import { AppError } from '@simple-agent-manager/worker-core';
import { drizzle } from 'drizzle-orm/d1';

import * as schema from '../db/schema';
Expand Down Expand Up @@ -74,9 +75,14 @@ export interface ProvisionedNode {
updatedAt: string;
}

export class CapacityPoolNodeLimitExceededError extends Error {
export class CapacityPoolNodeLimitExceededError extends AppError {
constructor() {
super('Capacity pool node limit reached');
super(
409,
'CAPACITY_POOL_NODE_LIMIT',
'Your compute pool has reached its node limit. Delete an idle node or ask the pool owner to raise the limit in Infrastructure.'
);
// TaskRunner uses this name to release its provisioning lease and wait for capacity.
this.name = 'CapacityPoolNodeLimitExceededError';
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,21 @@ import type {
TaskRunnerContext,
TaskRunnerState,
} from '../../../src/durable-objects/task-runner/types';
import { CapacityPoolNodeLimitExceededError } from '../../../src/services/nodes';

// Mock the dynamically-imported service modules. node-steps imports these via
// `await import(...)` inside handleNodeProvisioning, so the mocks apply to the
// dynamic import too.
const createNodeRecord = vi.fn();
const provisionNode = vi.fn();
vi.mock('../../../src/services/nodes', () => ({
createNodeRecord: (...args: unknown[]) => createNodeRecord(...args),
provisionNode: (...args: unknown[]) => provisionNode(...args),
}));
vi.mock('../../../src/services/nodes', async (importOriginal) => {
const original = await importOriginal<typeof import('../../../src/services/nodes')>();
return {
CapacityPoolNodeLimitExceededError: original.CapacityPoolNodeLimitExceededError,
createNodeRecord: (...args: unknown[]) => createNodeRecord(...args),
provisionNode: (...args: unknown[]) => provisionNode(...args),
};
});

const getRuntimeLimits = vi.fn(() => ({ nodeHeartbeatStaleSeconds: 180 }));
vi.mock('../../../src/services/limits', () => ({
Expand Down Expand Up @@ -362,9 +367,7 @@ describe('TaskRunner capacity exhaustion', () => {
});

it('does not call the provider when the atomic pool insert loses a cross-domain race', async () => {
const poolLimitError = new Error('Capacity pool node limit reached');
poolLimitError.name = 'CapacityPoolNodeLimitExceededError';
createNodeRecord.mockRejectedValueOnce(poolLimitError);
createNodeRecord.mockRejectedValueOnce(new CapacityPoolNodeLimitExceededError());
const { DATABASE } = createDbMock({
firstResolver: (sql) =>
sql.includes('capacity_pool_id = ?') && sql.includes('COUNT(*) AS count')
Expand All @@ -383,6 +386,51 @@ describe('TaskRunner capacity exhaustion', () => {
expect(provisionNode).not.toHaveBeenCalled();
});

it('releases the provisioning lease and waits after the named pool-limit error', async () => {
createNodeRecord.mockRejectedValueOnce(new CapacityPoolNodeLimitExceededError());
resolveCredentialSource.mockResolvedValue({
credentialSource: 'user',
providerName: 'vultr',
});
const { DATABASE, runCalls } = createDbMock({
firstResolver: (sql) => {
if (sql.includes('capacity_pool_id = ?') && sql.includes('COUNT(*) AS count')) {
return { count: 2 };
}
if (sql.includes('FROM vm_provisioning_leases')) {
return {
owner_task_id: 'task-1',
fencing_token: 1,
expires_at: new Date(Date.now() + 60_000).toISOString(),
};
}
return FALLTHROUGH;
},
});
const rc = createContext(DATABASE, { VM_ADMISSION_CONTROL_MODE: 'enforce' });
const state = createState({ capacityPoolSelection: capacityPoolSelection() });

await handleNodeProvisioning(state, rc);

expect(createNodeRecord).toHaveBeenCalledOnce();
expect(provisionNode).not.toHaveBeenCalled();
expect(rc.advanceToStep).not.toHaveBeenCalled();
expect(runCalls).toContainEqual({
sql: expect.stringContaining('DELETE FROM vm_provisioning_leases'),
args: [expect.any(String), 'task-1', 1],
});
expect(state.admissionScopeKey).toBeNull();
expect(state.admissionLeaseToken).toBeNull();
expect(rc.updateD1ExecutionStep).toHaveBeenCalledWith('task-1', 'waiting_for_node_capacity');
expect(rc.ctx.storage.setAlarm).toHaveBeenCalledWith(expect.any(Number));
expect(
runCalls.some(
(call) =>
call.sql.includes("SET state = 'waiting'") && call.args[0] === 'capacity_pool_node_limit'
)
).toBe(true);
});

it('does not provision through legacy fallback when the selected pool has no candidates', async () => {
const { DATABASE } = createDbMock({});
const rc = createContext(DATABASE);
Expand Down
178 changes: 178 additions & 0 deletions apps/api/tests/unit/routes/nodes-pool-node-limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import type { CapacityPlacementSnapshot } from '@simple-agent-manager/shared';
import Database from 'better-sqlite3';
import { Hono } from 'hono';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import * as schema from '../../../src/db/schema';
import type { Env } from '../../../src/env';
import { handleAppError } from '../../../src/middleware/app-error-handler';
import { AppError } from '../../../src/middleware/error';
import { nodesRoutes } from '../../../src/routes/nodes';
import { resolveCanonicalVmAllocationPlan } from '../../../src/services/canonical-vm-allocation';
import { scheduleDirectProvisioning } from '../../../src/services/direct-provisioning';
import { CapacityPoolNodeLimitExceededError, createNodeRecord } from '../../../src/services/nodes';
import { recordNodeRoutingMetric } from '../../../src/services/telemetry';
import { applySqliteMigration, createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1';

vi.mock('../../../src/middleware/auth', () => ({
getUserId: () => 'user-1',
requireAuth: () => async (_c: unknown, next: () => Promise<void>) => next(),
requireApproved: () => async (_c: unknown, next: () => Promise<void>) => next(),
}));

// Placement selection is upstream of the insert under test. Keep the real node
// service, ORM, shipped SQLite trigger and production error handler composed.
vi.mock('../../../src/services/canonical-vm-allocation', () => ({
resolveCanonicalVmAllocationPlan: vi.fn(),
}));
vi.mock('../../../src/services/direct-provisioning', () => ({
scheduleDirectProvisioning: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('../../../src/services/telemetry', () => ({ recordNodeRoutingMetric: vi.fn() }));

const snapshot: CapacityPlacementSnapshot = {
capacityPoolId: 'pool-1',
capacityPoolScope: 'user',
capacityPoolRevision: 1,
capacitySourceId: 'source-1',
capacityPoolCandidateId: 'candidate-1',
placementCredentialSource: 'user',
placementCredentialReference: 'credentials:credential-1',
placementCredentialVersion: 1,
capacityPoolProjectId: null,
workloadRole: 'workspace',
};

describe('POST /api/nodes pool node limit — real insert and production error handler', () => {
let sqlite: Database.Database;
let env: Env;
let app: Hono<{ Bindings: Env }>;

beforeEach(() => {
vi.clearAllMocks();
sqlite = new Database(':memory:');
createSchemaTables(sqlite, [schema.nodes, schema.capacityPools]);
// Reapply the shipped migration, including its default and atomic trigger.
sqlite.exec('ALTER TABLE capacity_pools DROP COLUMN max_nodes');
applySqliteMigration(
sqlite,
new URL('../../../src/db/migrations/0167_capacity_pool_max_nodes.sql', import.meta.url)
);
sqlite.exec("INSERT INTO capacity_pools (id, max_nodes) VALUES ('pool-1', 1)");
env = { DATABASE: createSqliteD1(sqlite), MAX_NODES_PER_USER: '10' } as Env;
vi.mocked(resolveCanonicalVmAllocationPlan).mockResolvedValue({
vmSize: 'small',
vmLocation: 'fsn1',
effectiveProvider: 'hetzner',
credentialAttributionUserId: 'user-1',
credentialAttributionProjectId: null,
credentialAttributionSource: 'user',
quotaCredentialSource: 'user',
capacityPlacementSnapshot: snapshot,
} as Awaited<ReturnType<typeof resolveCanonicalVmAllocationPlan>>);
app = new Hono<{ Bindings: Env }>();
app.onError(handleAppError);
app.route('/api/nodes', nodesRoutes);
});

afterEach(() => sqlite.close());

function postNode(): Promise<Response> {
return app.request(
'/api/nodes',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-node' }),
},
env
);
}

async function fillPool(): Promise<void> {
await createNodeRecord(env, {
userId: 'user-1',
name: 'existing-node',
vmSize: 'small',
vmLocation: 'fsn1',
heartbeatStaleAfterSeconds: 180,
capacityPlacementSnapshot: snapshot,
});
}

function nodeCount(): number {
return (sqlite.prepare('SELECT COUNT(*) AS count FROM nodes').get() as { count: number }).count;
}

it('returns actionable 409 JSON at max_nodes without scheduling provisioning or inserting a node', async () => {
await fillPool();

const response = await postNode();

expect(response.status).toBe(409);
expect(response.headers.get('Content-Type')).toContain('application/json');
expect(await response.json()).toEqual({
error: 'CAPACITY_POOL_NODE_LIMIT',
message:
'Your compute pool has reached its node limit. Delete an idle node or ask the pool owner to raise the limit in Infrastructure.',
});
expect(resolveCanonicalVmAllocationPlan).toHaveBeenCalledOnce();
expect(nodeCount()).toBe(1);
expect(scheduleDirectProvisioning).not.toHaveBeenCalled();
expect(recordNodeRoutingMetric).not.toHaveBeenCalled();
});

it('converts the real trigger error through the ORM cause chain to the named AppError', async () => {
await fillPool();
const error = await createNodeRecord(env, {
userId: 'user-1',
name: 'rejected',
vmSize: 'small',
vmLocation: 'fsn1',
heartbeatStaleAfterSeconds: 180,
capacityPlacementSnapshot: snapshot,
}).catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(CapacityPoolNodeLimitExceededError);
expect(error).toBeInstanceOf(AppError);
expect(error).toMatchObject({
name: 'CapacityPoolNodeLimitExceededError',
statusCode: 409,
error: 'CAPACITY_POOL_NODE_LIMIT',
});
expect(nodeCount()).toBe(1);
});

it('creates and schedules a node below max_nodes, then rejects the next request', async () => {
const response = await postNode();
expect(response.status).toBe(201);
const created = (await response.json()) as { id: string; status: string };
expect(created.status).toBe('creating');
expect(nodeCount()).toBe(1);
expect(scheduleDirectProvisioning).toHaveBeenCalledExactlyOnceWith(env, {
nodeId: created.id,
userId: 'user-1',
});

expect((await postNode()).status).toBe(409);
expect(nodeCount()).toBe(1);
expect(scheduleDirectProvisioning).toHaveBeenCalledOnce();
});

it('keeps unrelated insert failures as redacted 500 errors without provisioning', async () => {
sqlite.exec(`CREATE TRIGGER unrelated_insert_failure BEFORE INSERT ON nodes
BEGIN SELECT RAISE(ABORT, 'unrelated_database_failure'); END`);

const response = await postNode();

expect(response.status).toBe(500);
expect(await response.json()).toEqual({
error: 'INTERNAL_ERROR',
message: 'Internal server error',
requestId: expect.any(String),
});
expect(nodeCount()).toBe(0);
expect(scheduleDirectProvisioning).not.toHaveBeenCalled();
expect(recordNodeRoutingMetric).not.toHaveBeenCalled();
});
});
10 changes: 10 additions & 0 deletions apps/www/src/content/docs/docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,16 @@ Comment threads and replies accept an optional `mentions: [{ "userId": "..." }]`

## Nodes

### `POST /api/nodes`

Create a node for the authenticated user. Returns `201` when creation is scheduled.
If the caller has reached the selected compute pool's per-person limit for managed
workspace nodes, returns `409` with
`error: "CAPACITY_POOL_NODE_LIMIT"`. Delete an idle node or ask the pool owner to
raise the limit in Infrastructure, then retry. A rejected request does not create
a node or schedule provisioning (`apps/api/src/services/nodes.ts:createNodeRecord`,
`apps/api/src/routes/nodes.ts`, `apps/api/src/middleware/app-error-handler.ts:handleAppError`).

### `GET /api/nodes`

List all nodes for the authenticated user.
Expand Down
Loading
Loading