Skip to content

Commit dd725b8

Browse files
agents-git-bot[bot]whoiskatrin
authored andcommitted
Add process readiness methods to Sandbox documentation (#26915)
Co-authored-by: katereznykova <[email protected]>
1 parent 268564b commit dd725b8

File tree

2 files changed

+138
-17
lines changed

2 files changed

+138
-17
lines changed

src/content/docs/sandbox/api/commands.mdx

Lines changed: 105 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ for await (const event of parseSSEStream<ExecEvent>(stream)) {
8787
Start a long-running background process.
8888

8989
```ts
90-
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<ProcessInfo>
90+
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<Process>
9191
```
9292

9393
**Parameters**:
@@ -96,7 +96,16 @@ const process = await sandbox.startProcess(command: string, options?: ProcessOpt
9696
- `cwd` - Working directory
9797
- `env` - Environment variables
9898

99-
**Returns**: `Promise<ProcessInfo>` with `id`, `pid`, `command`, `status`
99+
**Returns**: `Promise<Process>` object with:
100+
- `id` - Unique process identifier
101+
- `pid` - System process ID
102+
- `command` - The command being executed
103+
- `status` - Current status (`'running'`, `'exited'`, etc.)
104+
- `kill()` - Stop the process
105+
- `getStatus()` - Get current status
106+
- `getLogs()` - Get accumulated logs
107+
- `waitForPort()` - Wait for process to listen on a port
108+
- `waitForLog()` - Wait for pattern in process output
100109

101110
<TypeScriptExample>
102111
```
@@ -213,6 +222,100 @@ console.log('Server logs:', logs);
213222
```
214223
</TypeScriptExample>
215224

225+
## Process readiness methods
226+
227+
The `Process` object returned by `startProcess()` includes methods to wait for the process to be ready before proceeding.
228+
229+
### `process.waitForPort()`
230+
231+
Wait for a process to listen on a port.
232+
233+
```ts
234+
await process.waitForPort(port: number, options?: WaitForPortOptions): Promise<void>
235+
```
236+
237+
**Parameters**:
238+
- `port` - The port number to check
239+
- `options` (optional):
240+
- `mode` - Check mode: `'http'` (default) or `'tcp'`
241+
- `timeout` - Maximum wait time in milliseconds
242+
- `interval` - Check interval in milliseconds (default: `100`)
243+
- `path` - HTTP path to check (default: `'/'`, HTTP mode only)
244+
- `status` - Expected HTTP status range (default: `{ min: 200, max: 399 }`, HTTP mode only)
245+
246+
**HTTP mode** (default) makes an HTTP GET request and checks the response status:
247+
248+
<TypeScriptExample>
249+
```
250+
const server = await sandbox.startProcess('node server.js');
251+
252+
// Wait for server to be ready (HTTP mode)
253+
await server.waitForPort(3000);
254+
255+
// Check specific endpoint and status
256+
await server.waitForPort(8080, {
257+
path: '/health',
258+
status: { min: 200, max: 299 },
259+
timeout: 30000
260+
});
261+
```
262+
</TypeScriptExample>
263+
264+
**TCP mode** checks if the port accepts connections:
265+
266+
<TypeScriptExample>
267+
```
268+
const db = await sandbox.startProcess('redis-server');
269+
270+
// Wait for database to accept connections
271+
await db.waitForPort(6379, {
272+
mode: 'tcp',
273+
timeout: 10000
274+
});
275+
```
276+
</TypeScriptExample>
277+
278+
**Throws**:
279+
- `ProcessReadyTimeoutError` - If port does not become ready within timeout
280+
- `ProcessExitedBeforeReadyError` - If process exits before becoming ready
281+
282+
### `process.waitForLog()`
283+
284+
Wait for a pattern to appear in process output.
285+
286+
```ts
287+
const result = await process.waitForLog(pattern: string | RegExp, timeout?: number): Promise<WaitForLogResult>
288+
```
289+
290+
**Parameters**:
291+
- `pattern` - String or RegExp to match in stdout/stderr
292+
- `timeout` - Maximum wait time in milliseconds (optional)
293+
294+
**Returns**: `Promise<WaitForLogResult>` with:
295+
- `line` - The matching line of output
296+
- `matches` - Array of capture groups (for RegExp patterns)
297+
298+
<TypeScriptExample>
299+
```
300+
const server = await sandbox.startProcess('node server.js');
301+
302+
// Wait for string pattern
303+
const result = await server.waitForLog('Server listening');
304+
console.log('Ready:', result.line);
305+
306+
// Wait for RegExp with capture groups
307+
const result = await server.waitForLog(/Server listening on port (\d+)/);
308+
console.log('Port:', result.matches[1]); // Extracted port number
309+
310+
// With timeout
311+
await server.waitForLog('Ready', 30000);
312+
```
313+
</TypeScriptExample>
314+
315+
**Throws**:
316+
- `ProcessReadyTimeoutError` - If pattern is not found within timeout
317+
- `ProcessExitedBeforeReadyError` - If process exits before pattern appears
318+
216319
## Related resources
217320

218321
- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running processes

src/content/docs/sandbox/guides/background-processes.mdx

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,36 @@ const isRunning = processes.some(p => p.id === processId && p.status === 'runnin
8383
```
8484
</TypeScriptExample>
8585

86+
## Wait for process readiness
87+
88+
Wait for a process to be ready before proceeding:
89+
90+
<TypeScriptExample>
91+
```
92+
const server = await sandbox.startProcess('node server.js');
93+
94+
// Wait for server to respond on port 3000
95+
await server.waitForPort(3000);
96+
97+
console.log('Server is ready');
98+
```
99+
</TypeScriptExample>
100+
101+
Or wait for specific log patterns:
102+
103+
<TypeScriptExample>
104+
```
105+
const server = await sandbox.startProcess('node server.js');
106+
107+
// Wait for log message
108+
const result = await server.waitForLog('Server listening');
109+
console.log('Server is ready:', result.line);
110+
```
111+
</TypeScriptExample>
112+
86113
## Monitor process logs
87114

88-
Stream logs in real-time to detect when a service is ready:
115+
Stream logs in real-time:
89116

90117
<TypeScriptExample>
91118
```
@@ -98,11 +125,6 @@ const logStream = await sandbox.streamProcessLogs(server.id);
98125
99126
for await (const log of parseSSEStream<LogEvent>(logStream)) {
100127
console.log(log.data);
101-
102-
if (log.data.includes('Server listening')) {
103-
console.log('Server is ready!');
104-
break;
105-
}
106128
}
107129
```
108130
</TypeScriptExample>
@@ -137,24 +159,20 @@ Start services in sequence, waiting for dependencies:
137159

138160
<TypeScriptExample>
139161
```
140-
import { parseSSEStream, type LogEvent } from '@cloudflare/sandbox';
141-
142162
// Start database first
143163
const db = await sandbox.startProcess('redis-server');
144164
145165
// Wait for database to be ready
146-
const dbLogs = await sandbox.streamProcessLogs(db.id);
147-
for await (const log of parseSSEStream<LogEvent>(dbLogs)) {
148-
if (log.data.includes('Ready to accept connections')) {
149-
break;
150-
}
151-
}
166+
await db.waitForPort(6379, { mode: 'tcp' });
152167
153168
// Now start API server (depends on database)
154169
const api = await sandbox.startProcess('node api-server.js', {
155170
env: { DATABASE_URL: 'redis://localhost:6379' }
156171
});
157172
173+
// Wait for API to be ready
174+
await api.waitForPort(8080, { path: '/health' });
175+
158176
console.log('All services running');
159177
```
160178
</TypeScriptExample>
@@ -207,7 +225,7 @@ When using `keepAlive: true`, containers will not automatically timeout. You **m
207225

208226
## Best practices
209227

210-
- **Wait for readiness** - Stream logs to detect when services are ready
228+
- **Wait for readiness** - Use `waitForPort()` or `waitForLog()` to detect when services are ready
211229
- **Clean up** - Always stop processes when done
212230
- **Handle failures** - Monitor logs for errors and restart if needed
213231
- **Use try/finally** - Ensure cleanup happens even on errors

0 commit comments

Comments
 (0)