> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ollie.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# How Functions Run

> Understand how Ollie Hub intercepts requests, routes traffic, and executes your custom code seamlessly.

Ollie Hub acts as an intelligent proxy that intercepts requests to your target URLs and executes your custom functions. Learn how this interception works, how functions are routed and executed, and how to optimize performance.

## Core Concept: Request Interception

```mermaid theme={"system"}
graph TD
    A["User Request"] --> B["Ollie Hub Proxy"]
    B --> C{"Function Type Detection"}
    
    C --> D["Request Function"]
    D --> E["Execute Request Code"]
    E --> F["Return Response"]
    
    C --> G["Response Function"]
    G --> H["Execute Response Code"]
    H --> I["Return Enhanced Response"]
    
    J["Cron/Schedule Trigger"] --> N["Ollie Hub Proxy"]
    N --> K["Task Function"]
    K --> L["Execute Background Code"]
    L --> M["Complete in Background"]
    
    style A fill:transparent,stroke:#556AEB,stroke-width:2px
    style B fill:transparent,stroke:#556AEB,stroke-width:2px
    style C fill:transparent,stroke:#666,stroke-width:1px
    style D fill:transparent,stroke:#28a745,stroke-width:2px
    style E fill:transparent,stroke:#666,stroke-width:1px
    style F fill:transparent,stroke:#556AEB,stroke-width:2px
    style G fill:transparent,stroke:#17a2b8,stroke-width:2px
    style H fill:transparent,stroke:#666,stroke-width:1px
    style I fill:transparent,stroke:#556AEB,stroke-width:2px
    style J fill:transparent,stroke:#ffc107,stroke-width:2px
    style K fill:transparent,stroke:#ffc107,stroke-width:2px
    style L fill:transparent,stroke:#666,stroke-width:1px
    style M fill:transparent,stroke:#666,stroke-width:1px
    style N fill:transparent,stroke:#556AEB,stroke-width:2px
```

## How Ollie Hub Works

<Steps>
  <Step title="Request Interception">
    Ollie Hub receives requests intended for your target URL and captures all request details

    ```
    Original: https://api.yourapp.com/users/123
    Hub URL:  https://hub.ollie.app/https://api.yourapp.com/users/123
    ```
  </Step>

  <Step title="Function Routing">
    Based on URL patterns and HTTP methods, Hub determines which function should handle the request

    ```typescript theme={"system"}
    // Exact match: /api/users/profile
    // Pattern match: /api/users/*
    // Catch-all: /*
    ```
  </Step>

  <Step title="Code Execution">
    Your custom function executes with full access to request data and can modify the response

    ```typescript theme={"system"}
    export const handler = async (event) => {
      // Your custom logic here
      return { statusCode: 200, body: 'Custom response' };
    };
    ```
  </Step>

  <Step title="Response Enhancement">
    Optional Response Functions can further modify the output before returning to the user
  </Step>
</Steps>

## URL Patterns and Routing

<Tabs>
  <Tab title="Proxy URLs">
    Ollie Hub uses a simple proxy pattern to intercept requests:

    <CodeGroup>
      ```bash Basic Example theme={"system"}
      # Your original endpoint
      https://api.myapp.com/users

      # Through Ollie Hub
      https://hub.ollie.app/https://api.myapp.com/users
      ```

      ```bash With Parameters theme={"system"}
      # Complex URL with query parameters
      https://api.myapp.com/search?q=products&sort=price

      # Through Hub (automatically handled)
      https://hub.ollie.app/https://api.myapp.com/search?q=products&sort=price
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Routing Priority">
    When multiple functions could handle the same request:

    <CardGroup cols={2}>
      <Card title="1. Exact Match" icon="target">
        `/api/users/profile` matches exactly
      </Card>

      <Card title="2. Parameter Match" icon="brackets-curly">
        `/api/users/{id}` with dynamic segments
      </Card>

      <Card title="3. Wildcard Match" icon="asterisk">
        `/api/users/*` catches all user routes
      </Card>

      <Card title="4. Catch-All" icon="globe">
        `/*` handles everything else
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="HTTP Methods">
    Functions can be configured to handle specific HTTP methods:

    ```typescript theme={"system"}
    // Handle specific methods
    export const handler = async (event) => {
      switch (event.httpMethod) {
        case 'GET':
          return await handleGet(event);
        case 'POST':
          return await handlePost(event);
        case 'PUT':
          return await handleUpdate(event);
        case 'DELETE':
          return await handleDelete(event);
        default:
          return { statusCode: 405, body: 'Method not allowed' };
      }
    };
    ```
  </Tab>
</Tabs>

## Error Handling & Policies

Understanding how Ollie Hub handles function failures is crucial for building reliable applications. Each function can be configured with an error policy that determines what happens when execution fails.

<CardGroup cols={2}>
  <Card title="Skip Policy" icon="forward">
    **Behavior**: Continue execution even if function fails
    **Use Case**: Non-critical functions (analytics, logging, enhancements)
    **Impact**: Request processing continues normally
    **Status**: Function marked as `skipped`

    ```mermaid theme={"system"}
    graph TD
      A[Function Execution] --> B{Success?}
      B -->|Yes| C[Status: executed]
      B -->|No| D[Status: skipped]
      C --> E[Continue to Next Function]
      D --> E
      E --> F[Complete Request]
      
      style D fill:transparent,stroke:#ffc107,stroke-width:2px
      style C fill:transparent,stroke:#28a745,stroke-width:2px
    ```
  </Card>

  <Card title="Throw Policy" icon="exclamation-triangle">
    **Behavior**: Stop execution and return error if function fails
    **Use Case**: Critical functions (authentication, validation, security)\
    **Impact**: Request fails with error response
    **Status**: Function marked as `failed`

    ```mermaid theme={"system"}
    graph TD
      A[Function Execution] --> B{Success?}
      B -->|Yes| C[Status: executed]
      B -->|No| D[Status: failed]
      C --> E[Continue to Next Function]
      D --> F[Return Error Response]
      
      style D fill:transparent,stroke:#dc3545,stroke-width:2px
      style C fill:transparent,stroke:#28a745,stroke-width:2px
      style F fill:transparent,stroke:#dc3545,stroke-width:2px
    ```
  </Card>
</CardGroup>

<Info>
  **Error Policy Best Practices**:

  * Use `throw` for authentication, validation, and security functions
  * Use `skip` for analytics, logging, and enhancement functions
  * Consider the impact on user experience when choosing policies
</Info>

<Tabs>
  <Tab title="Mixed Policy Chain">
    When functions have different error policies, the Hub handles them intelligently:

    <CodeGroup>
      ```typescript Function Configuration theme={"system"}
      const functions = [
        { 
          name: "Authentication",
          on_error: "throw", 
          priority: 0 
        },      // Must succeed
        { 
          name: "Analytics", 
          on_error: "skip", 
          priority: 1 
        },      // Optional
        { 
          name: "Transform", 
          on_error: "throw", 
          priority: 2 
        }       // Must succeed
      ];
      ```

      ```bash Execution Flow theme={"system"}
      ✅ Auth function succeeds → Continue
      ❌ Analytics function fails → Log warning, continue  
      ✅ Transform function succeeds → Complete request

      # If Auth or Transform failed:
      ❌ Request stops → Error response returned
      ```
    </CodeGroup>

    **Key Points**:

    * **Request Functions**: Execute sequentially, failures can stop the chain
    * **Response Functions**: Execute in parallel, failures are handled independently
    * **Mixed Policies**: Each function's policy is evaluated individually
  </Tab>

  <Tab title="Error Context & Logging">
    All errors are logged with rich context for debugging:

    ```json theme={"system"}
    {
      "level": "warn",
      "msg": "Error executing function",
      "id": "func-123",
      "onError": "skip",
      "error": {
        "message": "API timeout after 30 seconds",
        "type": "TimeoutError"
      },
      "request": {
        "url": "https://api.example.com/users",
        "method": "GET"
      },
      "timestamp": "2024-01-15T10:30:00Z"
    }
    ```

    **Error Information Includes**:

    * Function ID and error policy
    * Detailed error message and type
    * Request context (URL, method, headers)
    * Execution timestamp for debugging
  </Tab>

  <Tab title="Function Status Tracking">
    The Hub tracks execution status for each function in response headers:

    <CodeGroup>
      ```bash Example Headers theme={"system"}
      x-ollie-functions: func-1:executed,func-2:skipped,func-3:executed
      ```

      ```typescript Status Types theme={"system"}
      enum FunctionStatus {
        Executed = "executed",  // Function ran successfully
        Skipped = "skipped",    // Function failed with skip policy
        Failed = "failed"       // Function failed with throw policy
      }
      ```
    </CodeGroup>

    **Use Cases**:

    * **Debugging**: See which functions ran and their outcomes
    * **Monitoring**: Track function reliability and performance
    * **Analytics**: Understand function usage patterns
    * **Troubleshooting**: Quickly identify which functions are causing issues
  </Tab>
</Tabs>

<Warning>
  **Important**: Functions with `throw` policy will prevent subsequent functions from executing. Always consider the order and error policies when designing your function chain.
</Warning>

## Next Steps

<CardGroup cols={3}>
  <Card title="Request Functions" icon="globe" href="/ollie-hub/core-concepts/request-functions">
    Learn to handle HTTP requests and build APIs
  </Card>

  <Card title="Response Functions" icon="arrow-right-arrow-left" href="/ollie-hub/core-concepts/response-functions">
    Enhance responses with custom logic
  </Card>

  <Card title="Task Functions" icon="clock" href="/ollie-hub/core-concepts/task-functions">
    Automate workflows with scheduled tasks
  </Card>
</CardGroup>

<CardGroup cols={2}>
  <Card title="Local Development" icon="code" href="/ollie-hub/development/local-development">
    Test and debug functions locally
  </Card>

  <Card title="Best Practices" icon="star" href="/ollie-hub/development/best-practices">
    Follow proven patterns and optimizations
  </Card>
</CardGroup>

<Info>
  **Key Insight:** Ollie Hub acts as an intelligent proxy that intercepts your requests and executes custom code seamlessly. Understanding this flow helps you build more efficient and reliable functions.
</Info>
