Web hosting is a sub-module of LeanEngine that allows you to develop a web application with Java. It provides functions including cloud functions, hooks, hosting for static files, and custom routing, with your own domains bound to the service. You can use it to create a landing or download page for your mobile application, develop an admin console or a complete website, or run custom logic that has to be on the server side.
If you don't know how to create a LeanEngine project, debug it locally, or deploy it to the cloud, please first read LeanEngine Quick Start. Other related documents include:
LeanCache Guide (using the in-memory cache service to improve performance)
This guide uses Java as an example, but LeanEngine supports many other languages as well. You can choose the one you are familiar with for development:
Provided that you have [installed the command-line tool(leanengine_cli.html#installation), to create a new project from our example skelton, you just need one command:
lean init
Follow the prompts to enter the project information.
Running and Debugging Locally
Once all dependencies are installed, you can use our command-line interface in the project root directory to start a development server:
Run the following command in your project root directory:
lean deploy
Setting up Second-Level Domains
In the "Web Hosting Domain" section of your app's Dashboard > LeanEngine > Settings, you can fill in a custom second-level domain. For example, if you set it to be myapp, you can access your website through http://myapp.avosapps.us.
You may need to wait for a few hours until DNS settings take effect.
Our second-level domains support HTTPS by default.
If no request has been made to your app within the past 30 days and you haven't purchased a standard instance, the second-level domain may be recycled.
Project Skeleton
Your project has to follow the following structure to be recognized by LeanEngine and operate properly.
LeanEngine Java environment is constructed by Maven. For this reason, the LeanEngine Java project must contain $PROJECT_DIR/pom.xml as the startup file for the whole project. Once the building process is done, LeanEngine will search for a package under the directory $PROJECT_DIR/target:
WAR: If your project is built into a WAR file, LeanEngine will run it in a servlet container (currently Jetty 9.x).
JAR: If your project is built into a JAR file, LeanEngine will run java -jar <packageName>.jar.
We recommend that you use an example project as a starting point since you don't have to configure all the details:
java-war-getting-started: a minimal project that integrates the LeanCloud SDK and creates a WAR file to run as a servlet.
Java runtime requires more memory, so we recommend:
A project based on example project should use instances with at least 512 MB memory.
A project based on Spring Boot should use instances with at least 1 GB memory.
Simulate a reasonable workload locally and check how much memory your project uses. When choosing LeanEngine instances, make sure to leave some margin for traffic variation.
LeanEngine automatically sets -Xmx to be 70% of the size of the instance. The rest 30% will be reserved for off-heap memory and other purposes. If your project demands special requirements (like consuming more off-heap memory), you can set your own -Xmx parameter. For example, if the memory of your instance is 2 GB, you may go to "Custom environment variables" of LeanEngine's settings page and set the environment variable JAVA_OPTS to be -Xmx1500m in order to limit the size of JVM heap to be 1.5 GB and reserve the rest 500 MB for other purposes. Keep in mind that if -Xmx is too low, more CPU may be consumed for frequent GC tasks.
If an unsuitable instance size is picked, the deployment process may fail due to OOM error. The project may also restart frequently later on due to the same reason.
LeanEngine Java uses JRE 8 by default.
If you want to use other versions, you can specify java.runtime.version in system.properties file at the root of the project directory:
java.runtime.version=11
The Spring Boot template project currently only supports Java 8, so do not specify a version other than Java 8 in system.properties.
WAR Projects
First, confirm that Jetty plugin has been configured in pom.xml. The port of the web server can be obtained from the environment variable LEANCLOUD_APP_PORT. Please refer to our example code for reference.
Then use Maven to install dependencies and create the package:
mvn package
There are several ways to launch the project locally:
Launching WAR Projects with Command-Line Interface
Tip: Comparing to other methods, the command-line interface allows you to easier switch between different applications.
Launching WAR Projects with Environment Variables
The following commands set up the environment variables for LeanEngine and launch the project using the jetty plugin:
eval "$(lean env)"
mvn jetty:run
Tip: lean env outputs the commands for setting up the environment variables required for the current app. You can run it directly with eval.
Launching WAR Projects with Eclipse
First, confirm that the Maven plugin has been installed in Eclipse. Then import the project into Eclipse as a Maven Project. Right-click the project in the Package Explorer window and select Run As > Maven Build…. On the Main tab, set Goals to be jetty:run. Add the following environment variables on the Environment tab:
Name
Value
LEANCLOUD_APP_ENV
development
LEANCLOUD_APP_ID
{{appid}}
LEANCLOUD_APP_KEY
{{appkey}}
LEANCLOUD_APP_MASTER_KEY
{{masterkey}}
LEANCLOUD_APP_PORT
3000
Hit "run" to launch the project.
JAR Projects
Use Maven to install dependencies and create the package:
mvn package
There are several ways to launch the project locally:
Launching JAR Projects with Environment Variables
The following commands set up the required environment variables for LeanEngine and launch the project:
eval "$(lean env)"
java -jar target/{zipped jar file}
Tip: lean env outputs the commands for setting up the environment variables required for the current app. You can run it directly with eval.
Launching JAR Projects with Eclipse
First, confirm that the Maven plugin has been installed in Eclipse. Then import the project into Eclipse as a Maven Project. Right-click the project in the Package Explorer window, select Run As > Run Configurations…, select Application, and set Main class: (cn.leancloud.demo.todo.Application for the sample project). Add the following environment variables on the Environment tab:
Name
Value
LEANCLOUD_APP_ENV
development
LEANCLOUD_APP_ID
{{appid}}
LEANCLOUD_APP_KEY
{{appkey}}
LEANCLOUD_APP_MASTER_KEY
{{masterkey}}
LEANCLOUD_APP_PORT
3000
Hit "run" to launch the project.
Integration with Web Frameworks
LeanEngine Java depends on Servlet 3.1.0. You can use any web frameworks based on Servlet 3.1.0.
Using LeanStorage
LeanEngine uses LeanEngine Java SDK instead of LeanStorage Java SDK. The former is a superset of the latter with added support for cloud functions and hooks, so you can use any functions available for LeanStorage to store your data.
If you use the example project as the basis, the LeanEngine Java SDK has already been set up. You can follow the way it is used in the example project.
If you choose to start from scratch, you need to configure it as follows:
import com.avos.avoscloud.internal.impl.JavaRequestSignImplementation;
import cn.leancloud.LeanEngine;
// Obtain App ID from environment variable LEANCLOUD_APP_ID
String appId = System.getenv("LEANCLOUD_APP_ID");
// Obtain App Key from environment variable LEANCLOUD_APP_KEY
String appKey = System.getenv("LEANCLOUD_APP_KEY");
// Obtain Master Key from environment variable LEANCLOUD_APP_MASTER_KEY
String appMasterKey = System.getenv("LEANCLOUD_APP_MASTER_KEY");
LeanEngine.initialize(appId, appKey, appMasterKey);
// Delete the following line if you don't need to use the Master Key
JavaRequestSignImplementation.instance().setUseMasterKey(true);
Health Monitoring
While your project is being deployed, LeanEngine's hypervisor will check if it is started successfully every second. The deployment is considered a failure if the check still fails after 30 seconds. Even after the project is deployed successfully, we still run health checks regularly to ensure that your app is running normally. If the check fails, the LeanEngine hypervisor will automatically restart your app.
The URLs for health monitoring include the index page of your project (/) and /__engine/1/ping which is handled by the Java SDK. As long as one of them returns the HTTP status code 200, the project is considered to be normal. So make sure your program uses the Java SDK or has its index page return 200 as the HTTP status code. Besides this, in order to support cloud functions and hooks in LeanEngine, the hypervisor will use the URL /1.1/functions/_ops/metadatas to communicate with the Java SDK. Please make sure to have this URL handled by the Java SDK or return 404 as the HTTP status code to indicate that cloud functions and hooks are not used.
If you didn't use LeanEngine Java SDK, you need to handle the URL by yourself:
// Health monitoring
@WebServlet(name = "LeanEngineHealthServlet", urlPatterns = {"/__engine/1/ping"})
public class LeanEngineHealthCheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setHeader("content-type", "application/json; charset=UTF-8");
JSONObject result = new JSONObject();
result.put("runtime", System.getProperty("java.version"));
result.put("version", "custom");
resp.getWriter().write(result.toJSONString());
}
}
// Cloud function list
@WebServlet(name = "LeanEngineMetadataServlet", urlPatterns = {"/1.1/functions/_ops/metadatas"})
public class LeanEngineMetadataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
resp.setContentType("application/json; charset=UTF-8");
resp.getWriter().write("{\"result\":[]}");
}
}
Session Management
LeanEngine provides the component EngineSessionCookie that can be used to manage sessions of users (AVUser) with cookies. Add the following code after initialization if you need to use this component:
The following arguments are supported by the constructor of EngineSessionCookie:
secret: A string used to create the cookie signature, stored on the server. If you modified it, all the existing cookies will be invalidated, which means that all the sessions will expire.
maxAge: The time before the cookie expires (in seconds).
fetchUser: Whether or not to automatically fetch the currently logged in AVUser object (defaults to false). If it is set to be true, each HTTP request will initiate an API call to fetch the user object. If it is set to be false, you can only access the id (the objectId recorded in the _User table) and the sessionToken attribute of the AVUser.getCurrentUser() by default. You can manually fetch the entire user when needed.
You can implement a site with login feature like this:
LeanEngine Java environment supports basic classes including URL and HttpClient, but we recommend that you use a third party library like okhttp to send HTTP requests:
Now define the handler function for uploading files, build a Form object, and parse req as a parameter. This will save the uploaded file into a temporary directory, and construct the files object:
If your project uses cookies as an authentication method (like the SDK's CookieSession middleware), then there is a risk of CSRF attack which allows other sites to forge malicious requests with valid cookies.
CSRF tokens can be used to defend such attacks. A CSRF token is a random string generated by the server and passed to the client (usually through cookie). When the client makes a request, it must include the same CSRF token in the request body or the header. The server then verifies if the CSRF token is valid before processing the request.
Redirecting to HTTPS
For security consideration, it is recommended that all sites use HTTPS by default. LeanEngine supports such feature with a middleware that forces your website {App Domain}.avosapps.us to be accessed via HTTPS. Simply add the following code to have it enabled:
LeanEngine.setHttpsRedirectEnabled(true);
After your site is deployed to the production environment, all users accessing your website's second-level domain through HTTP will be redirected to HTTPS-enabled URLs.
Deploying and Publishing
Deploying with Command-Line Interface
Run the following command in your project root directory:
lean deploy
The command-line interface makes it easy to deploy projects, publish projects, view project status, and view logs. It allows you to deploy the same project to multiple applications as well. See Command-Line Interface Guide for more instructions.
Dependency Caching
LeanEngine implements a caching mechanism to speed up the build process (the process that installs dependencies for your project). For each new build, if the dependencies are not changed, the dependencies installed in the past will be reused and only the project code will be replaced.
The cached dependencies may become ineffective for various reasons, so it's not guaranteed that every build will make use of them.
If you are encountering problems with installing dependencies, you can enable the "Download latest dependencies" option when deploying on the web console, or add the --no-cache option when deploying with the command-line interface.
lean deploy --no-cache
Deploying from Git Repository
You can also deploy your project from a Git repository. LeanCloud doesn't offer version control services, so you need to push the project to a Git repository of your own choice. Good third-party websites that provide Git hosting services include GitHub, BitBucket, and GitLab.
After you push your code to a repository accessible from the Internet, please enter the URL of the Git repository (like https://github.com/<username>/<repoName>.git) into LeanEngine's settings page on the web console.
If the repository is private, you need to provide an SSH address (git@github.com:<username>/<repoName>.git) instead. You also need to provide the public key generated by LeanEngine as a deploy key to the Git service provider. For example, if you are using GitHub, you can add a deploy key by going to the repository's Settings > Deploy keys and click on Add deploy key.
After this, you will be able to deploy your project on the web console. It will deploy the code of the master branch by default, but you can specify a branch name, a label, or a specific commit when deploying.
If your repository contains submodules, LeanEngine will pull them automatically.
You can also set up a webhook so that each time you make a push to the Git repository, your project will be deployed from it.
To do so, go to your app's Dashboard > LeanEngine > Deploy > Deploy from git > Auto deploy to obtain the deploy token and webhook URL.
You can use the deploy token to construct HTTP requests to trigger deployments.
Filling in the code repository branch and LeanEngine environment, a corresponding webhook URL will be generated automatically.
The code from the specified branch will be deployed to the specified environment once the webhook URL receives any POST request.
For example, if you are using GitHub, you can go to your repository's Settings > Webhooks and add the URL as the Payload URL of a new webhook (leave other settings as default). By doing so, the designated branch will be deployed to LeanEngine each time you make a push to any existing branch. The reason we cannot perform a deployment based on the branch you are pushing to is that GitHub doesn't allow you to set up webhooks for specific branches, plus LeanEngine is not designing this feature for any specific platforms so it couldn't read the contents in a POST request.
However, you can use GitHub Actions to control the timing of your deployment in a more granular way. Please refer to the example shown on the dashboard.
Staging Environment and Production Environment
By default, you application has a production environment for LeanEngine and the corresponding domain is {App Domain}.avosapps.us. There is a trial instance in the production environment to run your project.
When the trial instance in the production environment is upgraded to a standard instance, there will be a new staging environment with the corresponding domain stg-{App Domain}.avosapps.us, with both environments accessing the same LeanStorage data. You can test your code by deploying it to the staging environment each time you make a change and publish it to the production environment when ready. If you want to have a test environment with an independent data source, you can create a separate application.
If you encounter the "Application not Found" error when accessing LeanEngine, it is usually because your code hasn't been deployed to the corresponding environment. This may be triggered when you attempt to access the staging environment when there isn't one or try to access the production environment without publishing your project.
Sometimes you may need to know the environment the current process is running in (development, staging, or production) and have your project behave differently:
String env = System.getenv("LEANCLOUD_APP_ENV");
if (env.equals("development")) {
// Development environment started by command-line interface
} else if (env.equals("production")) {
// Production environment
} else {
// Staging environment
}
In SDK, you can specify the environment where requests from clients are sent to:
AV.setProduction(true); // Production environment (default)
AV.setProduction(false); // Staging environment
leancloud.use_production(True) # Production environment (default)
leancloud.use_production(False) # Staging environment
# Call it before `leancloud.init`
LeanClient::useProduction(true); // Production environment (default)
LeanClient::useProduction(false); // Staging environment
AVCloud.setProductionMode(true); // Production environment (default)
AVCloud.setProductionMode(false); // Staging environment
Cloud Runtime Environment
System-Level Dependencies
You can specify system-level dependencies by changing systemDependencies of leanengine.yaml:
systemDependencies:
- imagemagick
LeanEngine supports the following dependencies:
ffmpeg: An audio and video processing tool and library.
imagemagick: An image processing tool and library.
phantomjs: A headless WebKit browser (deprecated).
chrome-headless: A headless Chrome browser (takes more time to be deployed and consumes a lot of CPU and memory; if you use puppeter, you need to pass {executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', '--disable-setuid-sandbox']} to puppeteer.launch; does not support Java).
node-canvas: System dependencies required for installing node-canvas (you still need to install node-canvas by yourself).
python-talib: A library for performing technical analysis of financial market data.
Adding system dependencies will slow down the deployment. Please don't add unused dependencies.
Environment Variables
LeanEngine provides the following environment variables by default:
Variable Name
Description
LEANCLOUD_APP_ID
The App ID of the current application.
LEANCLOUD_APP_KEY
The App Key of the current application.
LEANCLOUD_APP_MASTER_KEY
The Master Key of the current application.
LEANCLOUD_APP_ENV
Current environment:
Depending on how you start the local development instance, this variable may not exist or may be set to development.
Staging environment: stage.
Production environment: production.
LEANCLOUD_APP_PORT
The port listened by the project. Other ports are not accessible from the public network.
LEANCLOUD_API_SERVER
The URL used to access LeanStorage (looks like https://api.leancloud.cn). It is based on the location of the data center used to host the project and may change over time. You can use it when making requests to LeanStorage or other LeanCloud services with our REST API. Please do not use https://api.leancloud.cn directly in LeanEngine.
LEANCLOUD_AVAILABLE_CPUS
The number of CPUs available to the LeanEngine instance. It is based on the size of your instance and should be larger than 1 for large instances (like those with 2 CPUs and 1024 MB memory). Please do not use the number of CPUs of the operating system directly, or your project may be terminated if excessive threads are opened up.
LEANCLOUD_APP_GROUP
The group this instance belongs to. When using the LeanEngine Group Management feature, this becomes the name of the group.
LEANCLOUD_REGION
The region where the instance is located at. For LeanCloud International version, the value is US.
LEANCLOUD_VERSION_TAG
The instance deployment version.
You can also add custom environment variables in your app's Dashboard > LeanEngine > Settings > Custom environment variables. Variable names can only contain letters, numbers, and underscores, and can only begin with a letter. The value must be a string. The updated environment variables will take effect after the next deployment.
A common practice of using environment variables is to store configurations with them. By doing so, the behavior of your project can be changed by updating environment variables only without touching the code. You can also store secrets keys of third-party services as environment variables so that they are not exposed in the code.
The environment variables provided by LeanEngine cannot be overwritten by custom environment variables.
By default, the built-in and custom environment variables can only be read by the application at runtime.
If you want to read these environment variables while installing dependencies or compiling, add the following line to leanengine.yaml:
exposeEnvironmentsOnBuild: true
Load Balancing
On LeanEngine, requests from the clients go through a load balancer before they reach to your app. The load balancer handles SSL encryption and decryption, data compression, etc., so you don't have to add HTTPS- or gzip-related functions to your app.
Since the load balancer handles SSL encryption and decryption, the request URLs received by the web framework always start with http.
You need to check the X-Forwarded-Proto HTTP header to detect if the original requests use HTTP or HTTPS.
The load balancer also enforces limitations that the maximum size of each request is 100 MB (including uploading files to LeanEngine), the maximum time for processing each request is 60 seconds, and a WebSocket will be disconnected if no data goes through in the past 60 seconds.
File System
You can write temporary files into /home/leanengine or /tmp, up to 1 GB in total.
Each time a project is deployed to LeanEngine, a new container will be created. Even though you don't initiate deployments, the system may also occasionally perform clean-ups. Therefore, you can't treat the local file system as a persistent storage.
If the files written are relatively large, we recommend that you delete the files after using them. If more than 1 GB of disk space is used, you may receive "Disk quota exceeded" errors. In this situation, you can redeploy your project to clear out the files.
You can also export the logs of the past seven days to local files with the command-line interface.
Each line of log can contain no more than 4096 characters and the characters exceeding the limit will be discarded. There could be no more than 600 lines of logs output per minute and the lines exceeding the limit will be discarded.
We will try our best to avoid changing public IP addresses, but cannot eliminate the possibility of making changes. In the case of IP-related problems, please double check if the public IP addresses are changed.
Custom Domains
We recommend that you register your own domain and bind it to your LeanEngine production environment. You can bind a custom domain at Account settings > Domain binding.
Java Web Hosting Guide
Web hosting is a sub-module of LeanEngine that allows you to develop a web application with Java. It provides functions including cloud functions, hooks, hosting for static files, and custom routing, with your own domains bound to the service. You can use it to create a landing or download page for your mobile application, develop an admin console or a complete website, or run custom logic that has to be on the server side.
If you don't know how to create a LeanEngine project, debug it locally, or deploy it to the cloud, please first read LeanEngine Quick Start. Other related documents include:
This guide uses Java as an example, but LeanEngine supports many other languages as well. You can choose the one you are familiar with for development:
Starting with the Example Project
Provided that you have [installed the command-line tool(leanengine_cli.html#installation), to create a new project from our example skelton, you just need one command:
Follow the prompts to enter the project information.
Running and Debugging Locally
Once all dependencies are installed, you can use our command-line interface in the project root directory to start a development server:
For more information regarding command-line interface and local debugging, see Command-Line Interface Guide.
Deploying to the Cloud
Run the following command in your project root directory:
Setting up Second-Level Domains
In the "Web Hosting Domain" section of your app's Dashboard > LeanEngine > Settings, you can fill in a custom second-level domain. For example, if you set it to be
myapp
, you can access your website throughhttp://myapp.avosapps.us
.You may need to wait for a few hours until DNS settings take effect.
Our second-level domains support HTTPS by default.
If no request has been made to your app within the past 30 days and you haven't purchased a standard instance, the second-level domain may be recycled.
Project Skeleton
Your project has to follow the following structure to be recognized by LeanEngine and operate properly.
LeanEngine Java environment is constructed by Maven. For this reason, the LeanEngine Java project must contain
$PROJECT_DIR/pom.xml
as the startup file for the whole project. Once the building process is done, LeanEngine will search for a package under the directory$PROJECT_DIR/target
:java -jar <packageName>.jar
.We recommend that you use an example project as a starting point since you don't have to configure all the details:
java-war-getting-started
: a minimal project that integrates the LeanCloud SDK and creates a WAR file to run as a servlet.spring-boot-getting-started
: a minimal project using the Spring Boot framework that creates a JAR file.Java runtime requires more memory, so we recommend:
LeanEngine automatically sets
-Xmx
to be 70% of the size of the instance. The rest 30% will be reserved for off-heap memory and other purposes. If your project demands special requirements (like consuming more off-heap memory), you can set your own-Xmx
parameter. For example, if the memory of your instance is 2 GB, you may go to "Custom environment variables" of LeanEngine's settings page and set the environment variableJAVA_OPTS
to be-Xmx1500m
in order to limit the size of JVM heap to be 1.5 GB and reserve the rest 500 MB for other purposes. Keep in mind that if-Xmx
is too low, more CPU may be consumed for frequent GC tasks.If an unsuitable instance size is picked, the deployment process may fail due to OOM error. The project may also restart frequently later on due to the same reason.
LeanEngine Java uses JRE 8 by default. If you want to use other versions, you can specify
java.runtime.version
insystem.properties
file at the root of the project directory:The Spring Boot template project currently only supports Java 8, so do not specify a version other than Java 8 in
system.properties
.WAR Projects
First, confirm that Jetty plugin has been configured in
pom.xml
. The port of the web server can be obtained from the environment variableLEANCLOUD_APP_PORT
. Please refer to our example code for reference.Then use Maven to install dependencies and create the package:
There are several ways to launch the project locally:
Launching WAR Projects with Command-Line Interface
See Command-Line Interface Guide for more details.
Tip: Comparing to other methods, the command-line interface allows you to easier switch between different applications.
Launching WAR Projects with Environment Variables
The following commands set up the environment variables for LeanEngine and launch the project using the jetty plugin:
Tip:
lean env
outputs the commands for setting up the environment variables required for the current app. You can run it directly witheval
.Launching WAR Projects with Eclipse
First, confirm that the Maven plugin has been installed in Eclipse. Then import the project into Eclipse as a Maven Project. Right-click the project in the Package Explorer window and select Run As > Maven Build…. On the Main tab, set Goals to be
jetty:run
. Add the following environment variables on the Environment tab:LEANCLOUD_APP_ENV
development
LEANCLOUD_APP_ID
{{appid}}
LEANCLOUD_APP_KEY
{{appkey}}
LEANCLOUD_APP_MASTER_KEY
{{masterkey}}
LEANCLOUD_APP_PORT
3000
Hit "run" to launch the project.
JAR Projects
Use Maven to install dependencies and create the package:
There are several ways to launch the project locally:
Launching JAR Projects with Environment Variables
The following commands set up the required environment variables for LeanEngine and launch the project:
Tip:
lean env
outputs the commands for setting up the environment variables required for the current app. You can run it directly witheval
.Launching JAR Projects with Eclipse
First, confirm that the Maven plugin has been installed in Eclipse. Then import the project into Eclipse as a Maven Project. Right-click the project in the Package Explorer window, select Run As > Run Configurations…, select
Application
, and setMain class:
(cn.leancloud.demo.todo.Application
for the sample project). Add the following environment variables on the Environment tab:LEANCLOUD_APP_ENV
development
LEANCLOUD_APP_ID
{{appid}}
LEANCLOUD_APP_KEY
{{appkey}}
LEANCLOUD_APP_MASTER_KEY
{{masterkey}}
LEANCLOUD_APP_PORT
3000
Hit "run" to launch the project.
Integration with Web Frameworks
LeanEngine Java depends on Servlet 3.1.0. You can use any web frameworks based on Servlet 3.1.0.
Using LeanStorage
LeanEngine uses LeanEngine Java SDK instead of LeanStorage Java SDK. The former is a superset of the latter with added support for cloud functions and hooks, so you can use any functions available for LeanStorage to store your data.
If you use the example project as the basis, the LeanEngine Java SDK has already been set up. You can follow the way it is used in the example project.
If you choose to start from scratch, you need to configure it as follows:
Configure dependencies by adding LeanEngine Java SDK to
pom.xml
:Initialize the middleware by using your App Key:
Health Monitoring
While your project is being deployed, LeanEngine's hypervisor will check if it is started successfully every second. The deployment is considered a failure if the check still fails after 30 seconds. Even after the project is deployed successfully, we still run health checks regularly to ensure that your app is running normally. If the check fails, the LeanEngine hypervisor will automatically restart your app.
The URLs for health monitoring include the index page of your project (
/
) and/__engine/1/ping
which is handled by the Java SDK. As long as one of them returns the HTTP status code200
, the project is considered to be normal. So make sure your program uses the Java SDK or has its index page return200
as the HTTP status code. Besides this, in order to support cloud functions and hooks in LeanEngine, the hypervisor will use the URL/1.1/functions/_ops/metadatas
to communicate with the Java SDK. Please make sure to have this URL handled by the Java SDK or return404
as the HTTP status code to indicate that cloud functions and hooks are not used.If you didn't use LeanEngine Java SDK, you need to handle the URL by yourself:
Session Management
LeanEngine provides the component
EngineSessionCookie
that can be used to manage sessions of users (AVUser
) with cookies. Add the following code after initialization if you need to use this component:The following arguments are supported by the constructor of
EngineSessionCookie
:fetch
the currently logged inAVUser
object (defaults tofalse
). If it is set to betrue
, each HTTP request will initiate an API call tofetch
the user object. If it is set to befalse
, you can only access theid
(theobjectId
recorded in the_User
table) and thesessionToken
attribute of theAVUser.getCurrentUser()
by default. You can manuallyfetch
the entire user when needed.You can implement a site with login feature like this:
Logging in
Logging out
Profile Page
You can implement a simple login page (
login.jsp
) like this to be used with the handlers above:Implementing Common Features
Sending HTTP Requests
LeanEngine Java environment supports basic classes including
URL
andHttpClient
, but we recommend that you use a third party library likeokhttp
to send HTTP requests:Obtaining Client IP
You can get the client's IP directly from the
x-real-ip
field in the HTTP header:Uploading Files
Websites hosted on LeanEngine can handle file uploads with file-related APIs of LeanCloud Java SDK.
Assuming the frontend HTML code looks like this:
Now define the handler function for uploading files, build a
Form
object, and parsereq
as a parameter. This will save the uploaded file into a temporary directory, and construct thefiles
object:CSRF Tokens
If your project uses cookies as an authentication method (like the SDK's
CookieSession
middleware), then there is a risk of CSRF attack which allows other sites to forge malicious requests with valid cookies.CSRF tokens can be used to defend such attacks. A CSRF token is a random string generated by the server and passed to the client (usually through cookie). When the client makes a request, it must include the same CSRF token in the request body or the header. The server then verifies if the CSRF token is valid before processing the request.
Redirecting to HTTPS
For security consideration, it is recommended that all sites use HTTPS by default. LeanEngine supports such feature with a middleware that forces your website
{App Domain}.avosapps.us
to be accessed via HTTPS. Simply add the following code to have it enabled:After your site is deployed to the production environment, all users accessing your website's second-level domain through HTTP will be redirected to HTTPS-enabled URLs.
Deploying and Publishing
Deploying with Command-Line Interface
Run the following command in your project root directory:
The command-line interface makes it easy to deploy projects, publish projects, view project status, and view logs. It allows you to deploy the same project to multiple applications as well. See Command-Line Interface Guide for more instructions.
Dependency Caching
LeanEngine implements a caching mechanism to speed up the build process (the process that installs dependencies for your project). For each new build, if the dependencies are not changed, the dependencies installed in the past will be reused and only the project code will be replaced.
The cached dependencies may become ineffective for various reasons, so it's not guaranteed that every build will make use of them.
If you are encountering problems with installing dependencies, you can enable the "Download latest dependencies" option when deploying on the web console, or add the
--no-cache
option when deploying with the command-line interface.Deploying from Git Repository
You can also deploy your project from a Git repository. LeanCloud doesn't offer version control services, so you need to push the project to a Git repository of your own choice. Good third-party websites that provide Git hosting services include GitHub, BitBucket, and GitLab.
After you push your code to a repository accessible from the Internet, please enter the URL of the Git repository (like
https://github.com/<username>/<repoName>.git
) into LeanEngine's settings page on the web console.If the repository is private, you need to provide an SSH address (
git@github.com:<username>/<repoName>.git
) instead. You also need to provide the public key generated by LeanEngine as a deploy key to the Git service provider. For example, if you are using GitHub, you can add a deploy key by going to the repository's Settings > Deploy keys and click on Add deploy key.After this, you will be able to deploy your project on the web console. It will deploy the code of the
master
branch by default, but you can specify a branch name, a label, or a specific commit when deploying.If your repository contains submodules, LeanEngine will pull them automatically.
You can also set up a webhook so that each time you make a push to the Git repository, your project will be deployed from it. To do so, go to your app's Dashboard > LeanEngine > Deploy > Deploy from git > Auto deploy to obtain the deploy token and webhook URL. You can use the deploy token to construct HTTP requests to trigger deployments. Filling in the code repository branch and LeanEngine environment, a corresponding webhook URL will be generated automatically. The code from the specified branch will be deployed to the specified environment once the webhook URL receives any POST request.
For example, if you are using GitHub, you can go to your repository's Settings > Webhooks and add the URL as the Payload URL of a new webhook (leave other settings as default). By doing so, the designated branch will be deployed to LeanEngine each time you make a push to any existing branch. The reason we cannot perform a deployment based on the branch you are pushing to is that GitHub doesn't allow you to set up webhooks for specific branches, plus LeanEngine is not designing this feature for any specific platforms so it couldn't read the contents in a POST request. However, you can use GitHub Actions to control the timing of your deployment in a more granular way. Please refer to the example shown on the dashboard.
Staging Environment and Production Environment
By default, you application has a production environment for LeanEngine and the corresponding domain is
{App Domain}.avosapps.us
. There is a trial instance in the production environment to run your project.When the trial instance in the production environment is upgraded to a standard instance, there will be a new staging environment with the corresponding domain
stg-{App Domain}.avosapps.us
, with both environments accessing the same LeanStorage data. You can test your code by deploying it to the staging environment each time you make a change and publish it to the production environment when ready. If you want to have a test environment with an independent data source, you can create a separate application.If you encounter the "Application not Found" error when accessing LeanEngine, it is usually because your code hasn't been deployed to the corresponding environment. This may be triggered when you attempt to access the staging environment when there isn't one or try to access the production environment without publishing your project.
Sometimes you may need to know the environment the current process is running in (development, staging, or production) and have your project behave differently:
In SDK, you can specify the environment where requests from clients are sent to:
Cloud Runtime Environment
System-Level Dependencies
You can specify system-level dependencies by changing
systemDependencies
ofleanengine.yaml
:LeanEngine supports the following dependencies:
ffmpeg
: An audio and video processing tool and library.imagemagick
: An image processing tool and library.phantomjs
: A headless WebKit browser (deprecated).chrome-headless
: A headless Chrome browser (takes more time to be deployed and consumes a lot of CPU and memory; if you usepuppeter
, you need to pass{executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', '--disable-setuid-sandbox']}
topuppeteer.launch
; does not support Java).node-canvas
: System dependencies required for installingnode-canvas
(you still need to installnode-canvas
by yourself).python-talib
: A library for performing technical analysis of financial market data.Adding system dependencies will slow down the deployment. Please don't add unused dependencies.
Environment Variables
LeanEngine provides the following environment variables by default:
LEANCLOUD_APP_ID
LEANCLOUD_APP_KEY
LEANCLOUD_APP_MASTER_KEY
LEANCLOUD_APP_ENV
development
.stage
.production
.LEANCLOUD_APP_PORT
LEANCLOUD_API_SERVER
https://api.leancloud.cn
). It is based on the location of the data center used to host the project and may change over time. You can use it when making requests to LeanStorage or other LeanCloud services with our REST API. Please do not usehttps://api.leancloud.cn
directly in LeanEngine.LEANCLOUD_AVAILABLE_CPUS
LEANCLOUD_APP_GROUP
LEANCLOUD_REGION
US
.LEANCLOUD_VERSION_TAG
You can also add custom environment variables in your app's Dashboard > LeanEngine > Settings > Custom environment variables. Variable names can only contain letters, numbers, and underscores, and can only begin with a letter. The value must be a string. The updated environment variables will take effect after the next deployment.
A common practice of using environment variables is to store configurations with them. By doing so, the behavior of your project can be changed by updating environment variables only without touching the code. You can also store secrets keys of third-party services as environment variables so that they are not exposed in the code.
The environment variables provided by LeanEngine cannot be overwritten by custom environment variables.
By default, the built-in and custom environment variables can only be read by the application at runtime. If you want to read these environment variables while installing dependencies or compiling, add the following line to
leanengine.yaml
:Load Balancing
On LeanEngine, requests from the clients go through a load balancer before they reach to your app. The load balancer handles SSL encryption and decryption, data compression, etc., so you don't have to add HTTPS- or gzip-related functions to your app. Since the load balancer handles SSL encryption and decryption, the request URLs received by the web framework always start with
http
. You need to check theX-Forwarded-Proto
HTTP header to detect if the original requests use HTTP or HTTPS.The load balancer also enforces limitations that the maximum size of each request is 100 MB (including uploading files to LeanEngine), the maximum time for processing each request is 60 seconds, and a WebSocket will be disconnected if no data goes through in the past 60 seconds.
File System
You can write temporary files into
/home/leanengine
or/tmp
, up to 1 GB in total.Each time a project is deployed to LeanEngine, a new container will be created. Even though you don't initiate deployments, the system may also occasionally perform clean-ups. Therefore, you can't treat the local file system as a persistent storage.
If the files written are relatively large, we recommend that you delete the files after using them. If more than 1 GB of disk space is used, you may receive "Disk quota exceeded" errors. In this situation, you can redeploy your project to clear out the files.
Logs
You can view LeanEngine's deployment and runtime logs at Dashboard > LeanEngine > App logs. The logs can be filtered by levels.
You can also export the logs of the past seven days to local files with the command-line interface.
Each line of log can contain no more than 4096 characters and the characters exceeding the limit will be discarded. There could be no more than 600 lines of logs output per minute and the lines exceeding the limit will be discarded.
LeanEngine's access logs can be exported at Dashboard > LeanEngine > Access logs.
Time Zones
The time zone used on the server is UTC.
Public IP Addresses
If you need to configure IP whitelists on third-party services and need to obtain LeanEngine's public IP addresses, please go to Dashboard > LeanEngine > Settings > Public IP addresses.
We will try our best to avoid changing public IP addresses, but cannot eliminate the possibility of making changes. In the case of IP-related problems, please double check if the public IP addresses are changed.
Custom Domains
We recommend that you register your own domain and bind it to your LeanEngine production environment. You can bind a custom domain at Account settings > Domain binding.