Skip to content
Open
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
1 change: 1 addition & 0 deletions backend/sandbox/controller/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { sandboxLifecycleRouter } from './sandboxLifecycleController';
169 changes: 169 additions & 0 deletions backend/sandbox/controller/sandboxLifecycleController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { Request, Response, Router } from 'express';
import { v4 as uuidv4 } from 'uuid';
import {
containerManager,
MaxSandboxesError,
TtlExtensionLimitError,
} from '../../../sandbox/orchestrator/containerManager';
import { generateStellarKeypair } from '../utils/stellarUtils';

const router = Router();

export interface ProvisionRequest {
developerId: string;
}

export interface ExtendTtlRequest {
sandboxId: string;
}

/**
* POST /api/v1/sandbox/provision
* Provision a new ephemeral sandbox instance
*/
router.post('/provision', async (req: Request, res: Response) => {
try {
const { developerId } = req.body as ProvisionRequest;

if (!developerId) {
return res.status(400).json({ error: 'developerId is required' });
}

const activeCount = containerManager.getActiveCount();
if (activeCount >= 3) {
const waitTime = containerManager.estimateWaitTime();
return res.status(429).json({
error: 'Maximum concurrent sandboxes (3) reached',
estimatedWait: waitTime,
activeSandboxCount: activeCount,
maxConcurrent: 3,
});
}

const sandboxId = `sbx_${uuidv4().slice(0, 8)}`;
const keypair = generateStellarKeypair();
const dbPassword = uuidv4().slice(0, 16);

const status = await containerManager.provision({
sandboxId,
developerId,
dbPassword,
dbHostPort: 0,
apiHostPort: 0,
stellarAccount: keypair.publicKey,
});

return res.status(201).json({
sandboxId,
status: status.status,
createdAt: status.createdAt,
expiresAt: status.expiresAt,
stellarAccount: keypair.publicKey,
stellarSecret: keypair.secretKey,
endpoints: {
api: `https://sandbox-${sandboxId}.api.subtrackr.io`,
horizon: 'https://horizon-testnet.stellar.org',
},
limits: {
ram: '512MB',
cpu: 1,
disk: '2GB',
ttl: '1 hour',
maxExtensions: 1,
},
});
} catch (err) {
if (err instanceof MaxSandboxesError) {
return res.status(429).json({
error: err.message,
estimatedWait: err.estimatedWait,
maxConcurrent: err.maxConcurrent,
});
}
console.error('Provision failed:', err);
return res.status(500).json({ error: 'Failed to provision sandbox' });
}
});

/**
* DELETE /api/v1/sandbox/:sandboxId
* Tear down a sandbox instance
*/
router.delete('/:sandboxId', async (req: Request, res: Response) => {
try {
const { sandboxId } = req.params;
await containerManager.teardown(sandboxId);
return res.json({ message: `Sandbox ${sandboxId} torn down successfully` });
} catch (err) {
console.error('Teardown failed:', err);
return res.status(500).json({ error: 'Failed to tear down sandbox' });
}
});

/**
* POST /api/v1/sandbox/extend-ttl
* Extend sandbox TTL by 2 hours (one-time extension, max 4h total)
*/
router.post('/extend-ttl', async (req: Request, res: Response) => {
try {
const { sandboxId } = req.body as ExtendTtlRequest;

if (!sandboxId) {
return res.status(400).json({ error: 'sandboxId is required' });
}

const extended = containerManager.extendTtl(sandboxId);
if (!extended) {
return res.status(404).json({ error: 'Sandbox not found' });
}

const status = containerManager.getStatus(sandboxId);
return res.json({
message: `Sandbox ${sandboxId} TTL extended by 2 hours`,
newExpiry: status?.expiresAt,
});
} catch (err) {
if (err instanceof TtlExtensionLimitError) {
return res.status(400).json({ error: err.message });
}
console.error('Extend TTL failed:', err);
return res.status(500).json({ error: 'Failed to extend sandbox TTL' });
}
});

/**
* GET /api/v1/sandbox/:sandboxId
* Get sandbox status
*/
router.get('/:sandboxId', (req: Request, res: Response) => {
const { sandboxId } = req.params;
const status = containerManager.getStatus(sandboxId);

if (!status) {
return res.status(404).json({ error: 'Sandbox not found' });
}

return res.json(status);
});

/**
* GET /api/v1/sandbox/health/:sandboxId
* Health check - updates last activity timestamp
*/
router.post('/:sandboxId/touch', (req: Request, res: Response) => {
const { sandboxId } = req.params;
containerManager.touchActivity(sandboxId);
return res.json({ touched: true });
});

/**
* POST /api/v1/sandbox/:sandboxId/extend-idle
* User confirms they want to keep the sandbox after idle warning
*/
router.post('/:sandboxId/extend-idle', (req: Request, res: Response) => {
const { sandboxId } = req.params;
containerManager.touchActivity(sandboxId);
return res.json({ message: 'Idle timer reset', sandboxId });
});

export { router as sandboxLifecycleRouter };
17 changes: 17 additions & 0 deletions backend/sandbox/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@subtrackr/backend-sandbox",
"version": "1.0.0",
"private": true,
"description": "Sandbox lifecycle REST API controller",
"main": "controller/index.ts",
"dependencies": {
"@subtrackr/sandbox-orchestrator": "1.0.0",
"@stellar/stellar-sdk": "^12.0.0",
"express": "^4.18.0",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/express": "^4.17.0",
"@types/uuid": "^9.0.0"
}
}
23 changes: 23 additions & 0 deletions backend/sandbox/utils/stellarUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Keypair } from '@stellar/stellar-sdk';

export interface StellarKeypair {
publicKey: string;
secretKey: string;
}

export function generateStellarKeypair(): StellarKeypair {
const kp = Keypair.random();
return {
publicKey: kp.publicKey(),
secretKey: kp.secret(),
};
}

export function isValidStellarPublicKey(key: string): boolean {
try {
Keypair.fromPublicKey(key);
return true;
} catch {
return false;
}
}
Loading