infinity.scgi¶
Provides functionality for setting up an INFINITY.JS instance as a SCGI server.
Module: infinity.scgi
SCGI Server Architecture Overview¶
The INFINITY.JS SCGI server uses the same multi-threaded architecture as HTTP and HTTP/2 servers. SCGI (Simple Common Gateway Interface) is designed to work behind a web server (like Nginx or Apache) that forwards requests via the SCGI protocol.
Architecture Highlights¶
graph LR
WebServer["Web Server<br/>(Nginx/Apache)"]
Listener["SCGI Listener<br/>(Port 9000)"]
Queue["Connection Queue"]
Workers["Worker Thread Pool<br/>(poolSize)"]
Handlers["Request Handlers<br/>JavaScript Engine"]
Client["HTTP Client"]
Client -->|"HTTP Request"| WebServer
WebServer -->|"SCGI Protocol"| Listener
Listener --> Queue
Queue -.-> Workers
Workers --> Handlers
Handlers -.->|"SCGI Response"| WebServer
WebServer -.->|"HTTP Response"| Client
style WebServer fill:#9c27b0
style Listener fill:#ab47bc
style Queue fill:#ffa726
style Workers fill:#7cb342
style Handlers fill:#26c6da SCGI Architecture: - Reverse Proxy Setup: Web server (Nginx/Apache) forwards requests to SCGI server - Same Threading Model: Uses maxConnections and poolSize parameters - Protocol Simplicity: Netstring-based protocol simpler than FastCGI - Performance: Similar to HTTP server with proxy overhead
Typical Nginx Configuration:
location / {
scgi_pass 127.0.0.1:9000;
include scgi_params;
}
Example Server Setup:
infinity.loadModule('infinity.scgi');
let scgi = new infinity.scgi.server(
false, // allowCrossOrigin
false, // compress
true, // accessLog
9000, // port
1024, // maxConnections
64 // poolSize
);
scgi.registerHandler(infinity.scgi.server.handler.staticFile, '/', '../web/');
scgi.registerHandler(infinity.scgi.server.handler.jsonRpc, '/api/v1/jsonrpc');
scgi.start();
For detailed thread pool architecture and configuration guidelines, see HTTP Server Architecture Overview.
server¶
The class for operations with SCGI servers in INFINITY.JS. The handlers work like the handlers of infinity.http.server. Scripts of custom handlers and service methods registered with httpEnvironment: true access the request and response data via infinity.http.request (with scgi set to true and the additional SCGI properties like remoteHost or scriptFilename) and infinity.http.response.
The server instance has no free() method; it is released when the object is garbage collected.
Methods:
Example:
infinity.loadModule('infinity.scgi');
let myScgi = new infinity.scgi.server(false, false, false, 9000);
myScgi.registerHandler(infinity.scgi.server.handler.staticFile, '/', '../web/');
myScgi.registerHandler(infinity.scgi.server.handler.jsonRpc, '/v1/jsonrpc');
myScgi.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
myScgi.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
myScgi.stop();
system.ts:
namespace system {
export function shutdown(): void {
infinity.terminate();
}
export function getVersion(): string {
return '1.0.0 build 1234';
}
}
Folder structure:
+ example
+ ts
- main.ts
- system.ts
+ web
- index.html
Methods
constructor()¶
Lets you create an INFINITY.JS SCGI server object instance.
Signature:
constructor( allowCrossOrigin?: boolean, compress?: boolean, accessLog?: boolean, port?: number, maxConnections?: number, poolSize?: number, maxContentLength?: number, slowRequestTime?: number, maxRateCounter?: number )
Parameters:
-
allowCrossOrigin:
boolean, optionalFor allowing cross-origin-requests (CORS headers). Default:
false. -
compress:
boolean, optionalFor turning compression of responses on or off. Default:
false. -
accessLog:
boolean, optionalFor turning on or off the logging of all requests to the console/log file. Default:
false. -
port:
number, optionalSpecifies the port to listen on. Default:
4000. -
maxConnections:
number, optionalSpecifies the maximum number of simultaneous connections. Default:
0(unlimited). -
poolSize:
number, optionalSpecifies the number of worker threads to be held ready. Default:
0(no thread pool, a new thread is created for each connection). -
maxContentLength:
number, optionalSpecifies the maximum number of bytes (content-length header) that the server accepts in requests. Default:
104857600(100 MB). -
slowRequestTime:
number, optionalSpecifies how many seconds the processing of a request is allowed to take without being logged as "slow". Accepts decimals with
.as well. Default:0(slow requests are not logged). -
maxRateCounter:
number, optionalThe maximum number of rate counters (one per handler and client IP address) tracked for rate limiting (see the
limit,periodanddelayparameters of registerHandler()). If more addresses are tracked, all rate counters are reset. Default:0(unlimited).
Example:
infinity.loadModule('infinity.scgi');
let myScgi = new infinity.scgi.server(false, false, false, 9000);
registerHandler()¶
Registers a jsonRpc, rest, api or status handler for processing client requests on the SCGI server, with optional rate limiting.
Signature:
registerHandler( handler: infinity.scgi.server.handler, path: string, limit?: number, period?: number, delay?: number ): void
Parameters:
-
handler:
infinity.scgi.server.handlerThe type of handler to register for handling client requests.
-
path:
stringThe URL path on which this handler will be activated.
-
limit:
number, optionalThe maximum number of requests per client IP address on this path within the specified time period. If the limit is exceeded, the request is answered with status code
429. Default:0(no rate limiting). -
period:
number, optionalThe time frame in seconds for the rate limit.
-
delay:
number, optionalThe number of seconds the server waits before sending the
429response to a client that exceeded the rate limit.
Example:
myScgi.registerHandler(infinity.scgi.server.handler.rest, '/api', 100, 3600, 300);
registerHandler()¶
Registers a custom handler for processing client requests on the SCGI server: the given script file is executed for each request. Optionally sets rate limits.
Signature:
registerHandler( handler: infinity.scgi.server.handler, path: string, alias: string, limit?: number, period?: number, delay?: number ): void
Parameters:
-
handler:
infinity.scgi.server.handlerThe type of handler to be registered (
custom). -
path:
stringThe URL path on which the handler will be activated.
-
alias:
stringThe path of the script file (relative to the folder of the main script) that is executed for each request.
-
limit:
number, optionalThe maximum number of requests per client IP address on this path within the specified time period. If the limit is exceeded, the request is answered with status code
429. Default:0(no rate limiting). -
period:
number, optionalThe time frame in seconds for the rate limit.
-
delay:
number, optionalThe number of seconds the server waits before sending the
429response to a client that exceeded the rate limit.
Example:
myScgi.registerHandler(infinity.scgi.server.handler.custom, '/custom', '/custom.js');
registerHandler()¶
Registers a staticFile or spa handler for client requests, serving files from a local folder, including caching functionality.
Signature:
registerHandler( handler: infinity.scgi.server.handler, path: string, alias: string, expire?: number, maxCacheSize?: number, headers?: infinity.scgi.headerArray, limit?: number, period?: number, delay?: number ): void
Parameters:
-
handler:
infinity.scgi.server.handlerThe type of handler to register (
staticFileorspa). -
path:
stringThe request path for the client.
-
alias:
stringThe path of the folder (relative to the folder of the main script) containing the files to be served.
-
expire:
number, optionalCache expiration time in whole seconds. After the specified period the file will have to be examined for changes at the next call. Default:
0(files are not cached). -
maxCacheSize:
number, optionalThe cache threshold in bytes. Files with sizes exceeding the specified number will not be cached. Default:
0. -
headers:
infinity.scgi.headerArray, optionalAdditional headers to be sent with every response of the handler.
-
limit:
number, optionalThe maximum number of requests per client IP address that can be made in the defined period (rate limiting). If the limit is exceeded, the request is answered with status code
429. Default:0(no rate limiting). -
period:
number, optionalThe rate limit time period in seconds.
-
delay:
number, optionalThe number of seconds the server waits before sending the
429response to a client that exceeded the rate limit.
Example:
myScgi.registerHandler(infinity.scgi.server.handler.staticFile, '/', '../web/');
registerService()¶
Registers a service, allowing requests for execution of custom defined methods. Supports parameter and result type validation using built-in types, validation constraints (e.g., number{1,}, string{3,32}), and custom types defined with registerTypes().
Signature:
registerService( name: string, namespace: string, path: string, methods: infinity.scgi.methodArray ): void
Parameters:
-
name:
stringThe name of the service.
-
namespace:
stringThe namespace for the service.
-
path:
stringThe path to the file with the custom defined methods.
-
methods:
infinity.scgi.methodArrayAn array of method definitions. Each method can specify: -
name: Method name (required) -params: Array of parameter definitions with types and validation constraints -result: Declared return type (only used for the description generated by theapihandler, return values are not validated) -rest: REST method mapping ('get','getList','post','put'or'delete') -httpEnvironment: If true, provides access toinfinity.http.requestandinfinity.http.responseinside the method
Parameter Type Validation:
Supports the same validation syntax as infinity.http.server.registerService(): - number{min,max} - Numeric range validation - string{min,max} - String length validation - Custom types - Reference types defined with registerTypes()
Example:
// Basic service without validation
myScgi.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
// Service with validation constraints
myScgi.registerService('users', 'users', 'users.js', [
{
name: 'login',
params: ['username: string{3,32}', 'password: string{8,}'],
result: 'object'
},
{
name: 'get',
params: ['id: number{1,}'],
result: 'object'
}
]);
For detailed validation syntax and examples, see: infinity.http.server.registerService()
system.ts:
namespace system {
export function shutdown(): void {
infinity.terminate();
}
export function getVersion(): string {
return '1.0.0 build 1234';
}
}
registerTypes()¶
Registers custom type definitions for request/response validation. This method works identically to infinity.http.server.registerTypes() and supports the same type system including enums, objects, and arrays with validation constraints.
Signature:
registerTypes( types: infinity.http.typesArray ): void
For complete documentation including validation syntax, examples, and type definition reference, see infinity.http.server.registerTypes().
Example:
infinity.loadModule('infinity.scgi');
let scgi = new infinity.scgi.server();
scgi.registerTypes([
{name: 'api.status', kind: 'enum', values: ['ok = 1', 'error = 2']},
{name: 'api.response', kind: 'object', properties: [
'status: api.status',
'message: string{1,255}'
]}
]);
scgi.registerService('api', 'api', 'api.js', [
{name: 'getStatus', result: 'api.response'}
]);
unregisterTypes()¶
Unregisters a previously registered custom type definition. See infinity.http.server.unregisterTypes() for details.
Signature:
unregisterTypes( name: string ): void
start()¶
Starts the server with previously specified parameters.
Signature:
start(): void
Example:
myScgi.start();
stop()¶
Shuts down the server.
Signature:
stop(): void
Example:
myScgi.stop();
unregisterHandler()¶
Unregisters the specified registered handler, making the previously specified functionality unavailable.
Signature:
unregisterHandler( path: string ): void
Parameters:
- path:
stringThe request path for the client, which the handler has previously been registered for.
Example:
myScgi.unregisterHandler('/');
unregisterService()¶
Unregisters the specified registered service, making the previously specified functionality unavailable.
Signature:
unregisterService( name: string ): void
Parameters:
- name:
stringThe name of the previously registered service.
Example:
myScgi.unregisterService('system');
infinity.scgi.server¶
infinity.scgi.server.handler¶
Values:
-
custom:
0A custom handler: the script file specified in the third function parameter (
alias) of registerHandler() is executed for each request. -
staticFile:
1A handler for serving static file content from the folder specified in the
aliasparameter. For requests to a folder, theindex.htmlfile of the folder is served. -
jsonRpc:
2A handler for requests according to the JSON-RPC protocol (calls methods of the registered services).
-
rest:
3A handler for REST-requests (calls methods of the registered services according to their
restmapping). -
api:
4A handler that returns a JSON-WSP description of all registered services and methods (
GETrequests). -
status:
5A handler for server-status requests, returning server and resource usage information as JSON.
-
spa:
6A handler for single page applications: like
staticFile, but requests for files that do not exist are answered with theindex.html(orindex.htm) file of thealiasfolder.
Example:
infinity.loadModule('infinity.scgi');
let handler = infinity.scgi.server.handler.custom;
headerArray¶
Extends: Array<{name: string, value: string}>
An array of objects containing name-value string pairs (HTTP-header names and values).
methodArray¶
Extends: Array<{name: string, params?: Array<string>, result?: any, rest?: string, httpEnvironment?: boolean}>
An array containing objects with data inside its properties.
Properties:¶
-
name¶
Type:
string. The name of the function. -
params¶
Type:
Array<string>, optional. The function parameters in the format'name: type'or'name?: type'(optional parameter), see infinity.http.server.registerService(). -
result¶
Type:
any, optional. The declared return type of the function result (only used for the description of theapihandler, not validated). -
rest¶
Type:
string, optional. The REST verb the function is mapped to:'get','getList','post','put'or'delete'. -
httpEnvironment¶
Type:
boolean, optional. If set to true,infinity.http.requestandinfinity.http.responseare available inside the function.