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.

WebSocket

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

There are two types of services for WebSocket. The service of the server has the WebSockerCaller as the resource parameter, and the callback service of the client has WebSocketClient as the resource parameter. 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 received is an HTTP request. To intercept this request and perform 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) {
}

The upgradeService is a server callback service.

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 service of the server.

onText resource: The received text messages are dispatched to this resource.

onBinary resource: The received binary messages are dispatched to this resource.

onPing and onPong resources: The received ping and pong messages are dispatched to these resources respectively.

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

onClose: This resource is dispatched when a close frame with a statusCode and a reason is received.

onError: This resource is dispatched when an error occurs in the WebSocket connection. This will always be preceded by a connection closure with an appropriate 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 The `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.
BasicAuthConfig The `BasicAuthConfig` record can be used to configure Basic Authentication used by the HTTP endpoint.
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.
CachedToken The `CachedToken` stores the values received from the authorization/token server to use them for the latter requests without requesting tokens again.
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.
ClientCredentialsGrantConfig The `ClientCredentialsGrantConfig` record can be used to configue OAuth2 client credentials grant type.
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.
CorsConfig Configurations for CORS support.
DirectTokenConfig The `DirectTokenConfig` record configures the access token directly.
DirectTokenRefreshConfig The `DirectTokenRefreshConfig` record passes the configurations for refreshing the access token for the grant type of the direct token grant type.
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.
JwtAuthConfig The `JwtAuthConfig` record can be used to configure JWT based authentication used by the HTTP endpoint.
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.
MutualSslHandshake A record for providing mutual ssl handshake results.
OAuth2AuthConfig The `OAuth2AuthConfig` record can be used to configure OAuth2 based authentication used by the HTTP endpoint.
PasswordGrantConfig The `PasswordGrantConfig` record can be used to configue OAuth2 password grant type
PoolConfiguration Configurations for managing HTTP client connection pool.
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.
RefreshConfig The `RefreshConfig` record can be used to pass the configurations for refreshing the access token of password grant type.
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 retrying behavior 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.
ValidateCert A record for providing configurations for certificate revocation status checks.
Versioning Configurations for service versioning.
WSServiceConfig Configurations for a WebSocket service.
WebSocketClientEndpointConfig Configuration for the WebSocket client endpoint.
WebSocketUpgradeConfig Resource configuration to upgrade from HTTP to WebSocket.

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

Implements a cache for storing HTTP responses. This cache complies with the caching policy set when configuring HTTP caching in the HTTP client endpoint.

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
AuthStoreProvider LDAP_AUTH_STORE | CONFIG_AUTH_STORE

Authentication storage providers for BasicAuth scheme.

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 | NO_BEARER | AUTH_HEADER_BEARER

Specifies how to send the authentication credentials when exchanging tokens.

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

InboundAuthScheme JWT_AUTH | BASIC_AUTH

Inbound authentication schemes.

KeepAlive KEEPALIVE_NEVER | KEEPALIVE_AUTO | KEEPALIVE_ALWAYS

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

MutualSslStatus null | PASSED | FAILED

Defines the possible values for the mutual ssl status.

passed: Mutual SSL handshake is succesful. failed: Mutual SSL handshake has failed.

OAuth2GrantType PASSWORD_GRANT | DIRECT_TOKEN | CLIENT_CREDENTIALS_GRANT

Specifies the type of the OAuth2 grant type

OutboundAuthScheme OAUTH2 | JWT_AUTH | BASIC_AUTH

Outbound authentication schemes.

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.

RequestMessage xml | string | null | json | io:ReadableByteChannel | byte[] | Request | Entity[]

The types of messages that are accepted by HTTP client when sending out the outbound request.

ResponseMessage xml | string | null | json | io:ReadableByteChannel | byte[] | Response | Entity[]

The types of messages that are accepted by HTTP listener when sending out the outbound response.

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

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

Field Name Data Type Default Value Description
scheme BASIC_AUTH|OAUTH2|JWT_AUTH

Authentication scheme

config http:BasicAuthConfig|http:OAuth2AuthConfig|http:JwtAuthConfig

Configuration related to the selected authenticator.

public type AuthProvider

Configuration for authentication providers.

Field Name Data Type Default Value Description
id string

Authentication provider instance id

scheme BASIC_AUTH|JWT_AUTH? ()

Authentication scheme

authStoreProvider CONFIG_AUTH_STORE|LDAP_AUTH_STORE? ()

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

config auth:LdapAuthProviderConfig|auth:ConfigAuthProviderConfig|auth:JWTAuthProviderConfig? ()

Configuration related to the selected authentication provider.

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 BasicAuthConfig

The `BasicAuthConfig` record can be used to configure Basic Authentication used by the HTTP endpoint.

Field Name Data Type Default Value Description
username string

Username for Basic authentication

password string

Password for Basic authentication

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 CachedToken

The `CachedToken` stores the values received from the authorization/token server to use them for the latter requests without requesting tokens again.

Field Name Data Type Default Value Description
accessToken string

Access token for the authorization server

refreshToken string

Refresh token for the refresh token server

expiryTime int

Expiry time of the access token in milliseconds

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 ClientCredentialsGrantConfig

The `ClientCredentialsGrantConfig` record can be used to configue OAuth2 client credentials grant type.

Field Name Data Type Default Value Description
tokenUrl string

Token URL for the authorization server

clientId string

Client ID for the client credentials grant authentication

clientSecret string

Client secret for the client credentials grant authentication

scopes string[]

Scope of the access request

clockSkew int 0

Clock skew in seconds

retryRequest boolean true

Retry the request if the initial request returns a 401 response

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER|NO_BEARER AUTH_HEADER_BEARER

How authentication credentials are sent to the authorization server

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? ()

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? ()

Configurations associated with Redirection

retryConfig http:RetryConfig? ()

Configurations associated with Retry

proxy http:ProxyConfig? ()

Proxy server related options

poolConfig http:PoolConfiguration? ()

Configurations associated with request pooling

secureSocket http:SecureSocket? ()

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? ()

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 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 DirectTokenConfig

The `DirectTokenConfig` record configures the access token directly.

Field Name Data Type Default Value Description
accessToken string

Access token for the authorization server

refreshConfig http:DirectTokenRefreshConfig

Configurations for refreshing the access token

clockSkew int 0

Clock skew in seconds

retryRequest boolean true

Retry the request if the initial request returns a 401 response

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER|NO_BEARER AUTH_HEADER_BEARER

How authentication credentials are sent to the authorization server

public type DirectTokenRefreshConfig

The `DirectTokenRefreshConfig` record passes the configurations for refreshing the access token for the grant type of the direct token grant type.

Field Name Data Type Default Value Description
refreshUrl string

Refresh token URL for the refresh token server

refreshToken string

Refresh token for the refresh token server

clientId string

Client ID for authentication with the authorization server

clientSecret string

Client secret for authentication with the authorization server

scopes string[]

Scope of the access request

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER|NO_BEARER AUTH_HEADER_BEARER

How authentication credentials are sent to the authorization server

public type FailoverClientEndpointConfiguration

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

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

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? ()

Redirect related options

retryConfig http:RetryConfig? ()

Retry related options

proxy http:ProxyConfig? ()

Proxy related options

poolConfig http:PoolConfiguration? ()

Configurations associated with request pooling

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? ()

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? ()

Annotation to define HTTP to WebSocket upgrade

authConfig http:ListenerAuthConfig? ()

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? ()

The error which caused the HttpTimeoutError

statusCode int 0

HTTP status code

public type JwtAuthConfig

The `JwtAuthConfig` record can be used to configure JWT based authentication used by the HTTP endpoint.

Field Name Data Type Default Value Description
inferredJwtIssuerConfig auth:InferredJwtIssuerConfig

JWT issuer configuration used to issue JWT with specific configuration

public type ListenerAuthConfig

Configures the authentication scheme for a service or a resource.

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

Enables/disables authentication

authProviders string[]? ()

Array of authentication provider IDs

scopes string[]? ()

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? ()

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? ()

Redirect related options

retryConfig http:RetryConfig? ()

Retry related options

proxy http:ProxyConfig? ()

Proxy related options

poolConfig http:PoolConfiguration? ()

Configurations associated with request pooling

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? ()

HTTP authentication releated configurations

lbRule http:LoadBalancerRule? ()

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 MutualSslHandshake

A record for providing mutual ssl handshake results.

Field Name Data Type Default Value Description
status passed|failed? ()

Status of the handshake.

public type OAuth2AuthConfig

The `OAuth2AuthConfig` record can be used to configure OAuth2 based authentication used by the HTTP endpoint.

Field Name Data Type Default Value Description
grantType CLIENT_CREDENTIALS_GRANT|PASSWORD_GRANT|DIRECT_TOKEN

OAuth2 grant type

config http:ClientCredentialsGrantConfig|http:PasswordGrantConfig|http:DirectTokenConfig

Configurations for the given grant type

public type PasswordGrantConfig

The `PasswordGrantConfig` record can be used to configue OAuth2 password grant type

Field Name Data Type Default Value Description
tokenUrl string

Token URL for the authorization server

username string

Username for password grant authentication

password string

Password for password grant authentication

clientId string

Client ID for password grant authentication

clientSecret string

Client secret for password grant authentication

scopes string[]

Scope of the access request

refreshConfig http:RefreshConfig

Configurations for refreshing the access token

clockSkew int 0

Clock skew in seconds

retryRequest boolean true

Retry the request if the initial request returns a 401 response

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER|NO_BEARER AUTH_HEADER_BEARER

How authentication credentials are sent to the authorization server

public type PoolConfiguration

Configurations for managing HTTP client connection pool.

Field Name Data Type Default Value Description
maxActiveConnections int config:getAsInt(b7a.http.pool.maxActiveConnections, defaultValue=-1)

Max active connections per route(host:port). Default value is -1 which indicates unlimited.

maxIdleConnections int config:getAsInt(b7a.http.pool.maxIdleConnections, defaultValue=100)

Maximum number of idle connections allowed per pool.

waitTimeinMillis int config:getAsInt(b7a.http.pool.waitTimeinMillis, defaultValue=30000)

Maximum amount of time, the client should wait for an idle connection before it sends an error when the pool is exhausted

maxActiveStreamsPerConnection int config:getAsInt(b7a.http.pool.maxActiveStreamsPerConnection, defaultValue=50)

Maximum active streams per connection. This only applies to HTTP/2.

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 RefreshConfig

The `RefreshConfig` record can be used to pass the configurations for refreshing the access token of password grant type.

Field Name Data Type Default Value Description
refreshUrl string

Refresh token URL for the refresh token server

scopes string[]

Scope of the access request

credentialBearer AUTH_HEADER_BEARER|POST_BODY_BEARER|NO_BEARER AUTH_HEADER_BEARER

How authentication credentials are sent to the authorization server

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 retrying behavior 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 crypto:TrustStore? ()

Configurations associated with TrustStore

keyStore crypto:KeyStore? ()

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? ()

SSL/TLS protocol related options

certValidation http:ValidateCert? ()

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

handshakeTimeout int

SSL handshake time out

sessionTimeout int

SSL session time out

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? ()

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? ()

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[]? ()

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 crypto:TrustStore? ()

Configures the trust store to be used

keyStore crypto:KeyStore? ()

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? ()

SSL/TLS protocol related options

certValidation http:ValidateCert? ()

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

handshakeTimeout int? ()

SSL handshake time out

sessionTimeout int? ()

SSL session time out

ocspStapling http:ServiceOcspStapling? ()

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? ()

Configurations for secure communication with the remote HTTP endpoint

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. Upon timeout, onIdleTimeout resource (if defined) in the server service will be triggered. Note that this overrides the timeoutMillis config in the http:Listener.

maxFrameSize int 0

The maximum payload size of a WebSocket frame in bytes. If this is not set or is negative or zero, the default frame size will be used.

public type WebSocketClientEndpointConfig

Configuration for the WebSocket client endpoint.

Field Name Data Type Default Value Description
callbackService service? ()

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 (if defined) in the client service will be triggered.

readyOnConnect boolean true

true if the client is ready to receive 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? ()

SSL/TLS related options

maxFrameSize int 0

The maximum payload size of a WebSocket frame in bytes. If this is not set or is negative or zero the default frame size of 65536 will be used.

public type WebSocketUpgradeConfig

Resource configuration to upgrade from HTTP to WebSocket.

Field Name Data Type Default Value Description
upgradePath string

Path which is used to upgrade from HTTP to WebSocket

upgradeService service

Callback service for 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[] ()

    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[] ()

    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[] ()

    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<>)