infinity.http2¶
Provides HTTP/2 server functionality with WebSocket support.
Module: infinity.http2
HTTP/2 Server Architecture Overview¶
The INFINITY.JS HTTP/2 server uses the same multi-threaded architecture as the HTTP server, with additional support for HTTP/2 multiplexing and WebSocket connections.
Architecture Highlights¶
HTTP/2 servers in INFINITY.JS benefit from: - Same Thread Pool Model: Uses maxConnections and poolSize parameters (see HTTP Architecture for details) - HTTP/2 Multiplexing: Multiple requests/responses on single TCP connection - WebSocket Support: Bidirectional communication with the scripts set in the onMessage and onBinary properties - Channels: WebSocket clients can subscribe to channels, the server can broadcast data to all clients of a channel - Connection Reuse: Reduced latency through persistent connections
graph TB
subgraph "Main Program Thread"
MainJS["main.js"]
ServerObj["server = new infinity.http2.server()"]
Listener["HTTP/2 Listener<br/>(TLS Required)"]
end
subgraph "Connection Queue"
Queue["HTTP/2 Connections<br/>(Multiplexed Streams)"]
end
subgraph "Worker Thread Pool"
Worker1["Worker Thread 1<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
Worker2["Worker Thread 2<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
WorkerN["Worker Thread N<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
end
Client["HTTP/2 Client<br/>Multiple Streams"]
MainJS --> ServerObj
ServerObj --> Listener
Client -->|"Single TCP + TLS<br/>Multiple Streams"| Listener
Listener -->|"Stream 1, 3, 5..."| Queue
Queue -.->|"Assign Stream"| Worker1
Queue -.->|"Assign Stream"| Worker2
Queue -.->|"Assign Stream"| WorkerN
Worker1 -.->|"Response"| Client
Worker2 -.->|"WebSocket Frame"| Client
WorkerN -.->|"Response"| Client
style MainJS fill:#4a90e2
style Listener fill:#ab47bc
style Queue fill:#ffa726
style Worker1 fill:#7cb342
style Worker2 fill:#7cb342
style WorkerN fill:#7cb342
style Client fill:#ef5350 HTTP/2-Specific Features¶
Stream Multiplexing: - Single TCP connection carries multiple request/response pairs (streams) - Each stream processed independently by worker threads - Eliminates head-of-line blocking from HTTP/1.1
WebSocket Support:
The onMessage and onBinary properties of the server contain the file names of scripts that are executed for each received WebSocket text or binary message. Inside these scripts, the infinity.http2.session namespace gives access to the message and the connection:
main.ts:
infinity.loadModule('infinity.http2');
let server = new infinity.http2.server(true);
server.onMessage = 'message.js';
server.start();
message.ts:
console.log('WebSocket message: ' + infinity.http2.session.message);
infinity.http2.session.writeString('Echo: ' + infinity.http2.session.message);
Connection Management: - Browsers only use HTTP/2 over TLS (HTTPS) - Up to 256 concurrent streams per connection - Worker threads assigned per stream, not per connection
Performance Benefits: - Reduced latency through multiplexing - Header compression (HPACK) reduces bandwidth - Binary protocol improves parsing efficiency
Request and response data: Scripts of custom handlers and service methods registered with httpEnvironment: true access the request and response data via infinity.http.request and infinity.http.response (there are no infinity.http2.request and infinity.http2.response namespaces).
For detailed thread pool architecture and configuration guidelines, see HTTP Server Architecture Overview.
server¶
Allows for your instance of INFINITY.JS to act as an HTTP/2-server (also supporting HTTP/1.1 and WebSocket connections). Lets you receive requests and send data. Can register handlers for static files, single page applications, custom scripts, REST requests, the JSON-RPC protocol, API descriptions and a status report (JSON-RPC, REST and API handlers require the simultaneous usage of registerHandler() and registerService()). JSON-RPC and REST handlers can be combined in one service. The handlers work like the handlers of infinity.http.server; request and response data is available via infinity.http.request and infinity.http.response.
The server instance has no free() method; it is released when the object is garbage collected.
Properties:
Methods:
Example:
infinity.loadModule('infinity.http2');
let myServer = new infinity.http2.server(true, false, false, false, false, false, 443, 1024, 64, 104857600, 5.0);
myServer.registerHandler(infinity.http2.server.handler.status, '/status');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/', 60.0, 256144);
myServer.registerHandler(infinity.http2.server.handler.jsonRpc, '/v1/jsonrpc');
myServer.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
myServer.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
myServer.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
Example POST-request against /v1/jsonrpc:
{"jsonrpc": "2.0", "method": "system.getVersion"}
Properties
onBinary¶
Type: string
The filename (relative to the folder of the main script) of the script that is executed for each binary WebSocket message. The property is evaluated by start(), which throws an error if the file does not exist. Default: '' (binary messages are ignored). Within that script, you can access the infinity.http2.session object, which will contain (among others) the following property:
fileName: the path to a temporary file containing the binary data sent by the client (the file is deleted after the script has finished)
onMessage¶
Type: string
The filename (relative to the folder of the main script) of the script that is executed for each text WebSocket message. The property is evaluated by start(), which throws an error if the file does not exist. Default: '' (text messages are ignored). Within that script, you can access the infinity.http2.session object, which will contain (among others) the following property:
message: the message text that has been sent by the client
Methods
constructor()¶
Lets you create an INFINITY.JS HTTP/2 server object instance. Takes the most important parameters for the server to function.
Signature:
constructor( ssl?: boolean, verifyCertificate?: boolean, allowCrossOrigin?: boolean, compress?: boolean, accessLog?: boolean, iocp?: boolean, port?: number, maxConnections?: number, poolSize?: number, maxContentLength?: number, slowRequestTime?: number, protocol?: infinity.http2.server.protocol, maxRateCounter?: number )
Parameters:
-
ssl:
boolean, optionalFor using SSL connections. Default:
false. If enabled, the server initially uses the certificate filesinfinity.crt,infinity.keyandinfinity.root.crtfrom theresourcesfolder next to the folder of the INFINITY.JS executable. Use setCertificate() to set other certificate files. -
verifyCertificate:
boolean, optionalWhether to verify SSL client certificates. Default:
false. -
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. -
iocp:
boolean, optionalSpecifies the usage of I/O completion ports (Windows) for socket handling. Default:
false. -
port:
number, optionalSpecifies the port to listen on. Default:
443ifsslistrue, otherwise80. -
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). -
maxContentLength:
number, optionalSpecifies the maximum number of bytes (content-length header) that the server accepts in http 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). -
protocol:
infinity.http2.server.protocol, optionalSpecifies the TLS version to be used. Default:
all. -
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.http2');
let myServer = new infinity.http2.server(true, false, false, false, false, false, 443, 1024, 64, 104857600, 5.0);
broadcast()¶
Sends data as JSON text message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.
Signature:
broadcast( data: any, channel?: string, exclude?: string, include?: string ): void
Parameters:
-
data:
anyData to be sent (can be any object, number, string, etc.). The data is serialized to JSON, so a string is sent including quotes; use broadcastString() to send a string as it is.
-
channel:
string, optionalChannel name. If omitted, the data is sent to all clients.
-
exclude:
string, optionalComma-separated list of client ids to exclude from the broadcast.
-
include:
string, optionalComma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).
Example:
myServer.broadcast({event: 'update', id: 1}, 'news');
broadcastStream()¶
Sends data from a stream as binary message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.
Signature:
broadcastStream( stream: infinity.stream, channel?: string, exclude?: string, include?: string ): void
Parameters:
-
stream:
infinity.streamA stream from which to read data and send it to the clients.
-
channel:
string, optionalChannel name. If omitted, the data is sent to all clients.
-
exclude:
string, optionalComma-separated list of client ids to exclude from the broadcast.
-
include:
string, optionalComma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).
Example:
myServer.broadcastStream(stream, 'news');
broadcastString()¶
Sends a string as text message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.
Signature:
broadcastString( message: string, channel?: string, exclude?: string, include?: string ): void
Parameters:
-
message:
stringMessage to send to the clients.
-
channel:
string, optionalChannel name. If omitted, the message is sent to all clients.
-
exclude:
string, optionalComma-separated list of client ids to exclude from the broadcast.
-
include:
string, optionalComma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).
Example:
myServer.broadcastString('Hello subscribers', 'news');
registerHandler()¶
Registers a handler for client requests on the given path. The meaning of the parameters following path depends on the handler type:
jsonRpc,rest,apiandstatus:registerHandler(handler, path, limit?, period?, delay?)custom:registerHandler(handler, path, alias, limit?, period?, delay?)staticFileandspa:registerHandler(handler, path, alias, expire?, maxCacheSize?, headers?, limit?, period?, delay?)
A handler registered for an already registered path replaces the previous handler. See infinity.http.server.registerHandler() for details.
Signatures:
registerHandler( handler: infinity.http2.server.handler, path: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http2.server.handler, path: string, alias: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http2.server.handler, path: string, alias: string, expire?: number, maxCacheSize?: number, headers?: infinity.http2.headerArray, limit?: number, period?: number, delay?: number ): void
Parameters:
-
handler:
infinity.http2.server.handlerThe type of handler to register.
-
path:
stringThe request path the handler is registered for.
-
alias:
stringOnly for
custom,staticFileandspahandlers. Forcustomhandlers: the path of the script file (relative to the folder of the main script) that is executed for each request. ForstaticFileandspahandlers: the path of the folder (relative to the folder of the main script) containing the files to be served. -
expire:
number, optionalOnly for
staticFileandspahandlers. The cache 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, optionalOnly for
staticFileandspahandlers. The cache threshold in bytes. Files with sizes exceeding the specified number will not be cached. Default:0. -
headers:
infinity.http2.headerArray, optionalOnly for
staticFileandspahandlers. Additional 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 to this handler in the defined period (rate limiting; every handler has its own counters). 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:
myServer.registerHandler(infinity.http2.server.handler.status, '/status');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/', 60, 256144);
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.http2.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.http2.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:
myServer.registerHandler(infinity.http2.server.handler.jsonRpc, '/v1/jsonrpc');
// Basic service without validation
myServer.registerService('system', 'system', 'system.js', [
{name: 'shutdown'},
{name: 'getVersion', result: 'string'}
]);
// Service with validation constraints
myServer.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';
}
}
Folder structure:
+ example
+ ts
- main.ts
- system.ts
POST-request against /v1/jsonrpc:
{"jsonrpc": "2.0", "method": "system.getVersion"}
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.http2');
let http2 = new infinity.http2.server();
http2.registerTypes([
{name: 'users.role', kind: 'enum', values: ['user = 1', 'admin = 2']},
{name: 'users.user', kind: 'object', properties: [
'id: number{0,}',
'username: string{3,32}',
'role?: users.role'
]}
]);
http2.registerService('users', 'users', 'users.js', [
{name: 'add', params: ['user: users.user'], result: 'number'}
]);
unregisterTypes()¶
Unregisters a previously registered custom type definition. See infinity.http.server.unregisterTypes() for details.
Signature:
unregisterTypes( name: string ): void
setCertificate()¶
Sets the SSL certificate for the current server instance using the corresponding files provided in the function parameters. Throws an error if the server was created without SSL. Files that do not exist are ignored.
Signature:
setCertificate( certFile: string, keyFile: string, rootCertFile?: string, verify?: boolean ): void
Parameters:
-
certFile:
stringThe path to the certificate file to be used.
-
keyFile:
stringThe path to the key file to be used.
-
rootCertFile:
string, optionalThe path to the root certificate file to be used.
-
verify:
boolean, optionalWhether to verify SSL client certificates. Default:
false.
Example:
myServer.setCertificate('certFile.crt', 'keyFile.key', 'rootCertFile.crt', true);
start()¶
Starts the server instance with previously specified parameters. Evaluates the onMessage and onBinary properties.
Signature:
start(): void
Example:
myServer.start();
stop()¶
Shuts down the server instance.
Signature:
stop(): void
Example:
myServer.stop();
unregisterHandler()¶
Unregisters the specified registered handler, making the previously defined functionality unavailable.
Signature:
unregisterHandler( path: string ): void
Parameters:
- path:
stringThe request path for the client, which the handler has previously been registered for.
Example:
myServer.unregisterHandler('/');
unregisterService()¶
Unregisters the specified registered service, making the previously defined functionality unavailable.
Signature:
unregisterService( name: string ): void
Parameters:
- name:
stringThe name of the previously registered service.
Example:
myServer.unregisterService('system');
write()¶
Sends data as JSON text message to a specific WebSocket client connection. Returns whether the data could be sent.
Signature:
write( id: string, data: any ): boolean
Parameters:
-
id:
stringId of the client connection (see
infinity.http2.session.id). -
data:
anyData to be sent (can be any object, number, string, etc.). The data is serialized to JSON.
Return type: boolean
Example:
myServer.write(id, data);
writeStream()¶
Sends data from a stream as binary message to a specific WebSocket client connection. Returns whether the data could be sent.
Signature:
writeStream( id: string, stream: infinity.stream ): boolean
Parameters:
-
id:
stringId of the client connection (see
infinity.http2.session.id). -
stream:
infinity.streamA stream from which to read data and send it to the client.
Return type: boolean
Example:
myServer.writeStream(id, stream);
writeString()¶
Sends a string as text message to a specific WebSocket client connection. Returns whether the message could be sent.
Signature:
writeString( id: string, message: string ): boolean
Parameters:
-
id:
stringId of the client connection (see
infinity.http2.session.id). -
message:
stringMessage to send to the client.
Return type: boolean
Example:
myServer.writeString(id, message);
infinity.http2.server¶
infinity.http2.server.handler¶
Values:
-
custom:
0A custom handler: the script file specified in the third function parameter (
alias) of registerHandler() is executed for each request. Inside the script,infinity.http.requestandinfinity.http.responseare available. -
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.http2');
let handler = infinity.http2.server.handler.custom;
infinity.http2.server.protocol¶
Values:
-
all:
0No specific TLS version is set (default).
-
tls1_0:
1Specifies the usage of TLS 1.0.
-
tls1_1:
2Specifies the usage of TLS 1.1.
-
tls1_2:
3Specifies the usage of TLS 1.2.
-
tls1_3:
4Specifies the usage of TLS 1.3.
Example:
infinity.loadModule('infinity.http2');
let protocol = infinity.http2.server.protocol.tls1_2;
infinity.http2.session¶
The infinity.http2.session object is available in the scripts set in the onMessage and onBinary properties of the infinity.http2.server. It provides information about the WebSocket connection that sent the message and functions to send data back to it. Each message is processed in a new script runtime.
disconnect()¶
Disconnects the current WebSocket connection.
Signature:
disconnect(): void
Example:
infinity.loadModule('infinity.http2');
infinity.http2.session.disconnect();
subscribe()¶
Subscribes the current connection to a specific channel. The channel name can be chosen arbitrarily and the server can use the broadcast(), broadcastString() and broadcastStream() methods to send data to all connections that are subscribed to a specific channel.
Signature:
subscribe( channel: string ): void
Parameters:
- channel:
stringChannel name.
Example:
infinity.loadModule('infinity.http2');
infinity.http2.session.subscribe(channel);
subscribed()¶
Checks whether the current connection has been subscribed to a specific channel.
Signature:
subscribed( channel: string ): boolean
Parameters:
- channel:
stringChannel name.
Return type: boolean
Example:
infinity.loadModule('infinity.http2');
if ( infinity.http2.session.subscribed(channel) ) {}
unsubscribe()¶
Unsubscribes the current connection from a specific channel.
Signature:
unsubscribe( channel: string ): void
Parameters:
- channel:
stringChannel name.
Example:
infinity.loadModule('infinity.http2');
infinity.http2.session.unsubscribe(channel);
write()¶
Sends data as JSON text message to the current connection.
Signature:
write( data: any ): void
Parameters:
- data:
anyData to be sent (can be any object, number, string, etc.). The data is serialized to JSON.
Example:
infinity.http2.session.write({status: 'ok'});
writeStream()¶
Sends data from a stream as binary message to the current connection.
Signature:
writeStream( stream: infinity.stream ): void
Parameters:
- stream:
infinity.streamA stream from which to read and send data.
Example:
infinity.http2.session.writeStream(stream);
writeString()¶
Sends a string as text message to the current connection.
Signature:
writeString( message: string ): void
Parameters:
- message:
stringMessage to send.
Example:
infinity.http2.session.writeString('Echo: ' + infinity.http2.session.message);
fileName¶
Type: string
Only in the onBinary script: the path to a temporary file containing the binary data sent by the client. The file is deleted after the script has finished.
id¶
Type: string
The id of the WebSocket connection. It remains constant as long as the connection exists and can be used with the server methods write(), writeString() and writeStream() and the exclude/include parameters of the broadcast methods.
ip¶
Type: string
The IP address from which the client connected.
message¶
Type: string
Only in the onMessage script: the text message sent by the client.
port¶
Type: number
The port used by the connection with the client.
headerArray¶
Extends: Array<{name: string, value: string}>
An array of HTTP-header names and values.
Properties:¶
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.