Augment

Overview

Augment is a service which allows you to extend our services even further by combining them in new and unique ways. Augment has two main features as follows:

  • Serverless Functions to help you manage the custom logic you wrote in Golang, Java, .NET, Python, Ruby, PHP, or NodeJS and hook that logic to any of our services.
  • Function Triggering enables you to trigger your function to run in two ways, through either Event or HTTP Requests.

Some examples of how to use Augment to customize our services include:

  • Bridging account management and wallet functions to credit a new player account with virtual money that can be used in your in-game store.
  • Create your own API functions, with logic written on the server.

How It Works

Augment lets you write functions that are able to connect between various AccelByte services to help you extend their functionality, by listening to the AccelByte Kafka event stream for those services.

augment

As shown in the diagram, events that occur will trigger your function to generate new custom events. You can also choose to expose your function to our REST API platform from the Admin Portal Based on the diagram, the event that happens in Justice Kafka will trigger your function to generate new custom events. You can also choose to expose your function to our REST API platform using the Admin Portal.

Managing Serverless Functions

Augment enables you to write logic as serverless functions. You can define the runtime to compile or run these functions. The supported runtimes and versions are listed below:

RuntimeVersions
Golanggo1.10, go1.11, go1.12
Javajava1.8, java11
Node JSnodejs6, nodejs8, nodejs10, nodejs12, nodejs_distroless8, nodejsCE8
PHPphp7.2, php7.3
Pythonpython2.7, python3.4, python3.6, python3.7
Rubyruby2.3, ruby2.4, ruby2.5, ruby2.6
JVMjvm1.8
C#.NET Core 2.0, .NET Core 2.1.

Function Triggering

You can choose what types of events cause your function to trigger. In addition, functions can also be triggered by HTTP requests if they’re exposed to the REST API. Listed below are events that can be used to trigger your function.

TopicUsage
userAccountTriggers the function when there is a change to a user’s account.
userAuthenticationTriggers the function when there is a change to a user’s authentication.
userInformationTriggers the function when there is a change to a user’s personal information, such as their display name or country.
userPermissionsTriggers the function when there is a change to a user’s permissions.
userRolesTriggers the function when there is a change to a user’s roles.
countryAgeRestrictionTriggers the function when there is a change to a country’s age restriction.

Built-in Database

Your custom logic can be stored in a database using Augment’s built-in database feature. Augment will have access to this database by providing the credentials that have been included in your custom logic using the following environment variables:

VariablesRemarks
BUILTIN_DB_USER_NAMEUsername for the built-in database
BUILTIN_DB_USER_PASSWORDPassword for the built-in database
BUILTIN_DB_NAMEName of the built-in database

Those environment variables work only for their respective namespace, and cannot be used for other namespaces.

Tutorials

Here you’ll learn how to create a function, and manage the functions you’ve created. In these examples, we’ll create a function that credits new users with 100 USD in their wallet.

Create a Function

  1. Go to the Function Configurations section of the Admin Portal and click the Function menu.

    augment

  2. Click Create Function.

    augment

  3. Fill in the Create Augment form with the appropriate values:

    augment

    a. Input the Function Name. Make sure you choose a name that’s descriptive so that your function is easy to find.

    b. Input the Handler with the name of the function that is going to be executed inside the Function Code field. For this example, the function name is credit_wallet.

    c. Input the Environment Variables if your function requires any configurations to run such as ID, username, and password. For this example, leave this field empty.

    d. To enable triggers, set the Trigger Type to kafka-trigger. After enabling triggers, the Trigger Name and Topic fields will appear.

    • Input the name of the trigger in the Trigger Name field. Input something descriptive and easy to understand.
    • Set the Topic to the Kafka topic you want to trigger the function. For this example, choose either userInformation or userAccount.

    e. Select the Expose Function URL option to expose your function to the REST API. If you choose to expose the function, the endpoint will be generated after the function has been created. For this example, leave this option cleared.

    f. Set the Runtime. The runtime you choose will automatically define the Syntax language to be used in the functionCode and dependencyCode sections. For this example, select any Python 3 runtime.

    g. Fill in the Function Code with the logic you want to create. The function should be a function that accepts events and context as the input. Below is an example Function Code in Python that credit’s a new user’s wallet with 100 USD.

    import requests
    import os
    import base64
    import json
    def credit_wallet(event, context):
    user_data = event['data']
    token_url = "http://justice-iam-service.demo/iam/oauth/token"
    basic_auth_string = os.environ['IAM_CLIENT_ID'] + ":" + os.environ['IAM_CLIENT_SECRET']
    basic_auth = "Basic " + base64.b64encode(basic_auth_string.encode("utf-8")).decode("utf-8")
    grant_request_body = {'grant_type':'client_credentials','username':'','password':'','refresh_token':'','code':'','redirect_url':'','namespace':''}
    grant_request_headers = {'Authorization':basic_auth}
    grant_token_response = requests.post(token_url, data=grant_request_body, headers=grant_request_headers)
    print(grant_token_response.content)
    token_json = json.loads(grant_token_response.content.decode("utf-8"))
    credit_wallet_url = "http://justice-platform-service.demo/platform/admin/namespaces/accelbyte/users/" + user_data['userId'] + "/wallets/USD/credit"
    body = '''{"amount":100, "source":"PURCHASE", "reason":"string"}'''
    headers = {'content-type':'application/json', 'Authorization':"Bearer " + token_json['access_token']}
    r = requests.put(credit_wallet_url, data=body, headers=headers)
    print(r)
    return event['data']

    h. Fill in the Dependency Code with the list of dependencies for the function code. Below is an example of a Dependency Code.

    certifi==2019.11.28
    chardet==3.0.4
    idna==2.8
    pg8000==1.13.2
    requests==2.22.0
    scramp==1.1.0
    urllib3==1.25.8

    augment

  4. When you’re done, click Add and you’ll be directed to the Functions page.

Augment Built-in Database Function

You can create an Augment function and integrate it with a built-in database by providing the credentials that have been included in your function. The example below is a reference on how to insert data into your built-in database.

Function Code

from pymongo import MongoClient
import urllib.parse
import os
def test_func(event, context):
// this example shows how to use Augment built-in database to record data in `mydict`
username = urllib.parse.quote_plus(os.environ['BUILTIN_DB_USER_NAME'])
password = urllib.parse.quote_plus(os.environ['BUILTIN_DB_USER_PASSWORD'])
dbName = urllib.parse.quote_plus(os.environ['BUILTIN_DB_NAME'])
db_url = os.environ['BUILTIN_DB_HOST']
client = MongoClient('mongodb://%s:%s@%s' % (username, password, db_url))
mydb = client[dbName]
mycol = mydb["sample-collection"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
return "ok"

Dependency Code

pymongo
tip

You can also integrate the function with the Augment Built-in Database SDK.

Managing Your Functions

Expose a Function

  1. In the Admin Portal, choose the function you want to edit and click View.

    augment

  2. In the Augment Details panel, you can see the Function URL.

    augment

    info

    To check that the URL is valid, you can make a request to the generated URL using the following code:

    curl --location --request POST 'https://augment00.demo.accelbyte.io/accelbyte-test-expose-credit-c354' \
    --header 'Content-Type: application/json' \
    --data-raw '{"userId":"d6141d820b83466295080420613ab66d"}'
    • Upon successful request, the function will return this response:

      {
      "userId": "d6141d820b83466295080420613ab66d"
      }

Check the Uploaded Function

There are two ways to check if your function is working properly: you can either check through the Users menu or Wallet. Before you begin, make sure you have the User ID of a newly created user.

Via the Users Menu

  1. In the Admin Portal, go to User Management and click on the User menu.

    augment

  2. Search for the newly created User ID and you will be directed to the user page.

    augment

  3. Check the wallet section. They should have a credit of 100 USD.

    augment

Via the Wallet menu

  1. In the Admin Portal, go to the E-Commerce section and click on the Wallet menu.

    augment

  2. Search for the newly created User ID and you will be directed to the user page.

    augment

  3. Go to the Wallet column. A credit of 100 USD should be listed.

    augment

Augment SDK

We’ve created an SDK for Python 3 to help you by simplifying the API call to our services. The SDK covers Wallet and Statistics services, so it can be used to add credit to a player’s wallet, debit from a player’s wallet, or manage player statistics.

Implementing the Python SDK

Follow these steps to implement the Augment Python SDK in your function.

  1. In the Admin Portal, choose your desired function from the Function List on the Functions page. Then, click View to go to your Function Configurations.

    augment

  2. Here you can see your Function Configurations, along with the Function Code and Dependency Code you created earlier.

    augment

  3. Add the following code to the Function Code:

    from justice import Justice
  4. When you’re done, the Function and Dependency Code will look like this.

    from justice import Justice
    def credit_wallet(event, context):
    namespace = 'accelbyte'
    endpoint = "https://demo.accelbyte.io"
    core = Justice(namespace, endpoint)
    user_data = event['data']
    r = core.wallet.credit(user_data['userId'], 100, 'USD')
    return event['data']

    augment

Built-in Database SDK

To simplify the initialization of the built-in database mongo client, we provide an Augment SDK for Python 3. The Augment Built-in Database is a MongoDB instance, and the SDK utilizes PyMongo methods to operate on the database. You can create new functions and enter functions and dependency codes based on the desired functionality such as inserting data, retrieving data, and searching for data with Regex.

Insert Data into the Augment Built-in Database

Insert a Single Piece of Data into the Augment Built-in Database

The function code example below shows how to insert a single piece of data into a collection named sample-collection in the Augment database.

Function Code

from datastore import MongoDB
def insert_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
try:
augment_mongoclient.builtin_db[collection_name].insert_one(data)
except Exception as e:
return str(e)
data.pop('_id', None)
return data

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the data that you want to insert into the database, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"some": "test"
}'

After successfully calling the function, the data will be stored in the defined collection in the database.

Insert Multiple Pieces of Data into the Augment Built-in Database

The function code example below shows how to insert multiple pieces of data into a collection named sample-collection in the Augment database.

Function Code

import json
from datastore import MongoDB
def insert_many_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
try:
augment_mongoclient.builtin_db[collection_name].insert_many(data)
except Exception as e:
return str(e)
for element in data:
element.pop('_id', None)
return_data = json.dumps(data, indent=4)
return return_data

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the data you want to insert into the database, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '[
{"some": "test"},
{"some2": "test2"}
]'

After successfully calling the function, the data will be stored in the defined collection in the database.

Retrieve Data from the Augment Built-in Database

Retrieve Selected Data from the Augment Built-in Database

The function code example below shows how to retrieve selected data from a collection named sample-collection in the Augment database.

Function Code

from datastore import MongoDB
def get_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
try:
get_data = augment_mongoclient.builtin_db[collection_name].find_one(data)
except Exception as e:
return str(e)
if get_data is not None:
get_data.pop('_id', None)
else:
return "data not found"
return get_data

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the data you want to receive from the database, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"some": "test"
}'

After successfully calling the function, you will retrieve the data from the defined collection in the database.

Retrieve All Data from the Augment Built-in Database

The function code example below shows how to retrieve all of the data from a collection named sample-collection in the Augment database.

Function Code

import json
from datastore import MongoDB
def list_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
try:
get_data = augment_mongoclient.builtin_db[collection_name].find()
except Exception as e:
return str(e)
find_value = []
if get_data is not None:
for element in get_data:
print(element)
element.pop('_id', None)
find_value.append(element)
else:
return "no data found"
return_value = json.dumps(find_value, indent=4)
return return_value

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. Here is an example of the request body:

curl --location --request GET '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json'

After successfully calling the function, you will retrieve the data from the defined collection in the database.

Update Data in the Augment Built-in Database

The function code example below shows how to update selected data from a collection named sample-collection in the Augment database.

Function Code

from datastore import MongoDB
def update_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
old_data = {"name": data['old_name'], "company": data['old_company']}
new_data = {"name": data['new_name'], "company": data['new_company']}
try:
update_result = augment_mongoclient.builtin_db[collection_name].replace_one(old_data, new_data)
if update_result.matched_count == 0:
return "no matching data"
except Exception as e:
return str(e)
new_data.pop('_id', None)
return new_data

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the existing data and its replacement, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"old_name": "test",
"old_company": "company",
"new_name": "testupdate",
"new_company": "companyupdate"
}'

After successfully calling the function, the data will be updated and stored in the defined collection in the database.

Delete Data in the Augment Built-in Database

The function code example below shows how to delete selected data from a collection named sample-collection in the Augment database.

Function Code

from datastore import MongoDB
def delete_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
try:
delete_result = augment_mongoclient.builtin_db[collection_name].delete_one(data)
if delete_result.deleted_count == 0:
return "data not found"
except Exception as e:
return str(e)
return "ok"

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the data you want to delete, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"some": "test"
}'

After successfully calling the function, the data will be deleted from the defined collection in the database.

Search Data with Regex in the Augment Built-in Database

The function code example below shows how to use Regex to search for data from a collection named sample-collection in the Augment database.

Function Code

import json
from datastore import MongoDB
def list_data_builtindb(event, context):
augment_mongoclient = MongoDB()
collection_name = "sample-collection"
data = event['data']
name = data.get("name", "")
company = data.get("company", "")
try:
get_data = augment_mongoclient.builtin_db[collection_name].find({"$and": [
{"name": {'$regex': name}},
{"company": {'$regex': company}}
]})
except Exception as e:
return str(e)
find_value = []
if get_data is not None:
for element in get_data:
element.pop('_id', None)
find_value.append(element)
if len(find_value) == 0:
return "no matching data found"
else:
return "no data found"
return_value = json.dumps(find_value, indent=4)
return return_value

Dependency Code

justice-augment-python-sdk

You can call this function using the URL generated by the HTTPS Expose function. The request body should contain the data you are searching for, as seen in the example below:

curl --location --request POST '<FUNCTION_EXPOSE_HTTPS_URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"some": "test"
}'

After successfully calling the function, you will retrieve the search results from the database.

What’s Next?

  • If you’re interested in Early Access to Augment, we’d love to talk to you. Shoot us an email about your project to get started.
  • Check out the API Reference to learn more about Augment.