Pandastack Documentation
  • Welcome
  • Getting Started
    • Quickstart
      • Getting Started
    • Projects
      • Static Website
        • Configure your static website
          • Pre-defined ENV for static websites
      • Conatinered Website
        • How to configure nodejs project
        • How to Configure Python projects
        • How to Configure GO project
        • Docker runtime Projects
        • Private Connection with database.
        • Override default ENV
    • Databases
      • MySQL
      • PostgreSQL
      • Redis
      • MongoDB
      • TimeScaleDB
    • Monitoring
      • Uptime Check
      • SSL monitoring
      • Monitors pricing
    • Analytics
    • SSO
      • Google
      • Azure
    • Managed Apps
      • Wordpres
      • Directus
      • Strapi
      • Consul
      • Jenkins
    • PandaEdge
      • Deploy a nodejs function
      • Deploy a python function
      • Panda Edge pricing
Powered by GitBook
On this page
  • Edge Functions User Guide
  • Table of Contents
  • Creating a Function
  • Supported Runtimes
  • Function Structure
  • Environment Variables & Parameters
  • Function Limits
  • Deploying Functions
  • Testing Functions
  • Monitoring & Logs
  • Examples
  • Troubleshooting
  1. Getting Started

PandaEdge

Edge Functions User Guide

Edge Functions allow you to run custom code at the edge of the network, closer to your users for faster response times. This guide will help you understand how to create, deploy, and manage your edge functions effectively.

Note: We are constantly evolving to make better life for developers and as of now we have limited resources. Please be patient and contact support team if something is not working.

Table of Contents

  1. Creating a Function

  2. Supported Runtimes

  3. Function Structure

  4. Environment Variables & Parameters

  5. Function Limits

  6. Deploying Functions

  7. Testing Functions

  8. Monitoring & Logs

  9. Examples

  10. Troubleshooting

Creating a Function

Using the UI

  1. Navigate to the Edge Functions section in your dashboard

  2. Click the "Create Function" button

  3. Fill in the basic information:

    • Function Name: Choose a unique name (4-12 characters, lowercase letters, numbers, and hyphens only)

    • Runtime: Select your preferred programming language and version

  4. Write your code or upload a zip file containing your function files

  5. Configure memory, timeout, and environment variables

  6. Click "Deploy" to create your function

Function Naming

  • Names must be 4-12 characters long

  • Only lowercase letters, numbers, and hyphens are allowed

  • A random 6-character suffix will be added to your function name during deployment

Supported Runtimes

Our platform supports multiple programming languages:

Runtime
Versions
Main File

Node.js

14, 16, 18, 20

index.js

Python

3, 3.9

main.py

Java

8

Main.java

Swift

5.1

main.swift

PHP

7.4

index.php

Ruby

2.5

main.rb

Go

1.15

main.go

Rust

1.54

main.rs

.NET

3.1

Main.cs

Ballerina

0.990

main.bal

Function Structure

Each function must have a main handler that processes incoming requests. The structure varies slightly depending on the programming language.

Node.js Example

/**
 * Edge Function Handler
 * @param {object} params - Parameters passed to the function
 * @returns {object} Response object
 */
function main(params) {
    // Log the received parameters
    console.log('Received params:', params);

    // Your business logic here
    const result = {
        message: 'Hello from Node.js!',
        timestamp: new Date().toISOString(),
        params: params
    };

    // Return the response
    return {
        statusCode: 200,
        body: result
    };
}

Python Example

import json
from datetime import datetime

def main(params):
    """
    Edge Function Handler
    Args:
        params: Parameters passed to the function
    Returns:
        dict: Response object
    """
    # Log the received parameters
    print('Received params:', json.dumps(params))

    # Your business logic here
    result = {
        'message': 'Hello from Python!',
        'timestamp': datetime.now().isoformat(),
        'params': params
    }

    # Return the response
    return {
        'statusCode': 200,
        'body': result
    }

Environment Variables & Parameters

Setting Environment Variables

You can set environment variables in two ways:

  1. Through the UI: When creating or editing a function, use the Environment Variables section

  2. During deployment: Add them to your request when using the API

Environment variables are passed to your function through the params object.

Using Parameters

Parameters are passed to your function through the params object. There are multiple ways to pass parameters:

  1. Query parameters: These are automatically included in the params object

  2. JSON body: For POST requests, the JSON body is merged into the params object

  3. Environment variables: All environment variables are included in the params object

Example: Accessing Parameters

function main(params) {
    // Access query parameter: /api/v1/web/org_123/default/my-function?name=John
    const name = params.name;
    
    // Access environment variable named API_KEY
    const apiKey = params.API_KEY;
    
    // Access a value from the JSON body of a POST request
    const data = params.data;
    
    return {
        statusCode: 200,
        body: {
            message: `Hello, ${name}!`,
            received: params
        }
    };
}

Function Limits

Our platform enforces the following limits for edge functions:

Resource
Default
Min
Max

Memory

256 MB

128 MB

1024 MB

Timeout

30 seconds

1 second

300 seconds

Package Size

-

-

10 MB

Concurrent Executions

1

-

-

Log Size

-

-

10 MB

Deploying Functions

Using the UI

  1. Complete the function creation form

  2. Click "Deploy" to create and activate your function

Function URL

After deployment, your function will be accessible at:

https://edge.pandastack.app/api/v1/web/org_{ORG_ID}/default/{FUNCTION_NAME}

Testing Functions

Using the UI

  1. Navigate to your function's details page

  2. Go to the "Testing" tab

  3. Enter test parameters in JSON format

  4. Click "Test Function" to see the result

Using cURL

You can test your function using cURL:

curl -X POST "https://edge.pandastack.app/api/v1/web/org_{ORG_ID}/default/{FUNCTION_NAME}" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'

Monitoring & Logs

Viewing Logs

  1. Navigate to your function's details page

  2. Go to the "Logs" tab to see execution logs

  3. Use console.log() (Node.js) or print() (Python) to add custom log entries

Monitoring Metrics

The "Monitoring" tab provides metrics such as:

  • Invocation count

  • Error rate

  • Execution duration

  • Memory usage

Examples

Example 1: Simple API Response

function main(params) {
    return {
        statusCode: 200,
        body: {
            message: "Hello, world!",
            timestamp: new Date().toISOString()
        }
    };
}

Example 2: Using Environment Variables for Authentication

function main(params) {
    // Check for API key in parameters (from environment variables)
    const apiKey = params.API_KEY;
    const providedKey = params.key;
    
    if (!apiKey || providedKey !== apiKey) {
        return {
            statusCode: 401,
            body: {
                error: "Unauthorized"
            }
        };
    }
    
    return {
        statusCode: 200,
        body: {
            message: "Authentication successful",
            data: {
                // Your secure data here
            }
        }
    };
}

Example 3: Processing Form Data (Node.js)

function main(params) {
    // Access form fields from params
    const { name, email, message } = params;
    
    // Validate inputs
    if (!name || !email || !message) {
        return {
            statusCode: 400,
            body: {
                error: "Missing required fields"
            }
        };
    }
    
    // Process the form data
    console.log(`Form submission from ${name} (${email}): ${message}`);
    
    // In a real scenario, you might send an email, store in a database, etc.
    
    return {
        statusCode: 200,
        body: {
            success: true,
            message: "Form submitted successfully"
        }
    };
}

Example 4: Handling Different HTTP Methods

function main(params) {
    // Get the HTTP method from params.__ow_method
    const method = params.__ow_method || 'get';
    
    switch (method.toLowerCase()) {
        case 'get':
            return handleGet(params);
        case 'post':
            return handlePost(params);
        case 'put':
            return handlePut(params);
        case 'delete':
            return handleDelete(params);
        default:
            return {
                statusCode: 405,
                body: {
                    error: "Method not allowed"
                }
            };
    }
}

function handleGet(params) {
    return {
        statusCode: 200,
        body: {
            message: "GET request handled",
            query: params
        }
    };
}

function handlePost(params) {
    return {
        statusCode: 200,
        body: {
            message: "POST request handled",
            data: params
        }
    };
}

function handlePut(params) {
    return {
        statusCode: 200,
        body: {
            message: "PUT request handled",
            data: params
        }
    };
}

function handleDelete(params) {
    return {
        statusCode: 200,
        body: {
            message: "DELETE request handled",
            id: params.id
        }
    };
}

Example 5: External API Integration (Python)

import json
import urllib.request
from datetime import datetime

def main(params):
    # Get API key from environment variables
    api_key = params.get('WEATHER_API_KEY', '')
    
    # Get location from request parameters
    city = params.get('city', 'London')
    
    # Construct API URL
    url = f"https://api.example.com/weather?city={city}&apikey={api_key}"
    
    try:
        # Make API request
        with urllib.request.urlopen(url) as response:
            data = json.loads(response.read().decode())
            
        # Process and return the weather data
        return {
            'statusCode': 200,
            'body': {
                'city': city,
                'temperature': data.get('temp'),
                'conditions': data.get('conditions'),
                'timestamp': datetime.now().isoformat()
            }
        }
    except Exception as e:
        print(f"Error: {str(e)}")
        return {
            'statusCode': 500,
            'body': {
                'error': 'Failed to fetch weather data',
                'message': str(e)
            }
        }

Example 6: Accessing OpenWhisk System Information

Your function has access to special parameters that provide information about the OpenWhisk environment:

function main(params) {
    // OpenWhisk system parameters
    const systemInfo = {
        activationId: params.__OW_ACTIVATION_ID,
        actionName: params.__OW_ACTION_NAME,
        namespace: params.__OW_NAMESPACE,
        apiHost: params.__OW_API_HOST,
        deadline: params.__OW_DEADLINE
    };
    
    return {
        statusCode: 200,
        body: {
            message: "OpenWhisk System Information",
            system: systemInfo
        }
    };
}

Troubleshooting

Common Issues

  1. Function Returns 502 Bad Gateway

    • Ensure your function returns a proper response object

    • Check your function logs for errors

    • Verify your function isn't timing out

  2. Environment Variables Not Working

    • Make sure they are correctly set in the UI

    • Verify you're accessing them via the params object

  3. Function Takes Too Long to Execute

    • Check if your function is making slow external API calls

    • Consider increasing the memory allocation

    • Optimize your code for better performance

Getting Help

If you continue to experience issues, please contact our support team with:

  • Your function name

  • Any error messages

  • Steps to reproduce the issue

  • Relevant logs


For more information or technical support, please contact our support team at support@pandastack.io

PreviousJenkinsNextDeploy a nodejs function

Last updated 2 months ago