Verificando autenticación…

Skip to main content

Documentation: Template Java Cloud Function

Purpose and Scope

This project serves as a base template for creating Google Cloud Functions using Java 21 and Gradle. The main purpose is to provide an initial project structure, build configuration, and a simple functional example ("Hello World") that can be deployed as an HTTP function.

Objectives:

  • Provide a standardized starting point for Cloud Function development in Java.
  • Facilitate local environment setup and the build process.
  • Integrate basic best practices, such as including a security header.
  • Define the structure for deployment through CI/CD pipelines.

Scope:

  • Creation of a simple HTTP Cloud Function.
  • Configuration for building with Gradle and Java 21.
  • Instructions for local execution and unit testing.
  • Deployment guide on Google Cloud Platform.
  • Does not include, by default, integrations with other services such as Pub/Sub, Cloud Storage, Redis, Kafka, etc., but is designed to be extensible.

Architecture

The project is designed to be deployed as a Google Cloud Function, which is a serverless compute component offered by Google Cloud Platform (GCP). The function runs in response to events, in this case, an HTTP request.

Overview:

  • Serverless: There are no servers to manage. GCP handles the underlying infrastructure.
  • HTTP Trigger: The example function (com.latam.template.java.function.Function) is invoked through an HTTP request.
  • Runtime Environment: Java 21 (configured for Cloud Functions Gen2).
  • Scalability: GCP automatically scales the number of function instances based on demand.

No visual architecture diagram is included in this template. A typical diagram would show a client making an HTTP request to a Cloud Function endpoint, the function processing the request, and returning a response.

Technologies and Dependencies

The following are the main technologies and libraries used in this template project:

  • Programming Language: Java 21
  • Cloud Functions Framework:
    • com.google.cloud.functions:functions-framework-api:1.1.0 (API for developing functions)
    • com.google.cloud.functions.invoker:java-function-invoker:1.3.1 (For local execution)
  • Build Tool and Dependency Management: Gradle 7.6.4 (according to gradle-wrapper.properties)
  • Testing:
    • JUnit 4.13.2
    • Google Truth 1.1.5
    • Mockito Core 4.11.0
  • Deployment:
    • Google Cloud Platform (Cloud Functions)
    • GitLab CI/CD (using $LATAM_PIPELINE_CLOUD_FUNCTION_DEPLOY)
  • Artifact Repository: JFrog Artifactory (configured in gradle/latam-repo.gradle)

Local Configuration

Prerequisites

  • JDK (Java Development Kit) version 21.
  • Git.
  • Gradle (optional, since the project includes a ./gradlew wrapper that will download the correct version).
  • Access to JFrog Artifactory with valid credentials (username and password/API key).
  • Development IDE (optional, e.g., IntelliJ IDEA, Eclipse).

Configuration Steps

  1. Clone the repository: Follow the steps below

  2. Configure Artifactory credentials: Create a gradle.properties file at the project root (this file is excluded by .gitignore) with your JFrog Artifactory credentials.

    ARTIFACTORY_BASE_URL=https://artifactoryrepo1.appslatam.com/artifactory/
    ARTIFACTORY_GRADLE_CORP_REPO=corp-libs-gradle-release
    ARTIFACTORY_USERNAME=<your_artifactory_username>
    ARTIFACTORY_PASSWORD=<your_artifactory_api_key_or_token>

    These variables can also be configured as system environment variables.

  3. Build the project: Use the Gradle wrapper to build the project. This will download dependencies and generate the required artifacts.

    ./gradlew clean build
  4. Run the function locally: You can run the Cloud Function on your local machine using the Functions Framework invoker.

    ./gradlew runFunction -Prun.functionTarget=com.latam.template.java.function.Function -Prun.port=8080

    Once started, the function will be listening at http://localhost:8080. You can test it by accessing this URL from a browser or a tool like curl.

Deployment

Automated Deployment (GitLab CI/CD)

Deployment of this Cloud Function is primarily managed through GitLab CI/CD pipelines.

  • The .gitlab-ci.yml file includes the $LATAM_PIPELINE_CLOUD_FUNCTION_DEPLOY component, which automates the process.
  • Environment-specific deployment configuration for each environment (develop, cert, intg, prod) is defined in the YAML files within the deploy/env/ directory.
  • Key Cloud Function parameters such as runtime, memory, timeout, and service account are defined in deploy/function/runtime-config.yaml.erb:
    runtime: java21
    memory: 1024MB
    timeout: 540s
    region: "<%= region %>"
    trigger-http: ~
    execution-environment: gen2
    entry-point: com.latam.template.java.function.Function
    update-labels: "cmdb-<%= cmdb_it_element %>=<%= cmdb_it_element %>"
    service-account: "<%= service_account %>"
  • Environment variables for the function are managed through deploy/function/environment.yaml.erb and the corresponding environment files (e.g., deploy/env/dev.yaml).

Manual Deployment (gcloud CLI)

If a manual deployment is necessary, the gcloud CLI tool can be used. The project readme.md file lists several configuration options available for the gcloud functions deploy command. A basic example could be:

gcloud functions deploy FUNCTION_NAME \
--runtime java21 \
--trigger-http \
--entry-point com.latam.template.java.function.Function \
--region YOUR_REGION \
--project YOUR_PROJECT_ID \
--source . \
--service-account YOUR_SERVICE_ACCOUNT_EMAIL \
--allow-unauthenticated # Or configure IAM as needed

Make sure to adjust the parameters (FUNCTION_NAME, YOUR_REGION, etc.) according to your needs.

API Endpoints

The example function exposed by this template is a simple HTTP function.

HTTP MethodExpected Route on Cloud FunctionDescriptionAuthenticationExpected Response Example (Body)Response Headers Included
GET (or other HTTP methods)/ (function root route)Returns a "Hello World!" greeting message.Depends on GCP config (--allow-unauthenticated or IAM)Hello World!Strict-Transport-Security: max-age=31536000; includeSubDomains

Request Example (using curl):

curl http://localhost:8080/ # During local execution
# or the URL of the function deployed on GCP

Example Response (200 OK):

  • Body:
    Hello World!
  • Headers:
    • Content-Type: text/plain (or similar, may depend on the exact invoker/GCP configuration)
    • Strict-Transport-Security: max-age=31536000; includeSubDomains

Specific Components

This is a base template and, as such, does not include complex integrations with other GCP services (such as Pub/Sub, Cloud Storage, Firestore, Redis, Kafka, etc.) out of the box. Its goal is to provide a minimal functional structure.

To add specific functionality:

  1. Add Dependencies: Include the necessary client libraries in gradle/dependencies.gradle.
  2. Configuration: Add the required configuration properties (e.g., in application.yaml if using Spring Boot, or directly as environment variables for the Cloud Function).
  3. Implementation: Develop the business logic in your Java classes, using the APIs of the corresponding services.
  4. Service Account Permissions: Ensure that the Service Account used by the Cloud Function has the necessary IAM permissions to interact with the GCP services you integrate.

Testing

The project is configured to support unit testing using JUnit, Google Truth, and Mockito.

Running Tests

To run all unit tests defined in the project, use the following Gradle command:

./gradlew test

Test results will be generated in the build/reports/tests/test/ directory.

Writing Tests

  • Unit tests are typically located in the src/test/java directory.
  • It is recommended to follow best practices for naming test classes (e.g., MyClassTest.java) and test methods.

Security Considerations

  • Security Headers: The example function includes the Strict-Transport-Security header to improve security in HTTPS communications.
    response.appendHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
  • Credential Management:
    • Artifactory: Credentials (ARTIFACTORY_USERNAME, ARTIFACTORY_PASSWORD) should be managed securely. It is recommended to use a local gradle.properties file (not committed) or environment variables in CI/CD systems.
    • Google Cloud Platform (GCP): The Cloud Function runs with a Service Account. Ensure that this Service Account has the minimum necessary permissions (Principle of Least Privilege) to operate. Service Account credentials are managed by GCP.
  • Endpoint Authentication: By default, Cloud Functions can be public (--allow-unauthenticated) or require authentication/authorization through IAM. Configure this according to your application's security requirements.
  • Dependencies: Keep project dependencies up to date to mitigate known vulnerabilities. Periodically review security reports for the libraries used.