ballerina/http module

Module overview

This module provides an implementation for connecting and interacting with HTTP, HTTP2, and WebSocket endpoints. The module facilitates two types of endpoints as ‘Client’ and ‘Listener’.

Client endpoints

Client endpoints are used to connect to and interact with HTTP endpoints. They support connection pooling and can be configured to have a maximum number of active connections that can be made with the remote endpoint. Client endpoints activate connection eviction after a given idle period and also support follow-redirects so that the users do not have to manually handle 3xx HTTP status codes.

Client endpoints handle resilience in multiple ways such as load balancing, circuit breaking, endpoint timeouts, and a retry mechanism.

Load balancing is used in the round robin or failover manner.

When a failure occurs in the remote service, the client connections might wait for some time before a timeout occurs. Awaiting requests consume resources in the system. Circuit Breakers are used to trip after a certain number of failed requests to the remote service. Once a circuit breaker trips, it does not allow the client to send requests to the remote service for a period of time.

The Ballerina circuit breaker supports tripping on HTTP error status codes and I/O errors. Failure thresholds can be configured based on a sliding window (e.g., 5 failures within 10 seconds). Client endpoints also support a retry mechanism that allows a client to resend failed requests periodically for a given number of times.

Client endpoints support Certificate Revocation List (CRL), Online Certificate Status Protocol (OCSP) and OCSP Stapling for SSL/TLS connection. They also support HTTP2, keep-alive, chunking, HTTP caching, and data compression/decompression.

See Client Endpoint Example, Circuit Breaker Example, HTTP Redirects Example

Listener endpoints

A Service represents a collection of network-accessible entry points and can be exposed via a Listener endpoint. A resource represents one such entry point and can have its own path, HTTP methods, body format, 'consumes' and 'produces' content types, CORS headers, etc. In resources, endpoint and http:Request are mandatory parameters while path and body are optional.

When a Service receives a request, it is dispatched to the best-matched resource.

See Listener Endpoint Example, HTTP CORS Example, HTTP Failover Example, HTTP Load Balancer Example

Listener endpoints can be exposed via SSL. They support Mutual SSL, Hostname Verification, and Server Name Indication (SNI) and Application Layer Protocol Negotiation (ALPN). Listener endpoints also support Certificate Revocation List (CRL), Online Certificate Status Protocol (OCSP), OCSP Stapling, HTTP2, keep-alive, chunking, HTTP caching, and data compression/decompression.

See Mutual SSL Example.

See Caching Example, HTTP Disable Chunking Example.

WebSockets

The module also provides support for WebSockets. There are two types of WebSocket endpoints: WebSocketClient and WebSocketListener. Both endpoints support all WebSocket frames. The WebSocketClient has a callback service.

There are also two types of services for WebSocket: WebSocketService and WebSocketClientService. The callback service for WebSocketClient is always a WebSocketClientService. The WebSocket services have a fixed set of resources that do not have a resource config. The incoming messages are passed to these resources.

WebSocket upgrade: During a WebSocket upgrade, the initial message is an HTTP request. To intercept this request and make the upgrade explicitly with custom headers, the user must create an HTTP resource with WebSocket specific configurations as follows:

 @http:ResourceConfig {
        webSocketUpgrade: {
            upgradePath: "/{name}",
            upgradeService: chatApp
        }
    }
    resource function upgrader(http:Caller caller, http:Request req, string name) {
    }
}

Here upgradeService is a WebSocketService.

onOpen resource: As soon as the WebSocket handshake is completed and the connection is established, the onOpen resource is dispatched. This resource is only available in the WebSocketService.

onText resource: Received Text messages are dispatched to this resource.

onBinary resource: Received Binary messages are dispatched to this resource.

onPing and onPong resources: Received ping and pong messages are dispatched to these resources respectively as a blob

onIdleTimeout: This resource is dispatched when idle timeout is reached. idleTimeout has to be configured by the user in WebSocket service configuration.

onClose: This resource is dispatched when a close message is received.

onError: This resource is dispatched when an error occurs in the WebSocket connection. This will always be followed by a connection closure with an appropriate WebSocket close frame.

See WebSocket Basic Example, HTTP to WebSocket Upgrade Example, WebSocket Chat Application, WebSocket Proxy Server

Logging

This module supports two types of logs:

  • HTTP access logs: These are standard HTTP access logs that are formatted using the combined log format and logged at the INFO level. Logs can be published to the console or a file using the following configurations:
    • b7a.http.accesslog.console=true
    • b7a.http.accesslog.path=<path_to_log_file>
  • HTTP trace logs: These are detailed logs of requests coming to/going out of and responses coming to/going out of service endpoints or a client endpoints. Trace logs can be published to the console, to a file or to a network socket using the following set of configurations:
    • b7a.http.tracelog.console=true
    • b7a.http.tracelog.path=<path_to_log_file>
    • b7a.http.tracelog.host=<host_name>
    • b7a.http.tracelog.port=<port>

To publish logs to a socket, both the host and port configurations must be provided.

See HTTP Access Logs Example, HTTP Trace Logs Example

Samples

A Client endpoint can be defined using the URL of the remote service that the client needs to connect with, as shown below:

http:Client clientEndpoint = new("https://my-simple-backend.com");

The defined Client endpoint can be used to call a remote service as follows:

// Send a GET request to the specified endpoint
var response = clientEndpoint->get("/get?id=123");

A Listener endpoint can be defined as follows:

// Attributes associated with the `Listener` endpoint are defined here.
listener http:Listener helloWorldEP = new(9090);

Then a Service can be defined and attached to the above Listener endpoint as shown below:

// By default, Ballerina assumes that the service is to be exposed via HTTP/1.1.
@http:ServiceConfig { basePath:"/helloWorld" }
service helloWorld on helloWorldEP {

   // All resource functions are invoked with arguments of server connector and request.
   @http:ResourceConfig {
        methods:["POST"],
        path:"/{name}",
        body:"message"
    }
   resource function sayHello(http:Caller caller, http:Request req, string name, string message) {
       http:Response res = new;
       // A util method that can be used to set string payload.
       res.setPayload("Hello, World! I’m " + untaint name + ". " + untaint message);
       // Sends the response back to the client.
       var result = caller->respond(res);
       if (result is error) {
            log:printError("Error sending response", err = result);
       }
   }
}

Module Detail

Records

Record Description
AuthCacheConfig Provides a set of configurations for controlling the authorization caching behaviour of the endpoint.
AuthConfig AuthConfig record can be used to configure the authentication mechanism used by the HTTP endpoint.
AuthProvider Configuration for authentication providers.
Authentication Can be used for enabling/disabling authentication in an HTTP service.
Bucket Represents a discrete sub-part of the time window (Bucket).
CacheConfig Provides a set of configurations for controlling the caching behaviour of the endpoint.
CircuitBreakerConfig Provides a set of configurations for controlling the behaviour of the Circuit Breaker.
CircuitBreakerInferredConfig Derived set of configurations from the `CircuitBreakerConfig`.
CircuitHealth Maintains the health of the Circuit Breaker.
ClientEndpointConfig Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint.
CompressionConfig A record for providing configurations for content compression.
ConnectionThrottling Provides configurations for throttling connections of the endpoint.
CorsConfig Configurations for CORS support.
FailoverClientEndpointConfiguration Provides a set of HTTP related configurations and failover related configurations.
FailoverConfig Provides a set of configurations for controlling the failover behaviour of the endpoint.
FailoverInferredConfig Inferred failover configurations passed into the failover client.
FollowRedirects Provides configurations for controlling the endpoint's behaviour in response to HTTP redirect related responses.
HttpResourceConfig Configuration for an HTTP resource.
HttpServiceConfig Contains the configurations for an HTTP service.
HttpTimeoutError Defines a timeout error occurred during service invocation.
KeyStore A record for providing key store related configurations.
ListenerAuthConfig Configures the authentication scheme for a service or a resource.
LoadBalanceActionErrorData Represents an error occurred in an remote function of the Load Balance connector.
LoadBalanceClientEndpointConfiguration The configurations related to the load balance client endpoint.
Local Presents a read-only view of the local address.
Protocols A record for configuring SSL/TLS protocol and version to be used.
ProxyConfig Proxy server configurations to be used with the HTTP client endpoint.
Remote Presents a read-only view of the remote address.
RequestLimits Configures limits for requests. If these limits are violated, the request is rejected.
RetryConfig Provides configurations for controlling the retry behaviour in failure scenarios.
RetryInferredConfig Derived set of configurations from the `RetryConfig`.
RollingWindow Represents a rolling window in the Circuit Breaker.
SecureSocket Provides configurations for facilitating secure communication with a remote HTTP endpoint.
ServiceEndpointConfiguration Provides a set of configurations for HTTP service endpoints.
ServiceOcspStapling A record for providing configurations for certificate revocation status checks.
ServiceSecureSocket Configures the SSL/TLS options to be used for HTTP service.
TargetService Represents a single service and its related configurations.
TrustStore A record for providing trust store related configurations.
ValidateCert A record for providing configurations for certificate revocation status checks.
Versioning Configurations for service versioning.
WSServiceConfig Configurations for a WebSocket service.
WebSocketClientEndpointConfig Configuration struct for WebSocket client endpoint.
WebSocketUpgradeConfig Configures the HTTP to WebSocket upgrade.

Objects

Object Description
AuthHandlerRegistry

Representation of the Http Auth Handler Registry.

AuthnFilter

Representation of the Authentication filter.

AuthnHandlerChain

Representation of Authentication handler chain

AuthzFilter

Representation of the Authorization filter

CircuitBreakerClient

A Circuit Breaker implementation which can be used to gracefully handle network failures.

Filter

Representation of a HTTP Request Filter. This filter will be applied before the request is dispatched to the relevant resource. Any Filter implementation should be structurally similar to the Filter object.

FilterContext

Representation of request filter Context.

HttpAuthnHandler

Representation of Authentication handler for HTTP traffic.

HttpAuthzHandler

Representation of Authorization Handler for HTTP

HttpBasicAuthnHandler

Defines Basic Auth handler for HTTP traffic.

HttpCache
HttpFuture

Represents a 'future' that returns as a result of an asynchronous HTTP request submission. This can be used as a reference to fetch the results of the submission.

HttpJwtAuthnHandler

Representation of JWT Auth handler for HTTP traffic

Listener

This is used for creating HTTP server endpoints. An HTTP server endpoint is capable of responding to remote callers. The Listener is responsible for initializing the endpoint using the provided configurations.

LoadBalancerRounRobinRule

Implementation of round robin load balancing strategy.

LoadBalancerRule

LoadBalancerRule provides a required interfaces to implement different algorithms.

MockListener

Mock server endpoint which does not open a listening port.

PushPromise

Represents an HTTP/2 PUSH_PROMISE frame.

Request

Represents an HTTP request.

RequestCacheControl

Configures cache control directives for a Request.

Response

Represents an HTTP response.

ResponseCacheControl

Configures cache control directives for a Response.

WebSocketListener

Represents a WebSocket service endpoint.

Endpoints

Endpoint Description
Caller

The caller actions for responding to client requests.

Client

The HTTP client provides the capability for initiating contact with a remote HTTP service. The API it provides includes functions for the standard HTTP methods, forwarding a received request and sending requests using custom HTTP verbs.

FailoverClient

An HTTP client endpoint which provides failover support over multiple HTTP clients.

HttpCachingClient

An HTTP caching client implementation which takes an HttpActions instance and wraps it with an HTTP caching layer.

HttpCaller

Provides the HTTP actions for interacting with an HTTP server. Apart from the standard HTTP methods, forward() and execute() functions are provided. More complex and specific endpoint types can be created by wrapping this generic HTTP actions implementation.

HttpClient

Provides the HTTP remote functions for interacting with an HTTP server. Apart from the standard HTTP methods, forward() and execute() functions are provided. More complex and specific endpoint types can be created by wrapping this generic HTTP remote functions implementation.

HttpSecureClient

Provides secure HTTP remote functions for interacting with HTTP endpoints. This will make use of the authentication schemes configured in the HTTP client endpoint to secure the HTTP requests.

LoadBalanceClient

LoadBalanceClient endpoint provides load balancing functionality over multiple HTTP clients.

RedirectClient

Provides redirect functionality for HTTP client remote functions.

RetryClient

Provides the HTTP remote functions for interacting with an HTTP endpoint. This is created by wrapping the HTTP client to provide retrying over HTTP requests.

WebSocketCaller

Represents a WebSocket caller.

WebSocketClient

Represents a WebSocket client endpoint.

Functions

Function Description
createHttpCachingClient

Creates an HTTP client capable of caching HTTP responses.

createHttpSecureClient

Creates an HTTP client capable of securing HTTP requests with authentication.

decode

Decodes the given URL.

encode

Encodes the given URL.

extractBasicAuthHeaderValue

Extracts the basic authentication header value from the request.

invokeEndpoint

The HEAD remote function implementation of the Circuit Breaker. This wraps the head() function of the underlying HTTP remote function provider.

parseHeader

Parses the given header value to extract its value and parameter map.

Type Definitions

Type Values Description
AuthScheme OAUTH2 | JWT_AUTH | BASIC_AUTH
CachingPolicy RFC_7234 | CACHE_CONTROL_AND_VALIDATORS

Used for configuring the caching behaviour. Setting the policy field in the CacheConfig record allows the user to control the caching behaviour.

Chunking CHUNKING_NEVER | CHUNKING_AUTO | CHUNKING_ALWAYS

Defines the possible values for the chunking configuration in HTTP services and clients.

AUTO: If the payload is less than 8KB, content-length header is set in the outbound request/response, otherwise chunking header is set in the outbound request/response ALWAYS: Always set chunking header in the response NEVER: Never set the chunking header even if the payload is larger than 8KB in the outbound request/response

CircuitState CB_OPEN_STATE | CB_HALF_OPEN_STATE | CB_CLOSED_STATE

A finite type for modeling the states of the Circuit Breaker. The Circuit Breaker starts in the CLOSED state. If any failure thresholds are exceeded during execution, the circuit trips and goes to the OPEN state. After the specified timeout period expires, the circuit goes to the HALF_OPEN state. If the trial request sent while in the HALF_OPEN state succeeds, the circuit goes back to the CLOSED state.

Compression COMPRESSION_NEVER | COMPRESSION_AUTO | COMPRESSION_ALWAYS

Options to compress using gzip or deflate.

AUTO: When service behaves as a HTTP gateway inbound request/response accept-encoding option is set as the outbound request/response accept-encoding/content-encoding option ALWAYS: Always set accept-encoding/content-encoding in outbound request/response NEVER: Never set accept-encoding/content-encoding header in outbound request/response

CredentialBearer POST_BODY_BEARER | AUTH_HEADER_BEARER

Specifies how the authentication credentials should be sent when using the refresh token to refresh the access token

HttpOperation HTTP_PUT | HTTP_POST | HTTP_PATCH | HTTP_OPTIONS | HTTP_NONE | HTTP_HEAD | HTTP_GET | HTTP_FORWARD | HTTP_DELETE

Defines the HTTP operations related to circuit breaker, failover and load balancer.

FORWARD: Forward the specified payload GET: Request a resource POST: Create a new resource DELETE: Deletes the specified resource OPTIONS: Request communication options available PUT: Replace the target resource PATCH: Apply partial modification to the resource HEAD: Identical to GET but no resource body should be returned NONE: No operation should be performed

KeepAlive KEEPALIVE_NEVER | KEEPALIVE_AUTO | KEEPALIVE_ALWAYS

Defines the possible values for the keep-alive configuration in service and client endpoints.

RedirectCode REDIRECT_USE_PROXY_305 | REDIRECT_TEMPORARY_REDIRECT_307 | REDIRECT_SEE_OTHER_303 | REDIRECT_PERMANENT_REDIRECT_308 | REDIRECT_NOT_MODIFIED_304 | REDIRECT_MULTIPLE_CHOICES_300 | REDIRECT_MOVED_PERMANENTLY_301 | REDIRECT_FOUND_302

Defines the HTTP redirect codes as a type.

Annotations

Name Attaches To Data Type Description
ResourceConfig resource HttpResourceConfig

The annotation which is used to configure an HTTP resource.

ServiceConfig service HttpServiceConfig

The annotation which is used to configure an HTTP service.

WebSocketServiceConfig service WSServiceConfig

The annotation which is used to configure a WebSocket service.

public type AuthCacheConfig

Provides a set of configurations for controlling the authorization caching behaviour of the endpoint.

Field Name Data Type Default Value Description
enabled boolean true

Specifies whether authorization caching is enabled. Caching is enabled by default.

capacity int 100

The capacity of the cache

expiryTimeMillis int 5 * 1000

The number of milliseconds to keep an entry in the cache

evictionFactor float 1.0

The fraction of entries to be removed when the cache is full. The value should be between 0 (exclusive) and 1 (inclusive).

public type AuthConfig

AuthConfig record can be used to configure the authentication mechanism used by the HTTP endpoint.

Field Name Data Type Default Value Description
scheme Basic|OAuth2|JWT

Scheme of the configuration (Basic, OAuth2, JWT etc.)

username string

Username for Basic authentication

password string

Password for Basic authentication

accessToken string

Access token for OAuth2 authentication

refreshToken string

Refresh token for OAuth2 authentication

refreshUrl string

Refresh token URL for OAuth2 authentication

consumerKey string

Consumer key for OAuth2 authentication

consumerSecret string

Consumer secret for OAuth2 authentication

tokenUrl string

Token URL for OAuth2 authentication

clientId string

Clietnt ID for OAuth2 authentication

clientSecret string

Client secret for OAuth2 authentication

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER AUTH_HEADER_BEARER

How client authentication is sent to refresh access token (AuthHeaderBearer, PostBodyBearer)

scopes string[] []

Scope of the access request

public type AuthProvider

Configuration for authentication providers.

Field Name Data Type Default Value Description
scheme string

Authentication scheme

id string

Authentication provider instance id

authStoreProvider string

Authentication store provider (file, LDAP, etc.) implementation

authStoreProviderConfig auth:LdapAuthProviderConfig? null

Auth store related configurations

issuer string

Identifier of the token issuer

audience string

Identifier of the token recipients

trustStore http:TrustStore? null

Trustore configurations

certificateAlias string

Token signed key alias

clockSkew int 0

Time in seconds to mitigate clock skew

keyStore http:KeyStore? null

KeyStore instance providing key store related configurations

keyAlias string

The Key Alias

keyPassword string

The Key password

expTime int 0

Expiry time

signingAlg string

The signing algorithm which is used to sign the JWT token

propagateJwt boolean false

true if propagating authentication info as JWT

public type Authentication

Can be used for enabling/disabling authentication in an HTTP service.

Field Name Data Type Default Value Description
enabled boolean false

Specifies whether authentication is enabled

public type Bucket

Represents a discrete sub-part of the time window (Bucket).

Field Name Data Type Default Value Description
totalCount int 0

Total number of requests received during the sub-window time frame

failureCount int 0

Number of failed requests during the sub-window time frame

rejectedCount int 0

Number of rejected requests during the sub-window time frame

lastUpdatedTime time:Time

The time that the Bucket is last updated.

public type CacheConfig

Provides a set of configurations for controlling the caching behaviour of the endpoint.

Field Name Data Type Default Value Description
enabled boolean true

Specifies whether HTTP caching is enabled. Caching is enabled by default.

isShared boolean false

Specifies whether the HTTP caching layer should behave as a public cache or a private cache

expiryTimeMillis int 86400

The number of milliseconds to keep an entry in the cache

capacity int 8388608

The capacity of the cache

evictionFactor float 0.2

The fraction of entries to be removed when the cache is full. The value should be between 0 (exclusive) and 1 (inclusive).

policy CACHE_CONTROL_AND_VALIDATORS|RFC_7234 CACHE_CONTROL_AND_VALIDATORS

Gives the user some control over the caching behaviour. By default, this is set to CACHE_CONTROL_AND_VALIDATORS. The default behaviour is to allow caching only when the cache-control header and either the etag or last-modified header are present.

public type CircuitBreakerConfig

Provides a set of configurations for controlling the behaviour of the Circuit Breaker.

Field Name Data Type Default Value Description
rollingWindow http:RollingWindow {}

RollingWindow options of the CircuitBreaker

failureThreshold float 0.0

The threshold for request failures. When this threshold exceeds, the circuit trips. The threshold should be a value between 0 and 1.

resetTimeMillis int 0

The time period(in milliseconds) to wait before attempting to make another request to the upstream service

statusCodes int[] []

Array of HTTP response status codes which are considered as failures

public type CircuitBreakerInferredConfig

Derived set of configurations from the `CircuitBreakerConfig`.

Field Name Data Type Default Value Description
failureThreshold float 0.0

The threshold for request failures. When this threshold exceeds, the circuit trips. The threshold should be a value between 0 and 1

resetTimeMillis int 0

The time period(in milliseconds) to wait before attempting to make another request to the upstream service

statusCodes boolean[] []

Array of HTTP response status codes which are considered as failures

noOfBuckets int 0

Number of buckets derived from the RollingWindow

rollingWindow http:RollingWindow {}

RollingWindow options provided in the CircuitBreakerConfig

public type CircuitHealth

Maintains the health of the Circuit Breaker.

Field Name Data Type Default Value Description
lastRequestSuccess boolean false

Whether last request is success or not

totalRequestCount int 0

Total request count received within the RollingWindow

lastUsedBucketId int 0

ID of the last bucket used in Circuit Breaker calculations

startTime time:Time time:currentTime()

Circuit Breaker start time

lastRequestTime time:Time

The time that the last request received

lastErrorTime time:Time

The time that the last error occurred

lastForcedOpenTime time:Time

The time that circuit forcefully opened at last

totalBuckets http:Bucket[] []

The discrete time buckets into which the time window is divided

public type ClientEndpointConfig

Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint.

Field Name Data Type Default Value Description
circuitBreaker http:CircuitBreakerConfig? null

Configurations associated with Circuit Breaker behaviour

timeoutMillis int 60000

The maximum time to wait (in milliseconds) for a response before closing the connection

keepAlive AUTO|ALWAYS|NEVER KEEPALIVE_AUTO

Specifies whether to reuse a connection for multiple requests

chunking AUTO|ALWAYS|NEVER AUTO

The chunking behaviour of the request

httpVersion string 1.1

The HTTP version understood by the client

forwarded string disable

The choice of setting forwarded/x-forwarded header

followRedirects http:FollowRedirects? null

Configurations associated with Redirection

retryConfig http:RetryConfig? null

Configurations associated with Retry

proxy http:ProxyConfig? null

Proxy server related options

connectionThrottling http:ConnectionThrottling? {}

Configurations for connection throttling

secureSocket http:SecureSocket? null

SSL/TLS related options

cache http:CacheConfig {}

HTTP caching related configurations

compression AUTO|ALWAYS|NEVER COMPRESSION_AUTO

Specifies the way of handling compression (accept-encoding) header

auth http:AuthConfig? null

HTTP authentication related configurations

public type CompressionConfig

A record for providing configurations for content compression.

Field Name Data Type Default Value Description
enable AUTO|ALWAYS|NEVER COMPRESSION_AUTO

The status of compression

contentTypes string[] []

Content types which are allowed for compression

public type ConnectionThrottling

Provides configurations for throttling connections of the endpoint.

Field Name Data Type Default Value Description
maxActiveConnections int -1

Maximum number of active connections allowed for the endpoint. The default value, -1, indicates that the number of connections are not restricted.

waitTime int 60000

Maximum waiting time for a request to grab an idle connection from the client

maxActiveStreamsPerConnection int 20000

Maximum number of active streams allowed per an HTTP/2 connection

public type CorsConfig

Configurations for CORS support.

Field Name Data Type Default Value Description
allowHeaders string[] []

The array of allowed headers by the service

allowMethods string[] []

The array of allowed methods by the service

allowOrigins string[] []

The array of origins with which the response is shared by the service

exposeHeaders string[] []

The whitelisted headers which clients are allowed to access

allowCredentials boolean false

Specifies whether credentials are required to access the service

maxAge int -1

The maximum duration to cache the preflight from client side

public type FailoverClientEndpointConfiguration

Provides a set of HTTP related configurations and failover related configurations.

Field Name Data Type Default Value Description
circuitBreaker http:CircuitBreakerConfig? null

Circuit Breaker behaviour configurations

timeoutMillis int 60000

The maximum time to wait (in milliseconds) for a response before closing the connection

httpVersion string 1.1

The HTTP version supported by the endpoint

forwarded string disable

The choice of setting forwarded/x-forwarded header

keepAlive AUTO|ALWAYS|NEVER KEEPALIVE_AUTO

Specifies whether to reuse a connection for multiple requests

chunking AUTO|ALWAYS|NEVER AUTO

The chunking behaviour of the request

followRedirects http:FollowRedirects? null

Redirect related options

retryConfig http:RetryConfig? null

Retry related options

proxy http:ProxyConfig? null

Proxy related options

connectionThrottling http:ConnectionThrottling? null

The configurations for controlling the number of connections allowed concurrently

targets http:TargetService[] []

The upstream HTTP endpoints among which the incoming HTTP traffic load should be sent on failover

cache http:CacheConfig {}

The configurations for controlling the caching behaviour

compression AUTO|ALWAYS|NEVER COMPRESSION_AUTO

Specifies the way of handling compression (accept-encoding) header

auth http:AuthConfig? null

HTTP authentication releated configurations

failoverCodes int[] [501, 502, 503, 504]

Array of HTTP response status codes for which the failover behaviour should be triggered

intervalMillis int 0

Failover delay interval in milliseconds

public type FailoverConfig

Provides a set of configurations for controlling the failover behaviour of the endpoint.

Field Name Data Type Default Value Description
failoverCodes int[] []

Array of HTTP response status codes for which the failover mechanism triggers

interval int 0

Failover delay interval in milliseconds

public type FailoverInferredConfig

Inferred failover configurations passed into the failover client.

Field Name Data Type Default Value Description
failoverClientsArray http:Client[] []

Array of HTTP Clients that needs to be Failover

failoverCodesIndex boolean[] []

An indexed array of HTTP response status codes for which the failover mechanism triggers

failoverInterval int 0

Failover delay interval in milliseconds

public type FollowRedirects

Provides configurations for controlling the endpoint's behaviour in response to HTTP redirect related responses.

Field Name Data Type Default Value Description
enabled boolean false

Enable/disable redirection

maxCount int 5

Maximum number of redirects to follow

public type HttpResourceConfig

Configuration for an HTTP resource.

Field Name Data Type Default Value Description
methods string[] []

The array of allowed HTTP methods

path string

The path of resource

body string

Inbound request entity body name which declared in signature

consumes string[] []

The media types which are accepted by resource

produces string[] []

The media types which are produced by resource

cors http:CorsConfig {}

The cross origin resource sharing configurations for the resource. If not set, the resource will inherit the CORS behaviour of the enclosing service.

transactionInfectable boolean true

Allow to participate in the distributed transactions if value is true

webSocketUpgrade http:WebSocketUpgradeConfig? null

Annotation to define HTTP to WebSocket upgrade

authConfig http:ListenerAuthConfig? null

Authentication Configs to secure the resource

public type HttpServiceConfig

Contains the configurations for an HTTP service.

Field Name Data Type Default Value Description
endpoints http:Listener[] []

An array of endpoints the service would be attached to

host string b7a.default

Domain name of the service

basePath string

Service base path

compression http:CompressionConfig {}

The status of compression

chunking AUTO|ALWAYS|NEVER CHUNKING_AUTO

Configures the chunking behaviour for the service

cors http:CorsConfig {}

The cross origin resource sharing configurations for the service

versioning http:Versioning {}

The version of the service to be used

authConfig http:ListenerAuthConfig? {}

Authentication configurations for securing the service

public type HttpTimeoutError

Defines a timeout error occurred during service invocation.

Field Name Data Type Default Value Description
message string

An explanation on what went wrong

cause error? null

The error which caused the HttpTimeoutError

statusCode int 0

HTTP status code

public type KeyStore

A record for providing key store related configurations.

Field Name Data Type Default Value Description
path string

Path to the key store file

password string

Key store password

public type ListenerAuthConfig

Configures the authentication scheme for a service or a resource.

Field Name Data Type Default Value Description
authentication http:Authentication? null

Enables/disables authentication

authProviders string[]? null

Array of authentication provider IDs

scopes string[]? null

Array of scopes

public type LoadBalanceActionErrorData

Represents an error occurred in an remote function of the Load Balance connector.

Field Name Data Type Default Value Description
message string

An error message explaining about the error

statusCode int 0

HTTP status code of the LoadBalanceActionError

httpActionErr error[] []

Array of errors occurred at each endpoint

public type LoadBalanceClientEndpointConfiguration

The configurations related to the load balance client endpoint.

Field Name Data Type Default Value Description
circuitBreaker http:CircuitBreakerConfig? null

Circuit Breaker configuration

timeoutMillis int 60000

The maximum time to wait (in milli seconds) for a response before closing the connection

httpVersion string 1.1

The HTTP version to be used to communicate with the endpoint

forwarded string disable

The choice of setting forwarded/x-forwarded header

keepAlive AUTO|ALWAYS|NEVER KEEPALIVE_AUTO

Specifies whether to keep the connection alive (or not) for multiple request/response pairs

chunking AUTO|ALWAYS|NEVER AUTO

The chunking behaviour of the request

followRedirects http:FollowRedirects? null

Redirect related options

retryConfig http:RetryConfig? null

Retry related options

proxy http:ProxyConfig? null

Proxy related options

connectionThrottling http:ConnectionThrottling? null

The configurations for controlling the number of connections allowed concurrently

targets http:TargetService[] []

The upstream HTTP endpoints among which the incoming HTTP traffic load should be distributed

cache http:CacheConfig {}

The configurations for controlling the caching behaviour

compression AUTO|ALWAYS|NEVER COMPRESSION_AUTO

Specifies the way of handling compression (accept-encoding) header

auth http:AuthConfig? null

HTTP authentication releated configurations

lbRule http:LoadBalancerRule? null

LoadBalancing rule

failover boolean true

Configuration for load balancer whether to fail over in case of a failure

public type Local

Presents a read-only view of the local address.

Field Name Data Type Default Value Description
host string

The local host name/IP

port int 0

The local port

public type Protocols

A record for configuring SSL/TLS protocol and version to be used.

Field Name Data Type Default Value Description
name string

SSL Protocol to be used (e.g.: TLS1.2)

versions string[] []

SSL/TLS protocols to be enabled (e.g.: TLSv1,TLSv1.1,TLSv1.2)

public type ProxyConfig

Proxy server configurations to be used with the HTTP client endpoint.

Field Name Data Type Default Value Description
host string

Host name of the proxy server

port int 0

Proxy server port

userName string

Proxy server username

password string

proxy server password

public type Remote

Presents a read-only view of the remote address.

Field Name Data Type Default Value Description
host string

The remote host name/IP

port int 0

The remote port

public type RequestLimits

Configures limits for requests. If these limits are violated, the request is rejected.

Field Name Data Type Default Value Description
maxUriLength int -1

Maximum allowed length for a URI. Exceeding this limit will result in a 414 - URI Too Long response.

maxHeaderSize int -1

Maximum allowed size for headers. Exceeding this limit will result in a 413 - Payload Too Large response.

maxEntityBodySize int -1

Maximum allowed size for the entity body. Exceeding this limit will result in a 413 - Payload Too Large response.

public type RetryConfig

Provides configurations for controlling the retry behaviour in failure scenarios.

Field Name Data Type Default Value Description
count int 0

Number of retry attempts before giving up

interval int 0

Retry interval in milliseconds

backOffFactor float 0.0

Multiplier of the retry interval to exponentailly increase retry interval

maxWaitInterval int 0

Maximum time of the retry interval in milliseconds

statusCodes int[] []

HTTP response status codes which are considered as failures

public type RetryInferredConfig

Derived set of configurations from the `RetryConfig`.

Field Name Data Type Default Value Description
count int 0

Number of retry attempts before giving up

interval int 0

Retry interval in milliseconds

backOffFactor float 0.0

Multiplier of the retry interval to exponentailly increase retry interval

maxWaitInterval int 0

Maximum time of the retry interval in milliseconds

statusCodes boolean[] []

HTTP response status codes which are considered as failures

public type RollingWindow

Represents a rolling window in the Circuit Breaker.

Field Name Data Type Default Value Description
requestVolumeThreshold int 10

Minimum number of requests in a RollingWindow that will trip the circuit.

timeWindowMillis int 60000

Time period in milliseconds for which the failure threshold is calculated

bucketSizeMillis int 10000

The granularity at which the time window slides. This is measured in milliseconds.

public type SecureSocket

Provides configurations for facilitating secure communication with a remote HTTP endpoint.

Field Name Data Type Default Value Description
trustStore http:TrustStore? null

Configurations associated with TrustStore

keyStore http:KeyStore? null

Configurations associated with KeyStore

certFile string

A file containing the certificate of the client

keyFile string

A file containing the private key of the client

keyPassword string

Password of the private key if it is encrypted

trustedCertFile string

A file containing a list of certificates or a single certificate that the client trusts

protocol http:Protocols? null

SSL/TLS protocol related options

certValidation http:ValidateCert? null

Certificate validation against CRL or OCSP related options

ciphers string[] []

List of ciphers to be used eg: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

verifyHostname boolean true

Enable/disable host name verification

shareSession boolean true

Enable/disable new SSL session creation

ocspStapling boolean false

Enable/disable OCSP stapling

public type ServiceEndpointConfiguration

Provides a set of configurations for HTTP service endpoints.

Field Name Data Type Default Value Description
host string 0.0.0.0

The host name/IP of the endpoint

keepAlive AUTO|ALWAYS|NEVER KEEPALIVE_AUTO

Can be set to either KEEPALIVE_AUTO, which respects the connection header, or KEEPALIVE_ALWAYS, which always keeps the connection alive, or KEEPALIVE_NEVER, which always closes the connection

secureSocket http:ServiceSecureSocket? null

The SSL configurations for the service endpoint. This needs to be configured in order to communicate through HTTPS.

httpVersion string 1.1

Highest HTTP version supported by the endpoint

requestLimits http:RequestLimits? null

Configures the parameters for request validation

filters http:Filter[] []

If any pre-processing needs to be done to the request before dispatching the request to the resource, filters can applied

timeoutMillis int DEFAULT_LISTENER_TIMEOUT

Period of time in milliseconds that a connection waits for a read/write operation. Use value 0 to disable timeout

maxPipelinedRequests int MAX_PIPELINED_REQUESTS

Defines the maximum number of requests that can be processed at a given time on a single connection. By default 10 requests can be pipelined on a single cinnection and user can change this limit appropriately. This will be applicable only for HTTP 1.1

authProviders http:AuthProvider[]? null

The array of authentication providers which are used to authenticate the users

positiveAuthzCache http:AuthCacheConfig {}

Caching configurations for positive authorizations

negativeAuthzCache http:AuthCacheConfig {}

Caching configurations for negative authorizations

public type ServiceOcspStapling

A record for providing configurations for certificate revocation status checks.

Field Name Data Type Default Value Description
enable boolean false

The status of OCSP stapling

cacheSize int 0

Maximum size of the cache

cacheValidityPeriod int 0

The time period for which a cache entry is valid

public type ServiceSecureSocket

Configures the SSL/TLS options to be used for HTTP service.

Field Name Data Type Default Value Description
trustStore http:TrustStore? null

Configures the trust store to be used

keyStore http:KeyStore? null

Configures the key store to be used

certFile string

A file containing the certificate of the server

keyFile string

A file containing the private key of the server

keyPassword string

Password of the private key if it is encrypted

trustedCertFile string

A file containing a list of certificates or a single certificate that the server trusts

protocol http:Protocols? null

SSL/TLS protocol related options

certValidation http:ValidateCert? null

Certificate validation against CRL or OCSP related options

ciphers string[] [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256]

List of ciphers to be used (e.g.: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA)

sslVerifyClient string

The type of client certificate verification

shareSession boolean true

Enable/disable new SSL session creation

ocspStapling http:ServiceOcspStapling? null

Enable/disable OCSP stapling

public type TargetService

Represents a single service and its related configurations.

Field Name Data Type Default Value Description
url string

URL of the target service

secureSocket http:SecureSocket? null

Configurations for secure communication with the remote HTTP endpoint

public type TrustStore

A record for providing trust store related configurations.

Field Name Data Type Default Value Description
path string

Path to the trust store file

password string

Trust store password

public type ValidateCert

A record for providing configurations for certificate revocation status checks.

Field Name Data Type Default Value Description
enable boolean false

The status of validateCertEnabled

cacheSize int 0

Maximum size of the cache

cacheValidityPeriod int 0

The time period for which a cache entry is valid

public type Versioning

Configurations for service versioning.

Field Name Data Type Default Value Description
pattern string v{major}.{minor}

Expected version pattern in the request URL

allowNoVersion boolean false

Allow requests with missing version path segment in the URL to be dispatched

matchMajorVersion boolean false

Allow requests with only the major version specified in the URL to be dispatched

public type WSServiceConfig

Configurations for a WebSocket service.

Field Name Data Type Default Value Description
endpoints http:Listener[] []

An array of endpoints the service would be attached to

path string

Path of the WebSocket service

subProtocols string[] []

Negotiable sub protocol by the service

idleTimeoutInSeconds int 0

Idle timeout for the client connection. This can be triggered by putting an onIdleTimeout resource in the WebSocket service.

maxFrameSize int 0

The maximum payload size of a WebSocket frame in bytes

public type WebSocketClientEndpointConfig

Configuration struct for WebSocket client endpoint.

Field Name Data Type Default Value Description
callbackService service? null

The callback service for the client. Resources in this service gets called on receipt of messages from the server.

subProtocols string[] []

Negotiable sub protocols for the client

customHeaders map<string> {}

Custom headers which should be sent to the server

idleTimeoutInSeconds int -1

Idle timeout of the client. Upon timeout, onIdleTimeout resource in the client service will be triggered (if there is one defined)

readyOnConnect boolean true

true if the client is ready to recieve messages as soon as the connection is established. This is true by default. If changed to false the function ready() of the WebSocketClientneeds to be called once to start receiving messages.

secureSocket http:SecureSocket? null

SSL/TLS related options

public type WebSocketUpgradeConfig

Configures the HTTP to WebSocket upgrade.

Field Name Data Type Default Value Description
upgradePath string

Path which is used to upgrade from HTTP to WebSocket

upgradeService service

WebSocket service which should be used after a successful upgrade

public function createHttpCachingClient(string url, http:ClientEndpointConfig config, http:CacheConfig cacheConfig) returns (Client | error<>)

Creates an HTTP client capable of caching HTTP responses.

Parameter Name Data Type Default Value Description
url string

The URL of the HTTP endpoint to connect to

config http:ClientEndpointConfig

The configurations for the client endpoint associated with the caching client

cacheConfig http:CacheConfig

The configurations for the HTTP cache to be used with the caching client

Return Type Description
Client | error<>

An HttpCachingClient instance which wraps the base Client with a caching layer

public function createHttpSecureClient(string url, http:ClientEndpointConfig config) returns (Client | error<>)

Creates an HTTP client capable of securing HTTP requests with authentication.

Parameter Name Data Type Default Value Description
url string

Base URL

config http:ClientEndpointConfig

Client endpoint configurations

Return Type Description
Client | error<>

Created secure HTTP client

public function decode(string url, string charset) returns (string | error<>)

Decodes the given URL.

Parameter Name Data Type Default Value Description
url string

URL to be decoded

charset string

Charactor set that URL to be decoded from

Return Type Description
string | error<>

The string Value of the decoded url or an error that occured during decoding

public function encode(string url, string charset) returns (string | error<>)

Encodes the given URL.

Parameter Name Data Type Default Value Description
url string

URL to be encoded

charset string

Charactor set that URL to be encoded in

Return Type Description
string | error<>

The string Value of the encoded url or an error that occured during encoding

public function extractBasicAuthHeaderValue(http:Request req) returns (string | null)

Extracts the basic authentication header value from the request.

Parameter Name Data Type Default Value Description
req http:Request

Request instance

Return Type Description
string | null

Value of the basic authentication header, or nil if not found

public function invokeEndpoint(string path, http:Request outRequest, FORWARD|GET|POST|DELETE|OPTIONS|PUT|PATCH|HEAD|NONE requestAction, http:Client httpClient) returns (Response | error<>)

The HEAD remote function implementation of the Circuit Breaker. This wraps the head() function of the underlying HTTP remote function provider.

Parameter Name Data Type Default Value Description
path string

Resource path

outRequest http:Request

A Request struct

requestAction FORWARD|GET|POST|DELETE|OPTIONS|PUT|PATCH|HEAD|NONE

HttpOperation related to the request

httpClient http:Client

HTTP client which uses to call the relavant functions

Return Type Description
Response | error<>

The response for the request or an error if failed to establish communication with the upstream server

public function parseHeader(string headerValue) returns ((string,map<any>) | error<>)

Parses the given header value to extract its value and parameter map.

Parameter Name Data Type Default Value Description
headerValue string

The header value

Return Type Description
(string,map) | error<>

Returns a tuple containing the value and its parameter map

public type AuthHandlerRegistry object

Representation of the Http Auth Handler Registry.

  • <AuthHandlerRegistry> add(string id, http:HttpAuthnHandler authnHandler)

    Add an HttpAuthnHandler to HttpAuthHandlerRegistry

    Parameter Name Data Type Default Value Description
    id string

    Auth provider id

    authnHandler http:HttpAuthnHandler

    HttpAuthnHandler instance

  • <AuthHandlerRegistry> get(string id) returns (HttpAuthnHandler)

    Retrieves an HttpAuthnHandler from HttpAuthHandlerRegistry which corresponds to the given id

    Parameter Name Data Type Default Value Description
    id string

    Auth provider id

    Return Type Description
    HttpAuthnHandler

    HttpAuthnHandler instance or nil if not found

  • <AuthHandlerRegistry> getAll() returns (map<HttpAuthnHandler>)

    Retrieve the HttpAuthnHandler map

    Return Type Description
    map

    map of HttpAuthnHandler

  • <AuthHandlerRegistry> remove(string id)

    Removes a specific authn handler from the HttpAuthnHandler map

    Parameter Name Data Type Default Value Description
    id string
  • <AuthHandlerRegistry> clear()

    Removes all authn handler from the HttpAuthnHandler map

public type AuthnFilter object

Representation of the Authentication filter.

Field Name Data Type Default Value Description
authnHandlerChain http:AuthnHandlerChain

The Authentication handler chain

  • <AuthnFilter> __init(http:AuthnHandlerChain authnHandlerChain)

    Parameter Name Data Type Default Value Description
    authnHandlerChain http:AuthnHandlerChain
  • <AuthnFilter> filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns (boolean)

    Request filter method which attempts to authenticated the request.

    Parameter Name Data Type Default Value Description
    caller http:Caller

    Caller for outbound HTTP responses

    request http:Request

    An inboud HTTP request message

    context http:FilterContext

    A filter context

    Return Type Description
    boolean

    True if the filter succeeds

  • <AuthnFilter> filterResponse(http:Response response, http:FilterContext context) returns (boolean)

    Parameter Name Data Type Default Value Description
    response http:Response
    context http:FilterContext
    Return Type Description
    boolean

public type AuthnHandlerChain object

Representation of Authentication handler chain

  • <AuthnHandlerChain> __init(http:AuthHandlerRegistry authHandlerRegistry)

    Parameter Name Data Type Default Value Description
    authHandlerRegistry http:AuthHandlerRegistry
  • <AuthnHandlerChain> handle(http:Request req) returns (boolean)

    Tries to authenticate against any one of the available authentication handlers

    Parameter Name Data Type Default Value Description
    req http:Request

    Request instance

    Return Type Description
    boolean

    true if authenticated successfully, else false

  • <AuthnHandlerChain> handleWithSpecificAuthnHandlers(string[] authProviderIds, http:Request req) returns (boolean)

    Tries to authenticate against a specifc sub set of the authentication handlers, using the given array of auth provider ids

    Parameter Name Data Type Default Value Description
    authProviderIds string[]

    array of auth provider ids

    req http:Request

    Request instance

    Return Type Description
    boolean

    true if authenticated successfully, else false

public type AuthzFilter object

Representation of the Authorization filter

Field Name Data Type Default Value Description
authzHandler http:HttpAuthzHandler

HttpAuthzHandler instance for handling authorization

  • <AuthzFilter> __init(http:HttpAuthzHandler authzHandler)

    Parameter Name Data Type Default Value Description
    authzHandler http:HttpAuthzHandler
  • <AuthzFilter> filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns (boolean)

    Filter function implementation which tries to authorize the request

    Parameter Name Data Type Default Value Description
    caller http:Caller

    Caller for outbound HTTP responses

    request http:Request

    Request instance

    context http:FilterContext

    FilterContext instance

    Return Type Description
    boolean

    A flag to indicate if the request flow should be continued(true) or aborted(false), a code and a message

  • <AuthzFilter> filterResponse(http:Response response, http:FilterContext context) returns (boolean)

    Parameter Name Data Type Default Value Description
    response http:Response
    context http:FilterContext
    Return Type Description
    boolean

public type CircuitBreakerClient object

A Circuit Breaker implementation which can be used to gracefully handle network failures.

Field Name Data Type Default Value Description
url string

The URL of the target service

config http:ClientEndpointConfig

The configurations of the client endpoint associated with this CircuitBreaker instance

circuitBreakerInferredConfig http:CircuitBreakerInferredConfig

Configurations derived from CircuitBreakerConfig

httpClient http:Client

The underlying HttpActions instance which will be making the actual network calls

circuitHealth http:CircuitHealth

The circuit health monitor

currentCircuitState OPEN|HALF_OPEN|CLOSED CB_CLOSED_STATE

The current state the cicuit is in

  • <CircuitBreakerClient> __init(string url, http:ClientEndpointConfig config, http:CircuitBreakerInferredConfig circuitBreakerInferredConfig, http:Client httpClient, http:CircuitHealth circuitHealth)

    A Circuit Breaker implementation which can be used to gracefully handle network failures.

    Parameter Name Data Type Default Value Description
    url string

    The URL of the target service

    config http:ClientEndpointConfig

    The configurations of the client endpoint associated with this CircuitBreaker instance

    circuitBreakerInferredConfig http:CircuitBreakerInferredConfig

    Configurations derived from CircuitBreakerConfig

    httpClient http:Client

    The underlying HttpActions instance which will be making the actual network calls

    circuitHealth http:CircuitHealth

    The circuit health monitor

  • <CircuitBreakerClient> post(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The POST remote function implementation of the Circuit Breaker. This wraps the post() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> head(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The HEAD remote function implementation of the Circuit Breaker. This wraps the head() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? null

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> put(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The PUT remote function implementation of the Circuit Breaker. This wraps the put() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> execute(string httpVerb, string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    This wraps the post() function of the underlying HTTP remote functions provider. The execute() function can be used to invoke an HTTP call with the given HTTP verb.

    Parameter Name Data Type Default Value Description
    httpVerb string

    HTTP verb to be used for the request

    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> patch(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The PATCH remote function implementation of the Circuit Breaker. This wraps the patch() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> delete(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The DELETE remote function implementation of the Circuit Breaker. This wraps the delete() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    A Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> get(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The GET remote function implementation of the Circuit Breaker. This wraps the get() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? null

    An optional HTTP request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> options(string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (Response | error<>)

    The OPTIONS remote function implementation of the Circuit Breaker. This wraps the options() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? null

    An optional HTTP Request or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> forward(string path, http:Request request) returns (Response | error<>)

    This wraps the forward() function of the underlying HTTP remote functions provider. The Forward remote function can be used to forward an incoming request to an upstream service as it is.

    Parameter Name Data Type Default Value Description
    path string

    Resource path

    request http:Request

    A Request struct

    Return Type Description
    Response | error<>

    The response for the request or an error if failed to establish communication with the upstream server

  • <CircuitBreakerClient> submit(string httpVerb, string path, http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]? message) returns (HttpFuture | error<>)

    Circuit breaking not supported. Defaults to the submit() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    httpVerb string

    The HTTP verb value

    path string

    The resource path

    message http:Request|string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]?

    An HTTP outbound request message or any payload of type string, xml, json, byte[], io:ReadableByteChannel or mime:Entity[]

    Return Type Description
    HttpFuture | error<>

    An HttpFuture that represents an asynchronous service invocation, or an error if the submission fails

  • <CircuitBreakerClient> getResponse(http:HttpFuture httpFuture) returns (Response | error<>)

    Circuit breaking not supported. Defaults to the getResponse() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    httpFuture http:HttpFuture

    The HttpFuture related to a previous asynchronous invocation

    Return Type Description
    Response | error<>

    An HTTP response message, or an error if the invocation fails

  • <CircuitBreakerClient> hasPromise(http:HttpFuture httpFuture) returns (boolean)

    Circuit breaking not supported. Defaults to the hasPromise() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    httpFuture http:HttpFuture

    The HttpFuture relates to a previous asynchronous invocation

    Return Type Description
    boolean

    A boolean that represents whether a PushPromise exists

  • <CircuitBreakerClient> getNextPromise(http:HttpFuture httpFuture) returns (PushPromise | error<>)

    Circuit breaking not supported. Defaults to the getNextPromise() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    httpFuture http:HttpFuture

    The HttpFuture relates to a previous asynchronous invocation

    Return Type Description
    PushPromise | error<>

    An HTTP PushPromise message, or an error if the invocation fails

  • <CircuitBreakerClient> getPromisedResponse(http:PushPromise promise) returns (Response | error<>)

    Circuit breaking not supported. Defaults to the getPromisedResponse() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    promise http:PushPromise

    The related PushPromise

    Return Type Description
    Response | error<>

    A promised HTTP Response message, or an error if the invocation fails

  • <CircuitBreakerClient> rejectPromise(http:PushPromise promise)

    Circuit breaking not supported. Defaults to the rejectPromise() function of the underlying HTTP remote functions provider.

    Parameter Name Data Type Default Value Description
    promise http:PushPromise

    The PushPromise to be rejected

  • <CircuitBreakerClient> forceClose()

    Force the circuit into a closed state in which it will allow requests regardless of the error percentage until the failure threshold exceeds.

  • <CircuitBreakerClient> forceOpen()

    Force the circuit into a open state in which it will suspend all requests until resetTimeMillis interval exceeds.

  • <CircuitBreakerClient> getCurrentState() returns (CircuitState)

    Provides CircuitState of the circuit breaker.

    Return Type Description
    CircuitState

    The current CircuitState of circuit breaker

public type Filter object

Representation of a HTTP Request Filter. This filter will be applied before the request is dispatched to the relevant resource. Any Filter implementation should be structurally similar to the Filter object.

  • <Filter> filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns (boolean)

    Request filter function. If a false is returned the response should have been sent from this function as it will not be dispatched to the next filter or the resource.

    Parameter Name Data Type Default Value Description
    caller http:Caller

    The http caller

    request http:Request

    An inboud HTTP request message

    context http:FilterContext

    A filter context

    Return Type Description
    boolean

    True if the filter succeeds

  • <Filter> filterResponse(http:Response response, http:FilterContext context) returns (boolean)

    Response filter function. If a false is returned a 500 Internal Server Error would be sent to the client.

    Parameter Name Data Type Default Value Description
    response http:Response

    An outbound HTTP response message

    context http:FilterContext

    A filter context

    Return Type Description
    boolean

    True if the filter succeeds

public type FilterContext object

Representation of request filter Context.

Field Name Data Type Default Value Description
serviceRef service

The service

serviceName string

Name of the service

resourceName string

Name of the resource

attributes map {}

Attributes to share between filters

  • <FilterContext> __init(service serviceRef, string serviceName, string resourceName)

    Parameter Name Data Type Default Value Description
    serviceRef service
    serviceName string