Full-code (serverless) functions
Altogic full-code functions is a serverless execution environment for building cloud services. With full-code functions, you write simple, single-purpose functions (e.g., custom code) that are attached to events emitted from your backend application. Your function is triggered when an event being watched is fired and your code is executed in a fully managed environment. There is no need to provision any infrastructure or worry about managing any servers.
Currently, you can write full-code functions using Javascript for the Node.js runtime. As traffic increases to your backend app, they automatically scale up and down to meet your needs, helping you to avoid downtime and paying for always-on compute.
Altogic full-code functions provide an additional layer of logic that lets you write custom code to extend your app's cloud services. Full-code functions augment existing no-code services and allow you to address an increasing number of use cases with arbitrary programming logic.
Each serverless function can be used to handle requests triggered from the below channels:
- Endpoints: You can direct RESTful API requests of an endpoint to your function
- Message queues: You can direct the processing of messages submitted to a queue to your function
- Cron jobs: You can schedule tasks that run at specific times or periods and direct the processing of these tasks to your function
Full-code functions can be deployed to your application's environment. You can create several environments for your apps at dozens of regions across the world. You can deploy your full-code functions to a single app environment or to multiple environments to improve latency and availability and meet your development needs.
Creating full-code functions
To create and deploy your full-code functions, you can use Altogic CLI, which is the command line interface specifically designed to manage your serverless functions.
When writing your own Altogic serverless function, you must export the code in certain ways. To deploy a serverless Node.js API, create a function in a .js file within the /src directory at the root of your project. Below is an example Node.js full-code function using Express.js-like helper methods from the Request and Response objects.
- Node.js
module.exports = async function (req, res) {
res.json({
quote: "Hello world!",
});
};
You can also include a package.json file along with your function code and import any modules you would like to use in your full-code function.
info
The maximum code size of your full-code function can be 50MB including the source code and any other resources.
When your function is called, you receive two parameters, a request and a response object. The request object contains all data that was sent to the function. A schema of the request object can be found below for different request triggering channels. For example, when your function is triggered through a call to an endpoint, all input parameters are passed to the request object whereas for a message queue trigger, your function will receive only appInfo
and body
parameters in the request object.
Property | Description | Endpoint | Message queue | Cron job |
---|---|---|---|---|
ids | Endpoint path id parameters object | Yes | No | No |
query | Request query string parameters | Yes | No | No |
headers | Request headers object | Yes | No | No |
appParams | App parameters object (e.g., environment variables) | Yes | Yes | Yes |
client | Requesting device type and IP information | Yes | No | No |
session | Session of the user making the request | Yes | No | No |
appInfo | Contextual information about the app and the environment | Yes | Yes | Yes |
files | Array of file objects | Yes | No | No |
body | Request body JSON object. Depending on your requirements, this can be a single JSON object or an array of JSON objects. | Yes | Yes | No |
Below you can also find sample data of a request for endpoint triggered full-code function.
Example request structure
//ids
//https://myapp123.c1-na.altogic.com/users/624b52783c77af658ac14ea2/products/6151be8581f301001aa73c3c
{
userId: '624b52783c77af658ac14ea2',
productId: '6151be8581f301001aa73c3c'
}
//query
//https://myapp123.c1-na.altogic.com/users?username=user123&quantity=123
{
username: 'user123',
quantity: 123
}
//headers
{
token: 'tk_23423...',
'content-type': 'application/json'
}
//appParams
//App params are configured in Atogic Designer -> App Settings -> Parameters
{
param1: 123,
param2: true,
param3: 'text value'
}
//client
//Only applicable for request triggered through calling and endpoint and provides calling party info.
{
ip: '100.123.45.66',
deviceType: 'desktop'
}
//session
{
userId: "62602c378415c0a0519102aa",
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbnZJZCI6IjYyNjAyYzM3ODQxNWMwYTA1MTkxMDJiNiIsInVzZXJJZCI6IjYyNjAyYzM3ODQxNWMwYTA1MTkxMDJhYSIsInV1aWQiOiI2NmMxM2JhZS1iOGE1LTQ1NDItOWJkZC0zYmE4NTAwZTU2NjUiLCJpYXQiOjE2NjM2ODYxNTB9.LAbzFnk59Ix8z-6Wkcd3Gz49FWnswtvuGFCqG-AX5fU",
creationDtm: "2022-09-20T15:02:30.331Z",
userAgent: {
family: "Chrome",
major: "105",
minor: "0",
patch: "0",
device: {
family: "Other",
major: "0",
minor: "0",
patch: "0",
},
os: {
family: "Mac OS X",
major: "10",
minor: "15",
patch: "7",
},
},
accessGroupKeys: ['admin', 'member'],
}
//appInfo
//Populated by the execution environment of your app
{
appName: "Practice App",
environmentName: "Development",
environmentType: "trial",
apiBaseUrl: "https://c1-na.altogic.com/e:62602c378415c0a0519102b6",
executionStartDtm: "2022-09-20T15:02:30.325Z",
}
//files
//List of files. The contents keep the Buffer of the file contents
[
{
"fieldName": "file2",
"fileName": "red.png",
"encoding": "7bit",
"mimeType": "image/png",
"size": 18372,
"contents": {
"type": "Buffer",
"data": [
123,
34,
116,
... ]
}
},
...
]
//body - This depends on the parameters that you send in your request body
The response object has two methods, send(text, status = 200)
and json(json, status = 200)
that can be used to send data back to the calling party. If the function is triggered by calling an endpoint, the response returned by send()
or json()
is returned to the calling party. However, if the function is triggered by a message queue or cron job, there is no tangible calling party, the response returned by send()
or json()
method is added to the log records.
Deploying your function
You can deploy your serverless functions using Altogic CLI. Make sure you have installed Altogic CLI and you have successfully logged into your Altogic account. Please ensure you are in the same folder as your altogic.json
and run altogic deploy
to deploy your function. You will be prompted to select which environment to deploy if you have multiple execution environments.
$ altogic deploy
When you run the deploy command, Altogic creates a new image and applies this image to your app's execution environment. Depending on the size of your code and its dependencies, it may take a couple of minutes to build and deploy your function. You can run altogic get builds
and altogic get deployments
to get the status of your builds and deployments respectively.
warning
The entrypoint (e.g., the function export file) of your function is by default set to src/index.js
in altogic.json
file. If you change the location of your function's soruce code and/or the entrypoint, you need to manually update the entrypoint value in altogic.json
file before deployment. During function execution if the entrypoint cannot be idenfied, an error will be returned.
info
Altogic's autoscaling support adjusts the number of pods your serverless function uses, based on the rate of requests your function needs to process. When your function receives no requests, Altogic can set the function deployment to use zero pod replicas. As a result, when your function becomes idle, it uses no pods and therefore consumes no compute or memory resources.
When the first new request arrives to be served by an idle function, Altogic increases the application deployment replicas to one and queues the incoming request until a function pod is ready. The time it takes Altogic to deploy the first function pod depends several factors (e.g., the runtime used, the size of the docker image created, function start/load time) and typically the cold-start can take a few seconds.
Altogic scales down the number of pods of your function if your function is idle for more than 5 minutes.
Linking your function to triggers
After writing and successfully deploying your function to your execution environment, you need to link your function to an endpoint, message queue, and/or scheduled task. You can use Altogic Designer to configure your endpoint, message queue, and cron job handlers. After linking your functions, you can invoke them by sending a RESTful API request to the linked endpoint, submitting a message to the linked queue or they can also be invoked by the linked scheduled task (e.g., cron-job) trigger.
Local testing of your functions
You can test your node.js runtime functions locally by running the start
command. This command will launch a local HTTP server and provide you the endpoint (URL) of the function. The start
command has hot-reloading capabilities. It will watch for any changes to your files and restart the HTTP server.
$ altogic start
Local development HTTP server running at port:4000.
You can now test your function using the following endpoint: http://localhost:4000
info
During the local testing of your functions you need to pass headers, query string parameters, appParams, client, session, appInfo etc. related parameters in the body of your request. As an example if you need to pass a query string parameter such as http://localhost:4000?sort=asc
, then during local testing pass this parameter in the body of the request in following format { query: { sort: "asc"}}
, similarly you need to pass the other parameters in the same way. However, after deployment, you can pass these parameters to your function in the haeder of the request or as query string parameter in the URL of your endpoint.
Testing deployed functions
You can use Altogic Tester or any other API testing tool (e.g., Postman) to test your serverless functions. In your function code, you can log messages using console.log
, console.info
, console.warn
, console.error
and, console.debug
methods. Upon execution of your deployed function, these log messages are also returned in response body.