Skip to content

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 ​

PropertyDetail
LanguageLua 5.4
SandboxRestricted (no I/O, OS, debug, package system)
Default timeout1000ms per invocation
Uniquenessapp_id + name (one function per name per application)
ExecutionDedicated cloud_function_threads pool with backpressure
DeliveryScripts 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:

LibraryReason
ioFile system access
osOperating system interaction
debugSandbox escape vector
package / requireModule loading
dofile / loadfileFile execution

Available Standard Libraries ​

  • string -- string manipulation
  • table -- table operations
  • math -- mathematical functions
  • utf8 -- UTF-8 support
  • coroutine -- 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:

GlobalTypeDescription
paramstableKey-value parameters passed by the SDK caller
user_idnumberAuthenticated user's ID
app_idnumberApplication ID from the session
usernamestringAuthenticated username
device_idstringClient device identifier
server_timenumberServer timestamp (unix milliseconds)

Management ​

Creating a Cloud Function ​

POST /admin/v1/cloud-functions
json
{
    "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=1

Returns all cloud functions for the specified application, with pagination support.

Updating a Function ​

PUT /admin/v1/cloud-functions/:name?app_id=1
json
{
    "script": "-- updated logic\nlocal rate = 0.10\nreturn tostring(rate)",
    "enabled": true
}

Toggling Enable/Disable ​

PATCH /admin/v1/cloud-functions/:name/toggle?app_id=1

Disabled functions return an error when invoked by the SDK.

Deleting a Function ​

DELETE /admin/v1/cloud-functions/:name?app_id=1

Viewing a Function Detail ​

GET /admin/v1/cloud-functions/:name?app_id=1

Execution 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:

CoresCF ThreadsMax In-Flight
1--2132
3--42128
5--83192
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 ​

  1. Admin creates or updates a function via the admin API.
  2. The function manifest is stored in the Control DB.
  3. Server nodes pull manifests via POST /cp/v2/nodes/:id/configs/pull.
  4. 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=.
  5. The script is compiled and cached in the node's Lua VM pool.

SDK Invocation ​

cpp
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 ​

cpp
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 ​

lua
-- 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 ​

lua
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 ​

lua
-- 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 msg

Input Validation ​

lua
local email = params.email or ""
if not email:match("^[%w%.]+@[%w%.]+%.%w+$") then
    error("Invalid email format")
end
return "valid"

JSON Response Construction ​

lua
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:

ErrorCauseSDK Behavior
Function not foundName does not exist or is disabledsuccess=false, error message
TimeoutScript exceeded 1000mssuccess=false, timeout error
Runtime errorLua error() or uncaught exceptionsuccess=false, error message includes Lua traceback
BackpressureIn-flight limit reachedsuccess=false, overload error
Sandbox violationAttempt to use restricted libraryCaught 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.format or table concatenation. The SDK receives the return value as a plain string.
  • Validate inputs -- use tonumber() and nil checks. The params table 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 pcall for error handling -- wrap risky operations in pcall to return structured error messages instead of crashing.

Next Steps ​