Introduction

Many alternative platforms which provide an alternative to GameSparks Cloud-Code do not offer an alternative to timed or recurring scripts like the every-minute, every-day and every-hour scripts that GameSparks offers.

Very often these scripts are integral to the backend and can be used for a range of features including live-ops scheduling, activating campaigns and scheduling auto-generated content for your games. It is therefore important, where possible, we find an alternative solution for these scripts.

In this topic we are going to cover one way to scheduled events using an AWS service. We are then going to have these events trigger a serverless script which you can use to reach out to your Cloud-Code scripts or the alternative-platform's REST API.

Before starting anything you will need to make sure you have an AWS account. Setting up a new AWS account is a simple process, just go to aws.amazon.com to sign-up.

AWS Lambda Functions

Lambda functions are serverless scripts which you can trigger from a number of other AWS services. You can develop these scripts in a variety of different languages, and they integrate with a large number of other AWS services.

For this example we are going to show some simple HTTP requests using Node.js, as this would be most similar to the JavaScript you will be familiar with from GameSparks. Keep in mind that these calls will be asynchronous in Node.js so we will have to write our code to wait for a response if we are dealing with calls to 3rd party services like our platform's Cloud-Code or a database call. Create A Lambda Function The first thing we need to do is create a new Lambda function. Navigate to the service from the AWS console and you will see a panel where your functions are listed. We want to create a new one so click on the “Create Function” button.

On the next screen you will see some options for setting up your Lambda function. We don't need to worry about this here. We are going to use Node.js for this example so you can give your Lambda a name and choose Node.js as the environment.

It will then take a moment for your Lambda to be created before you will be presented with the script editor.

You don't really need to worry about most of the options presented here. We are mainly going to be editing and testing the script. The first thing you will need to do is double-click on the index.js script. This is where our code example will go.

Script Features

Since our code is going to be simple for this example, we won't really be exploring how a Lambda script is put together, but as you’ll want to work on your own Lambda code we’ll quickly explain the different components of the script.

First, you can see the handler function being set. Code inside this function will be executed when the Lambda is executed, but that doesn't mean you need to include all your own functions and variables in there too. You can add those wherever makes sense to you, for example, global variables can go at the top of your script.

The event parameter is very useful as it contains the context of the script, along with any parameters you wish to pass in. We aren't going to be passing anything in for this example but it's good to know if you wish to use Lambdas for some future projects.

The response is a JSON object returned from the handler function. Something important to know here is that the body field must be a string. You will get no response if it is not returning string.

We don't actually need a response for our function in this example, but it will be useful for debugging anyway.

Simple HTTP Request

For this example we will just show how to do a GET request from the Lambda, though this example can be used for POST requests too, which we will show in brief in the guide on Resetting Leaderboards here.

We will use the random name generator. This won't be the same API we used in the Cloud-Code topic, because we want to use a valid HTTPS API here and that is what the REST APIs of these alternative backends will be using too. If you want to use a HTTP request you will need a different module.

const https = require('https');   
const requestDetails = {
    host:   "api.fungenerators.com",
    path:   "/name/generate?category=car&limit=10",
    method: "GET"
}

exports.handler = async (event) => {

    let respDetails = await httpRequest(requestDetails);
    console.log(respDetails);

    // response JSON //
    const response = {
        statusCode: 200,
        // body must be a string //
        body: JSON.stringify(respDetails),
    };
    return response;
};

/**
 * Performs a request to the URL with the given details
 * @param {object} requestDetails
 * @param {object} bodyInput
*/
function httpRequest(requestDetails, bodyInput) {
  return new Promise((resolve, reject) => {
    var options = {
    host    : requestDetails.host,
    path    : requestDetails.path,
    method  : requestDetails.method,
    headers   : { "Content-type": "application/json" }
    }    

    // If there is no body passed in, use an empty JSON //
    if(!bodyInput){
        bodyInput = {};
    }

    let req = https.request(options, (res) => {
    if (res.statusCode < 200 || res.statusCode >= 300) {
        return reject(new Error('statusCode=' + res.statusCode));
    }
    var body = [];
    res.on('data', function(chunk) { body.push(chunk); });
    res.on('end', function() {
        try {
        body = JSON.parse(Buffer.concat(body).toString());
        } catch(e) {
        reject(e);
        }
        resolve(body);
    });
    });

    req.on('error', (e) => { reject(e.message); });

    req.write(JSON.stringify(bodyInput));
    req.end();
  });
}

Once you have copied the code into your script you will need to save it, but there is one more important step required before we can test the code.

You need to hit the “Deploy” button before your changes will be deployed.

Now we can test the Lambda function. When you create your first test you can leave the JSON body empty as we won't be sending any data to this Lambda, it will be triggered by an event which we will set up later.

Once you run the test you should see the response and some function logs.

NPM Modules

You can use the NPM module with Lambda functions, though the process is quite complicated and requires that you init and install npm packages locally and then upload the changes to your Lambda function to continue to use those modules. There is a guide on this process here. However, there is a much easier way to install NPM modules if you use the Cloud9 IDE instead of the Lambda script editor.

Having explained that you can install NPM modules, the question is should you use Lambdas like a Node.js project?

AWS advises that you should not do this, and instead, you should aim to keep your Lambda function as light as possible or create other functions for separate tasks, rather than maintaining a server-project in your Lambda function. Don't try to import dozens of modules or maintain a huge folder to custom-scripts in a single Lambda. You should split them up into separate Lambdas.

However, for something like HTTP networking it would be far more convenient to import something like Axios instead of creating your own networking code so the option is there if needed. Cloud9 Cloud9 is an online IDE which allows you to edit Lambda functions and connect them to services such as API Gateway. As a fully realised IDE, you can do things like debug your code inline and set breakpoints, which will speed up development time. Another feature of Cloud9 is that there is a terminal in the IDE which works just like the terminal you may be familiar with in any local IDE such as Visual Studio.

Using the terminal you can init an npm package and install modules directly, without needing to install locally and then upload a new file. You can also do all your commits and syncing to your repo from here so it is very convenient.

This is a paid service however, so you pay for the hours that you use it for. The service can be configured to automatically switch off if you have been idle for a certain amount of time and it usually takes <1min to start up. There are more details on the pricing here.

Cloud9

Cloud9 is an online IDE which allows you to edit Lambda functions and connect them to services such as API Gateway. As a fully realised IDE, you can do things like debug your code inline and set breakpoints, which will speed up development time. Another feature of Cloud9 is that there is a terminal in the IDE which works just like the terminal you may be familiar with in any local IDE such as Visual Studio.

Using the terminal you can init an npm package and install modules directly, without needing to install locally and then upload a new file. You can also do all your commits and syncing to your repo from here so it is very convenient.

This is a paid service however, so you pay for the hours that you use it for. The service can be configured to automatically switch off if you have been idle for a certain amount of time and it usually takes <1min to start up. There are more details on the pricing here.

Lambda Pricing

Lambda is a paid AWS service and the pricing can be quite complicated. The basics you need to know is that you are charged per-execution and for how long the script runs for. There are some other factors to take into account, but in essence you have to remember to keep your scripts simple and keep the execution time down.

Unfortunately, for this example, we are relying on a call out to a 3rd party service, so we cannot control how long that call might take to execute. We can make some effort to reduce this by choosing to deploy our Lambda closer to where the alternative service is deployed, i.e. EU or US regions. This will keep the round-trip time as short as possible.

There is a guide here if you wish to know more about how to work out your Lambda costs.

Triggering Platform Code

The example above covers the basics needed to execute HTTP requests but what about actually hitting endpoints on these platforms?

For Beamable and Accelbyte there are REST APIs available which will help you out with any out-of-the-box features you need to deal with through these scheduled scripts. However, if you wish to have custom code triggered from these scheduled events you will have to create that yourself.

Beamable

For Beamable you can achieve this using a Microservice. In our topic on Cloud-Code here you can see some examples of how to create Microservices and how you can hit them from REST. We would advise grouping these calls into a single Microservice so all the system-script functionality you need to port over to GameSparks can be deployed in the same Microservice.

AccelByte

With AccelByte there are two options. You can create your own game-server using their backend SDK for Go or JS, or you can employ their team to develop a custom Microservice for your game which will get deployed into your custom environment.

You would then use the endpoint on the custom made backend to run your system-scripts from the Lambda function.

CloudWatch Rules

Now that we have our Lambda function setup, we need a way to trigger it at scheduled intervals. We are going to use an AWS CloudWatch rule for this. The CloudWatch service offers a lot of monitoring and logging features and it is quite a big topic, so for now we are only going to cover the basics needed for triggering Lambdas.

Navigate to the CloudWatch service from the AWS services dashboard.

You’ll need to click on the “Rules” option from the menu on the left-hand-side of the page.

This will bring you to a setup guide which makes things very easy for you. First you can set the interval you want your script to execute at. These intervals are always done on UTC time.

You can also see the “Cron expression” option here, which is very useful for more complicated scheduling or specific times of the day you wish to schedule if midnight UTC is not suitable. You can find more information on that here.

Once your interval has been set up, you can link your Lambda function to this rule. There are option options available when setting this up but you can just choose the default ones for this example as we aren't passing any special information into our function.

Now you can give your rule a name and create it. Your rule is now ready to go!

Monitoring & Debugging

The next thing you’ll need is some way to ensure your rule is triggering and the scripts are performing correctly.

If you click on your rule and click on the link under “Monitoring”, you will be able to see a history of all executions for your rule.

Though we started this example with the everyday script, it is advisable to check it out and test it using an example that runs every minute until you know everything is working correctly.