Cloud Functions
AuthNexus cloud functions allow you to run server-side Lua scripts that execute within authenticated user sessions. They provide a flexible extension mechanism for business logic without modifying the core server binary.
Overview
| Property | Detail |
|---|---|
| Language | Lua 5.4 |
| Sandbox | Restricted (no I/O, OS, debug, package system) |
| Default timeout | 1000ms per invocation |
| Uniqueness | app_id + name (one function per name per application) |
| Execution | Dedicated cloud_function_threads pool with backpressure |
| Delivery | Scripts managed in Control DB, pulled by nodes via Channel 1 |
Sandbox Environment
Cloud functions run in a hardened Lua 5.4 sandbox. The following standard libraries are removed:
| Library | Reason |
|---|---|
io | File system access |
os | Operating system interaction |
debug | Sandbox escape vector |
package / require | Module loading |
dofile / loadfile | File execution |
Available Standard Libraries
string-- string manipulationtable-- table operationsmath-- mathematical functionsutf8-- UTF-8 supportcoroutine-- coroutine primitives (within the sandbox)tonumber,tostring,type,select,pairs,ipairs,next,pcall,xpcall,error,assert
Injected Globals
The server injects context-specific globals into each function invocation:
| Global | Type | Description |
|---|---|---|
params | table | Key-value parameters passed by the SDK caller |
user_id | number | Authenticated user's ID |
app_id | number | Application ID from the session |
username | string | Authenticated username |
device_id | string | Client device identifier |
server_time | number | Server timestamp (unix milliseconds) |
Management
Creating a Cloud Function
POST /admin/v1/cloud-functions{
"app_id": 1,
"name": "calculate_discount",
"script": "local rate = tonumber(params.quantity) > 10 and 0.15 or 0.05\nreturn tostring(rate)",
"enabled": true
}Listing Functions
GET /admin/v1/cloud-functions?app_id=1Returns all cloud functions for the specified application, with pagination support.
Updating a Function
PUT /admin/v1/cloud-functions/:name?app_id=1{
"script": "-- updated logic\nlocal rate = 0.10\nreturn tostring(rate)",
"enabled": true
}Toggling Enable/Disable
PATCH /admin/v1/cloud-functions/:name/toggle?app_id=1Disabled functions return an error when invoked by the SDK.
Deleting a Function
DELETE /admin/v1/cloud-functions/:name?app_id=1Viewing a Function Detail
GET /admin/v1/cloud-functions/:name?app_id=1Execution Model
Thread Pool
Cloud functions execute on a dedicated cloud_function_threads pool, physically isolated from I/O, logic, DB, and crypto threads. This prevents a CPU-intensive or slow Lua script from blocking other server operations.
Backpressure
Concurrent execution is limited by cloud_function_max_in_flight, which scales with the thread count:
| Cores | CF Threads | Max In-Flight |
|---|---|---|
| 1--2 | 1 | 32 |
| 3--4 | 2 | 128 |
| 5--8 | 3 | 192 |
| 9+ | n/4 (max 16) | threads x 128 |
When the in-flight limit is reached, new invocations are queued. If the queue overflows, the server returns an error to the SDK.
Timeout
Each invocation has a default timeout of 1000ms. If the script exceeds this limit, execution is terminated and an error is returned. The timeout is enforced at the Lua VM level.
Script Delivery
- Admin creates or updates a function via the admin API.
- The function manifest is stored in the Control DB.
- Server nodes pull manifests via
POST /cp/v2/nodes/:id/configs/pull. - When a manifest indicates a new or updated function, the node fetches the script body via
GET /cp/v2/objects/cloud-functions/:name?app_id=. - The script is compiled and cached in the node's Lua VM pool.
SDK Invocation
auto result = client.call_cloud_function(
"calculate_discount",
{{"item_id", "42"}, {"quantity", "15"}}
);
if (result.success) {
std::cout << "Result: " << result.result << std::endl;
std::cout << "Execution time: " << result.execution_time_ms << "ms" << std::endl;
} else {
std::cerr << "Error: " << result.message << std::endl;
}CloudFunctionResult
struct CloudFunctionResult {
bool success; // Whether execution succeeded
ResultCode code; // Error code (0 on success)
std::string message; // Error message or empty
std::string result; // Function return value (string)
uint32_t execution_time_ms; // Wall-clock execution time
uint64_t server_time; // Server timestamp
};Examples
Simple Key-Value Lookup
-- Lookup a configuration value
local key = params.key or "default"
local config = {
max_retries = "3",
timeout_ms = "5000",
feature_x = "enabled",
}
return config[key] or "unknown"Discount Calculator
local quantity = tonumber(params.quantity) or 0
local tier = params.tier or "standard"
local rates = {
standard = {10, 0.05, 50, 0.10, 100, 0.15},
premium = {5, 0.10, 25, 0.15, 50, 0.20},
}
local tiers = rates[tier] or rates.standard
local discount = 0
for i = 1, #tiers, 2 do
if quantity >= tiers[i] then
discount = tiers[i + 1]
end
end
return string.format('{"discount":%.2f,"quantity":%d,"tier":"%s"}',
discount, quantity, tier)User-Specific Logic
-- Access injected user context
local msg = string.format(
"Hello %s (ID: %d), your device is %s. Server time: %d",
username, user_id, device_id, server_time
)
return msgInput Validation
local email = params.email or ""
if not email:match("^[%w%.]+@[%w%.]+%.%w+$") then
error("Invalid email format")
end
return "valid"JSON Response Construction
local items = {}
for k, v in pairs(params) do
table.insert(items, string.format('"%s":"%s"', k, v))
end
return "{" .. table.concat(items, ",") .. "}"Error Handling
Cloud function errors fall into several categories:
| Error | Cause | SDK Behavior |
|---|---|---|
| Function not found | Name does not exist or is disabled | success=false, error message |
| Timeout | Script exceeded 1000ms | success=false, timeout error |
| Runtime error | Lua error() or uncaught exception | success=false, error message includes Lua traceback |
| Backpressure | In-flight limit reached | success=false, overload error |
| Sandbox violation | Attempt to use restricted library | Caught at load time; function never executes |
Best Practices
- Keep functions short -- target under 100ms execution time. The 1000ms timeout is a safety net, not a target.
- Return JSON strings -- for structured data, construct JSON manually using
string.formator table concatenation. The SDK receives the return value as a plain string. - Validate inputs -- use
tonumber()and nil checks. Theparamstable may contain unexpected keys. - Avoid infinite loops -- the timeout will kill the script, but it wastes a thread pool slot for the full duration.
- Use
pcallfor error handling -- wrap risky operations inpcallto return structured error messages instead of crashing.
Next Steps
- SDK Integration -- invoking cloud functions from the SDK
- Admin API -- cloud function management endpoints
- System Architecture -- thread pool isolation model