Appearance
Request Lifecycle in MARS Engine
Understand how MARS Engine processes every API and WebSocket call-from start to finish.
Overview
Each request in MARS Engine-whether HTTP or WebSocket-runs inside a secure, isolated execution context that includes:
- A database transaction
- A fresh set of input parameters
- A response buffer
- Scoped helpers and global utilities
This ensures safety, predictability, and full control over data flow from input to output.
Lifecycle Stages
text
Request received
↓
Open transaction
↓
Run script
↓
Buffer output
↓
Auto commit (or rollback on error)
↓
Send response1. Input: param(), cookie(), session()
MARS Engine provides unified input handling:
js
const userId = param('user_id');
const token = cookie('auth_token');
const role = session('user_role');param()supports query, body, and file fieldssession()autoloads bysid(from query, body, or header)- Input helpers are available in both API and WebSocket scripts
2. Headers: header(), response.status()
Control response headers and status before writing data:
js
header('X-Custom-Header', 'MARS');
response.status(201); // CreatedSet these early-once write() is called, headers are locked in.
3. Core logic & helpers
Use any combination of MARS Engine built-ins:
js
const row = db.query('SELECT * FROM users WHERE id = ?', userId)[0];
const now = new DateTime().toString();
write("data", { row, now})Available helpers: db, fs, net, mail, fcm, dns, sha, base64, sanitize, DateTime, etc.
4. Output: write()
Write response fields (JSON or file stream):
js
write('user', row);
write('fetchedAt', now);- Keys must be unique-no duplicate keys allowed
- You may
write(row.file_content)to stream binary
5. Exiting the script: exit(), errors
Exit options:
exit()if you need to force stop (disallowed intryblocks)- Throwing an error triggers automatic rollback
Example:
js
if (users.length===0) {
response.status(404);
write('error', 'User not found');
exit();
}6. Transaction commit/rollback
By default:
- If the script finishes without errors → MARS commits
- If it throws or exits abnormally → MARS rolls back
You can commit early:
js
db.commit();
write('step', 'done'); // Continue with additional logicOr cancel manually:
js
db.rollback();
write('status', 'cancelled');In WebSocket scripts
Lifecycle stages are similar, but:
- No HTTP headers
- Use
onOpen,onMessage,onClose - Still benefits from
param(),session(),write(),db.query()
Example:
js
// Websocket onMessage method
const msg = param('msg', 'ping');
write('echo', msg);Summary
| Stage | What to use |
|---|---|
| Input | param(), cookie(), session() |
| Logic | Any built-in or custom logic |
| Output | write(), header(), response.status() |
| Control | exit(), error handling |
| DB safety | Automatic transaction commit/rollback |
Understanding the request lifecycle helps you build safer, faster, and more maintainable APIs in MARS Engine.