Questo contenuto non è disponibile nella lingua selezionata.
Chapter 12. Functions development reference guide
12.1. Developing Go functions
OpenShift Serverless Functions with Go is a Technology Preview feature only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs) and might not be functionally complete. Red Hat does not recommend using them in production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features, see Technology Preview Features Support Scope.
After you have created a Go function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
12.1.1. Prerequisites
- Before you can develop functions, you must complete the steps in Configuring OpenShift Serverless Functions.
12.1.2. Go function template structure
					When you create a Go function using the Knative (kn) CLI, the project directory looks like a typical Go project. The only exception is the additional func.yaml configuration file, which is used for specifying the image.
				
					Go functions have few restrictions. The only requirements are that your project must be defined in a function module, and must export the function Handle().
				
					Both http and event trigger functions have the same template structure:
				
Template structure
- 1
- Thefunc.yamlconfiguration file is used to determine the image name and registry.
- 2
- You can add any required dependencies to thego.modfile, which can include additional local Go files. When the project is built for deployment, these dependencies are included in the resulting runtime container image.Example of adding dependencies go get gopkg.in/yaml.v2@v2.4.0 $ go get gopkg.in/yaml.v2@v2.4.0Copy to Clipboard Copied! Toggle word wrap Toggle overflow 
12.1.3. About invoking Go functions
					When using the Knative (kn) CLI to create a function project, you can generate a project that responds to CloudEvents, or one that responds to simple HTTP requests. Go functions are invoked by using different methods, depending on whether they are triggered by an HTTP request or a CloudEvent.
				
12.1.3.1. Functions triggered by an HTTP request
						When an incoming HTTP request is received, functions are invoked with a standard Go Context as the first parameter, followed by the http.ResponseWriter and http.Request parameters. You can use standard Go techniques to access the request, and set a corresponding HTTP response for your function.
					
Example HTTP response
12.1.3.2. Functions triggered by a cloud event
						When an incoming cloud event is received, the event is invoked by the CloudEvents Go SDK. The invocation uses the Event type as a parameter.
					
You can leverage the Go Context as an optional parameter in the function contract, as shown in the list of supported function signatures:
Supported function signatures
12.1.3.2.1. CloudEvent trigger example
A cloud event is received which contains a JSON string in the data property:
{
  "customerId": "0123456",
  "productId": "6543210"
}
{
  "customerId": "0123456",
  "productId": "6543210"
}
							To access this data, a structure must be defined which maps properties in the cloud event data, and retrieves the data from the incoming event. The following example uses the Purchase structure:
						
							Alternatively, a Go encoding/json package could be used to access the cloud event directly as JSON in the form of a bytes array:
						
func Handle(ctx context.Context, event cloudevents.Event) {
  bytes, err := json.Marshal(event)
  // ...
}
func Handle(ctx context.Context, event cloudevents.Event) {
  bytes, err := json.Marshal(event)
  // ...
}12.1.4. Go function return values
Functions triggered by HTTP requests can set the response directly. You can configure the function to do this by using the Go http.ResponseWriter.
Example HTTP response
					Functions triggered by a cloud event might return nothing, error, or CloudEvent in order to push events into the Knative Eventing system. In this case, you must set a unique ID, proper Source, and a Type for the cloud event. The data can be populated from a defined structure, or from a map.
				
Example CloudEvent response
12.1.5. Testing Go functions
					Go functions can be tested locally on your computer. In the default project that is created when you create a function using kn func create, there is a handle_test.go file, which contains some basic tests. These tests can be extended as needed.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- Navigate to the test folder for your function.
- Run the tests: - go test - $ go test- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.1.6. Next steps
12.2. Developing Quarkus functions
After you have created a Quarkus function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
12.2.1. Prerequisites
- Before you can develop functions, you must complete the setup steps in Configuring OpenShift Serverless Functions.
12.2.2. Quarkus function template structure
					When you create a Quarkus function by using the Knative (kn) CLI, the project directory looks similar to a typical Maven project. Additionally, the project contains the func.yaml file, which is used for configuring the function.
				
					Both http and event trigger functions have the same template structure:
				
Template structure
- 1
- Used to determine the image name and registry.
- 2
- The Project Object Model (POM) file contains project configuration, such as information about dependencies. You can add additional dependencies by modifying this file.Example of additional dependencies Copy to Clipboard Copied! Toggle word wrap Toggle overflow Dependencies are downloaded during the first compilation. 
- 3
- The function project must contain a Java method annotated with@Funq. You can place this method in theFunction.javaclass.
- 4
- Contains simple test cases that can be used to test your function locally.
12.2.3. About invoking Quarkus functions
You can create a Quarkus project that responds to cloud events, or one that responds to simple HTTP requests. Cloud events in Knative are transported over HTTP as a POST request, so either function type can listen and respond to incoming HTTP requests.
When an incoming request is received, Quarkus functions are invoked with an instance of a permitted type.
| Invocation method | Data type contained in the instance | Example of data | 
|---|---|---|
| HTTP POST request | JSON object in the body of the request | 
									 | 
| HTTP GET request | Data in the query string | 
									 | 
| 
									 | 
									JSON object in the  | 
									 | 
					The following example shows a function that receives and processes the customerId and productId purchase data that is listed in the previous table:
				
Example Quarkus function
					The corresponding Purchase JavaBean class that contains the purchase data looks as follows:
				
Example class
public class Purchase {
    private long customerId;
    private long productId;
    // getters and setters
}
public class Purchase {
    private long customerId;
    private long productId;
    // getters and setters
}12.2.3.1. Invocation examples
						The following example code defines three functions named withBeans, withCloudEvent, and withBinary;
					
Example
						The withBeans function of the Functions class can be invoked by:
					
- An HTTP POST request with a JSON body: - curl "http://localhost:8080/withBeans" -X POST \ -H "Content-Type: application/json" \ -d '{"message": "Hello there."}'- $ curl "http://localhost:8080/withBeans" -X POST \ -H "Content-Type: application/json" \ -d '{"message": "Hello there."}'- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- An HTTP GET request with query parameters: - curl "http://localhost:8080/withBeans?message=Hello%20there." -X GET - $ curl "http://localhost:8080/withBeans?message=Hello%20there." -X GET- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- A - CloudEventobject in binary encoding:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- A - CloudEventobject in structured encoding:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
						The withCloudEvent function of the Functions class can be invoked by using a CloudEvent object, similarly to the withBeans function. However, unlike withBeans, withCloudEvent cannot be invoked with a plain HTTP request.
					
						The withBinary function of the Functions class can be invoked by:
					
- A - CloudEventobject in binary encoding:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- A - CloudEventobject in structured encoding:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.2.4. CloudEvent attributes
					If you need to read or write the attributes of a CloudEvent, such as type or subject, you can use the CloudEvent<T> generic interface and the CloudEventBuilder builder. The <T> type parameter must be one of the permitted types.
				
					In the following example, CloudEventBuilder is used to return success or failure of processing the purchase:
				
12.2.5. Quarkus function return values
					Functions can return an instance of any type from the list of permitted types. Alternatively, they can return the Uni<T> type, where the <T> type parameter can be of any type from the permitted types.
				
					The Uni<T> type is useful if a function calls asynchronous APIs, because the returned object is serialized in the same format as the received object. For example:
				
- If a function receives an HTTP request, then the returned object is sent in the body of an HTTP response.
- 
							If a function receives a CloudEventobject in binary encoding, then the returned object is sent in the data property of a binary-encodedCloudEventobject.
The following example shows a function that fetches a list of purchases:
Example command
- Invoking this function through an HTTP request produces an HTTP response that contains a list of purchases in the body of the response.
- 
							Invoking this function through an incoming CloudEventobject produces aCloudEventresponse with a list of purchases in thedataproperty.
12.2.5.1. Permitted types
						The input and output of a function can be any of the void, String, or byte[] types. Additionally, they can be primitive types and their wrappers, for example, int and Integer. They can also be the following complex objects: Javabeans, maps, lists, arrays, and the special CloudEvents<T> type.
					
						Maps, lists, arrays, the <T> type parameter of the CloudEvents<T> type, and attributes of Javabeans can only be of types listed here.
					
Example
12.2.6. Testing Quarkus functions
					Quarkus functions can be tested locally on your computer. In the default project that is created when you create a function using kn func create, there is the src/test/ directory, which contains basic Maven tests. These tests can be extended as needed.
				
Prerequisites
- You have created a Quarkus function.
- 
							You have installed the Knative (kn) CLI.
Procedure
- Navigate to the project folder for your function.
- Run the Maven tests: - ./mvnw test - $ ./mvnw test- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.2.7. Overriding liveness and readiness probe values
					You can override liveness and readiness probe values for your Quarkus functions. This allows you to configure health checks performed on the function.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- Override the - /health/livenessand- /health/readinesspaths with your own values. You can do this either by changing properties in the function source or by setting the- QUARKUS_SMALLRYE_HEALTH_LIVENESS_PATHand- QUARKUS_SMALLRYE_HEALTH_READINESS_PATHenvironment variables on- func.yamlfile.- To override the paths using the function source, update the path properties in the - src/main/resources/application.propertiesfile:- quarkus.smallrye-health.root-path=/health quarkus.smallrye-health.liveness-path=alive quarkus.smallrye-health.readiness-path=ready - quarkus.smallrye-health.root-path=/health- 1 - quarkus.smallrye-health.liveness-path=alive- 2 - quarkus.smallrye-health.readiness-path=ready- 3 - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- To override the paths using environment variables, define the path variables in the - buildblock of the- func.yamlfile:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
 
- Add the new endpoints to the - func.yamlfile, so that they are properly bound to the container for the Knative service:- deploy: healthEndpoints: liveness: /health/alive readiness: /health/ready- deploy: healthEndpoints: liveness: /health/alive readiness: /health/ready- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.2.8. Next steps
12.3. Developing Node.js functions
After you have created a Node.js function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
12.3.1. Prerequisites
- Before you can develop functions, you must complete the steps in Configuring OpenShift Serverless Functions.
12.3.2. Node.js function template structure
					When you create a Node.js function using the Knative (kn) CLI, the project directory looks like a typical Node.js project. The only exception is the additional func.yaml file, which is used to configure the function.
				
					Both http and event trigger functions have the same template structure:
				
Template structure
- 1
- Thefunc.yamlconfiguration file is used to determine the image name and registry.
- 2
- Your project must contain anindex.jsfile which exports a single function.
- 3
- You are not restricted to the dependencies provided in the templatepackage.jsonfile. You can add additional dependencies as you would in any other Node.js project.Example of adding npm dependencies npm install --save opossum npm install --save opossumCopy to Clipboard Copied! Toggle word wrap Toggle overflow When the project is built for deployment, these dependencies are included in the created runtime container image. 
- 4
- Integration and unit test scripts are provided as part of the function template.
12.3.3. About invoking Node.js functions
					When using the Knative (kn) CLI to create a function project, you can generate a project that responds to CloudEvents, or one that responds to simple HTTP requests. CloudEvents in Knative are transported over HTTP as a POST request, so both function types listen for and respond to incoming HTTP events.
				
					Node.js functions can be invoked with a simple HTTP request. When an incoming request is received, functions are invoked with a context object as the first parameter.
				
12.3.3.1. Node.js context objects
						Functions are invoked by providing a context object as the first parameter. This object provides access to the incoming HTTP request information.
					
						This information includes the HTTP request method, any query strings or headers sent with the request, the HTTP version, and the request body. Incoming requests that contain a CloudEvent attach the incoming instance of the CloudEvent to the context object so that it can be accessed by using context.cloudevent.
					
12.3.3.1.1. Context object methods
							The context object has a single method, cloudEventResponse(), that accepts a data value and returns a CloudEvent.
						
In a Knative system, if a function deployed as a service is invoked by an event broker sending a CloudEvent, the broker examines the response. If the response is a CloudEvent, this event is handled by the broker.
Example context object method
12.3.3.1.2. CloudEvent data
If the incoming request is a CloudEvent, any data associated with the CloudEvent is extracted from the event and provided as a second parameter. For example, if a CloudEvent is received that contains a JSON string in its data property that is similar to the following:
{
  "customerId": "0123456",
  "productId": "6543210"
}
{
  "customerId": "0123456",
  "productId": "6543210"
}
							When invoked, the second parameter to the function, after the context object, will be a JavaScript object that has customerId and productId properties.
						
Example signature
function handle(context, data)
function handle(context, data)
							The data parameter in this example is a JavaScript object that contains the customerId and productId properties.
						
12.3.3.1.3. Arbitrary data
							A function can receive any data, not just CloudEvents. For example, you might want to call a function by using POST with an arbitrary object in the body:
						
In this case, you can define the function as follows:
function handle(context, customer) {
  return "Hello " + customer.contact.title + " " + customer.contact.lastname;
}
function handle(context, customer) {
  return "Hello " + customer.contact.title + " " + customer.contact.lastname;
}Supplying the contact object to the function would then return the following output:
Hello Mr. Smith
Hello Mr. Smith12.3.3.1.4. Supported data types
CloudEvents can contain various data types, including JSON, XML, plain text, and binary data. These data types are provided to the function in their respective formats:
- JSON Data: Provided as a JavaScript object.
- XML Data: Provided as an XML document.
- Plain Text: Provided as a string.
- Binary Data: Provided as a Buffer object.
12.3.3.1.5. Multiple data types in a function
Ensure your function can handle different data types by checking the Content-Type header and parsing the data accordingly. For example:
12.3.4. Node.js function return values
					Functions can return any valid JavaScript type or can have no return value. When a function has no return value specified, and no failure is indicated, the caller receives a 204 No Content response.
				
					Functions can also return a CloudEvent or a Message object in order to push events into the Knative Eventing system. In this case, the developer is not required to understand or implement the CloudEvent messaging specification. Headers and other relevant information from the returned values are extracted and sent with the response.
				
Example
12.3.4.1. Returning primitive types
Functions can return any valid JavaScript type, including primitives such as strings, numbers, and booleans:
Example function returning a string
function handle(context) {
  return "This function Works!"
}
function handle(context) {
  return "This function Works!"
}Calling this function returns the following string:
curl https://myfunction.example.com
$ curl https://myfunction.example.comThis function Works!
This function Works!Example function returning a number
function handle(context) {
  let somenumber = 100
  return { body: somenumber }
}
function handle(context) {
  let somenumber = 100
  return { body: somenumber }
}Calling this function returns the following number:
curl https://myfunction.example.com
$ curl https://myfunction.example.com100
100Example function returning a boolean
function handle(context) {
  let someboolean = false
  return { body: someboolean }
}
function handle(context) {
  let someboolean = false
  return { body: someboolean }
}Calling this function returns the following boolean:
curl https://myfunction.example.com
$ curl https://myfunction.example.comfalse
false
						Returning primitives directly without wrapping them in an object results in a 204 No Content status code with an empty body:
					
Example function returning a primitive directly
function handle(context) {
  let someboolean = false
  return someboolean
}
function handle(context) {
  let someboolean = false
  return someboolean
}Calling this function returns the following:
http :8080
$ http :8080HTTP/1.1 204 No Content Connection: keep-alive ...
HTTP/1.1 204 No Content
Connection: keep-alive
...12.3.4.2. Returning headers
						You can set a response header by adding a headers property to the return object. These headers are extracted and sent with the response to the caller.
					
Example response header
function handle(context, customer) {
  // process customer and return custom headers
  // the response will be '204 No content'
  return { headers: { customerid: customer.id } };
}
function handle(context, customer) {
  // process customer and return custom headers
  // the response will be '204 No content'
  return { headers: { customerid: customer.id } };
}12.3.4.3. Returning status codes
						You can set a status code that is returned to the caller by adding a statusCode property to the return object:
					
Example status code
Status codes can also be set for errors that are created and thrown by the function:
Example error status code
12.3.5. Testing Node.js functions
					Node.js functions can be tested locally on your computer. In the default project that is created when you create a function by using kn func create, there is a test folder that contains some simple unit and integration tests.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- Navigate to the test folder for your function.
- Run the tests: - npm test - $ npm test- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.3.6. Overriding liveness and readiness probe values
					You can override liveness and readiness probe values for your Node.js functions. This allows you to configure health checks performed on the function.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- In your function code, create the - Functionobject, which implements the following interface:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - 1
- The initialization function, called before the server is started. This function is optional and should be synchronous.
- 2
- The shutdown function, called after the server is stopped. This function is optional and should be synchronous.
- 3
- The liveness function, called to check if the server is alive. This function is optional and should return 200/OK if the server is alive.
- 4
- The readiness function, called to check if the server is ready to accept requests. This function is optional and should return 200/OK if the server is ready.
- 5
- The function to handle HTTP requests.
 - For example, add the following code to the - index.jsfile:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - As an alternative to - Function.liveness.pathand- Function.readiness.path, you can specify custom endpoints using the- LIVENESS_URLand- READINESS_URLenvironment variables:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Add the new endpoints to the - func.yamlfile, so that they are properly bound to the container for the Knative service:- deploy: healthEndpoints: liveness: /alive readiness: /ready- deploy: healthEndpoints: liveness: /alive readiness: /ready- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.3.7. Node.js context object reference
					The context object has several properties that can be accessed by the function developer. Accessing these properties can provide information about HTTP requests and write output to the cluster logs.
				
12.3.7.1. log
Provides a logging object that can be used to write output to the cluster logs. The log adheres to the Pino logging API.
Example log
function handle(context) {
  context.log.info(“Processing customer”);
}
function handle(context) {
  context.log.info(“Processing customer”);
}
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.function.com'
$ kn func invoke --target 'http://example.function.com'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
						You can change the log level to one of fatal, error, warn, info, debug, trace, or silent. To do that, change the value of logLevel by assigning one of these values to the environment variable FUNC_LOG_LEVEL using the config command.
					
12.3.7.2. query
Returns the query string for the request, if any, as key-value pairs. These attributes are also found on the context object itself.
Example query
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.com?name=tiger'
$ kn func invoke --target 'http://example.com?name=tiger'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}12.3.7.3. body
Returns the request body if any. If the request body contains JSON code, this will be parsed so that the attributes are directly available.
Example body
function handle(context) {
  // log the incoming request body's 'hello' parameter
  context.log.info(context.body.hello);
}
function handle(context) {
  // log the incoming request body's 'hello' parameter
  context.log.info(context.body.hello);
}
						You can access the function by using the curl command to invoke it:
					
Example command
kn func invoke -d '{"Hello": "world"}'
$ kn func invoke -d '{"Hello": "world"}'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}12.3.7.4. headers
Returns the HTTP request headers as an object.
Example header
function handle(context) {
  context.log.info(context.headers["custom-header"]);
}
function handle(context) {
  context.log.info(context.headers["custom-header"]);
}
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.function.com'
$ kn func invoke --target 'http://example.function.com'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}12.3.7.5. HTTP requests
- method
- Returns the HTTP request method as a string.
- httpVersion
- Returns the HTTP version as a string.
- httpVersionMajor
- Returns the HTTP major version number as a string.
- httpVersionMinor
- Returns the HTTP minor version number as a string.
12.3.8. Next steps
12.4. Developing TypeScript functions
After you have created a TypeScript function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
12.4.1. Prerequisites
- Before you can develop functions, you must complete the steps in Configuring OpenShift Serverless Functions.
12.4.2. TypeScript function template structure
					When you create a TypeScript function using the Knative (kn) CLI, the project directory looks like a typical TypeScript project. The only exception is the additional func.yaml file, which is used for configuring the function.
				
					Both http and event trigger functions have the same template structure:
				
Template structure
- 1
- Thefunc.yamlconfiguration file is used to determine the image name and registry.
- 2
- You are not restricted to the dependencies provided in the templatepackage.jsonfile. You can add additional dependencies as you would in any other TypeScript project.Example of adding npm dependencies npm install --save opossum npm install --save opossumCopy to Clipboard Copied! Toggle word wrap Toggle overflow When the project is built for deployment, these dependencies are included in the created runtime container image. 
- 3
- Your project must contain ansrc/index.jsfile which exports a function namedhandle.
- 4
- Integration and unit test scripts are provided as part of the function template.
12.4.3. About invoking TypeScript functions
					When using the Knative (kn) CLI to create a function project, you can generate a project that responds to CloudEvents or one that responds to simple HTTP requests. CloudEvents in Knative are transported over HTTP as a POST request, so both function types listen for and respond to incoming HTTP events.
				
					TypeScript functions can be invoked with a simple HTTP request. When an incoming request is received, functions are invoked with a context object as the first parameter.
				
12.4.3.1. TypeScript context objects
						To invoke a function, you provide a context object as the first parameter. Accessing properties of the context object can provide information about the incoming HTTP request.
					
Example context object
function handle(context:Context): string
function handle(context:Context): string
						This information includes the HTTP request method, any query strings or headers sent with the request, the HTTP version, and the request body. Incoming requests that contain a CloudEvent attach the incoming instance of the CloudEvent to the context object so that it can be accessed by using context.cloudevent.
					
12.4.3.1.1. Context object methods
							The context object has a single method, cloudEventResponse(), that accepts a data value and returns a CloudEvent.
						
In a Knative system, if a function deployed as a service is invoked by an event broker sending a CloudEvent, the broker examines the response. If the response is a CloudEvent, this event is handled by the broker.
Example context object method
12.4.3.1.2. Context types
The TypeScript type definition files export the following types for use in your functions.
Exported type definitions
12.4.3.1.3. CloudEvent data
If the incoming request is a CloudEvent, any data associated with the CloudEvent is extracted from the event and provided as a second parameter. For example, if a CloudEvent is received that contains a JSON string in its data property that is similar to the following:
{
  "customerId": "0123456",
  "productId": "6543210"
}
{
  "customerId": "0123456",
  "productId": "6543210"
}
							When invoked, the second parameter to the function, after the context object, will be a JavaScript object that has customerId and productId properties.
						
Example signature
function handle(context: Context, cloudevent?: CloudEvent): CloudEvent
function handle(context: Context, cloudevent?: CloudEvent): CloudEvent
							The cloudevent parameter in this example is a JavaScript object that contains the customerId and productId properties.
						
12.4.4. TypeScript function return values
					Functions can return any valid JavaScript type or can have no return value. When a function has no return value specified, and no failure is indicated, the caller receives a 204 No Content response.
				
					Functions can also return a CloudEvent or a Message object in order to push events into the Knative Eventing system. In this case, the developer is not required to understand or implement the CloudEvent messaging specification. Headers and other relevant information from the returned values are extracted and sent with the response.
				
Example
12.4.4.1. Returning headers
						You can set a response header by adding a headers property to the return object. These headers are extracted and sent with the response to the caller.
					
Example response header
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
  // process customer and return custom headers
  const customer = cloudevent.data as Record<string, any>;
  return { headers: { 'customer-id': customer.id } };
}
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
  // process customer and return custom headers
  const customer = cloudevent.data as Record<string, any>;
  return { headers: { 'customer-id': customer.id } };
}12.4.4.2. Returning status codes
						You can set a status code that is returned to the caller by adding a statusCode property to the return object:
					
Example status code
Status codes can also be set for errors that are created and thrown by the function:
Example error status code
12.4.5. Testing TypeScript functions
					TypeScript functions can be tested locally on your computer. In the default project that is created when you create a function using kn func create, there is a test folder that contains some simple unit and integration tests.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- If you have not previously run tests, install the dependencies first: - npm install - $ npm install- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the test folder for your function.
- Run the tests: - npm test - $ npm test- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.4.6. Overriding liveness and readiness probe values
					You can override liveness and readiness probe values for your TypeScript functions. This allows you to configure health checks performed on the function.
				
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
- 
							You have installed the Knative (kn) CLI.
- 
							You have created a function by using kn func create.
Procedure
- In your function code, create the - Functionobject, which implements the following interface:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - 1
- The initialization function, called before the server is started. This function is optional and should be synchronous.
- 2
- The shutdown function, called after the server is stopped. This function is optional and should be synchronous.
- 3
- The liveness function, called to check if the server is alive. This function is optional and should return 200/OK if the server is alive.
- 4
- The readiness function, called to check if the server is ready to accept requests. This function is optional and should return 200/OK if the server is ready.
- 5
- The function to handle HTTP requests.
 - For example, add the following code to the - index.jsfile:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - As an alternative to - Function.liveness.pathand- Function.readiness.path, you can specify custom endpoints using the- LIVENESS_URLand- READINESS_URLenvironment variables:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Add the new endpoints to the - func.yamlfile, so that they are properly bound to the container for the Knative service:- deploy: healthEndpoints: liveness: /alive readiness: /ready- deploy: healthEndpoints: liveness: /alive readiness: /ready- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
12.4.7. TypeScript context object reference
					The context object has several properties that can be accessed by the function developer. Accessing these properties can provide information about incoming HTTP requests and write output to the cluster logs.
				
12.4.7.1. log
Provides a logging object that can be used to write output to the cluster logs. The log adheres to the Pino logging API.
Example log
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.function.com'
$ kn func invoke --target 'http://example.function.com'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
						You can change the log level to one of fatal, error, warn, info, debug, trace, or silent. To do that, change the value of logLevel by assigning one of these values to the environment variable FUNC_LOG_LEVEL using the config command.
					
12.4.7.2. query
Returns the query string for the request, if any, as key-value pairs. These attributes are also found on the context object itself.
Example query
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.function.com' --data '{"name": "tiger"}'
$ kn func invoke --target 'http://example.function.com' --data '{"name": "tiger"}'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}12.4.7.3. body
Returns the request body, if any. If the request body contains JSON code, this will be parsed so that the attributes are directly available.
Example body
						You can access the function by using the kn func invoke command:
					
Example command
kn func invoke --target 'http://example.function.com' --data '{"hello": "world"}'
$ kn func invoke --target 'http://example.function.com' --data '{"hello": "world"}'Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}12.4.7.4. headers
Returns the HTTP request headers as an object.
Example header
						You can access the function by using the curl command to invoke it:
					
Example command
curl -H'x-custom-header: some-value’' http://example.function.com
$ curl -H'x-custom-header: some-value’' http://example.function.comExample output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}12.4.7.5. HTTP requests
- method
- Returns the HTTP request method as a string.
- httpVersion
- Returns the HTTP version as a string.
- httpVersionMajor
- Returns the HTTP major version number as a string.
- httpVersionMinor
- Returns the HTTP minor version number as a string.
12.4.8. Next steps
- Build and deploy a function.
- See the Pino API documentation for more information about logging with functions.
12.5. Developing Python functions
OpenShift Serverless Functions with Python is a Technology Preview feature only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs) and might not be functionally complete. Red Hat does not recommend using them in production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features, see Technology Preview Features Support Scope.
After you have created a Python function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
12.5.1. Prerequisites
- Before you can develop functions, you must complete the steps in Configuring OpenShift Serverless Functions.
12.5.2. Python function template structure
					When you create a Python function by using the Knative (kn) CLI, the project directory looks similar to a typical Python project. Python functions have very few restrictions. The only requirements are that your project contains a func.py file that contains a main() function, and a func.yaml configuration file.
				
					Developers are not restricted to the dependencies provided in the template requirements.txt file. Additional dependencies can be added as they would be in any other Python project. When the project is built for deployment, these dependencies will be included in the created runtime container image.
				
					Both http and event trigger functions have the same template structure:
				
Template structure
fn ├── func.py ├── func.yaml ├── requirements.txt └── test_func.py
fn
├── func.py 
├── func.yaml 
├── requirements.txt 
└── test_func.py 12.5.3. About invoking Python functions
					Python functions can be invoked with a simple HTTP request. When an incoming request is received, functions are invoked with a context object as the first parameter.
				
					The context object is a Python class with two attributes:
				
- 
							The requestattribute is always present, and contains the Flaskrequestobject.
- 
							The second attribute, cloud_event, is populated if the incoming request is aCloudEventobject.
					Developers can access any CloudEvent data from the context object.
				
Example context object
12.5.4. Python function return values
Functions can return any value supported by Flask. This is because the invocation framework proxies these values directly to the Flask server.
Example
def main(context: Context):
    body = { "message": "Howdy!" }
    headers = { "content-type": "application/json" }
    return body, 200, headers
def main(context: Context):
    body = { "message": "Howdy!" }
    headers = { "content-type": "application/json" }
    return body, 200, headersFunctions can set both headers and response codes as secondary and tertiary response values from function invocation.
12.5.4.1. Returning CloudEvents
						Developers can use the @event decorator to tell the invoker that the function return value must be converted to a CloudEvent before sending the response.
					
Example
						This example sends a CloudEvent as the response value, with a type of "my.type" and a source of "/my/function". The CloudEvent data property is set to the returned data variable. The event_source and event_type decorator attributes are both optional.
					
12.5.5. Testing Python functions
					You can test Python functions locally on your computer. The default project contains a test_func.py file, which provides a simple unit test for functions.
				
						The default test framework for Python functions is unittest. You can use a different test framework if you prefer.
					
Prerequisites
- To run Python functions tests locally, you must install the required dependencies: - pip install -r requirements.txt - $ pip install -r requirements.txt- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
Procedure
- 
							Navigate to the folder for your function that contains the test_func.pyfile.
- Run the tests: - python3 test_func.py - $ python3 test_func.py- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow