# Functions
Source: https://sovaria.in/docs/functions-overview

Write functions in Python, JavaScript, TypeScript (Bun) or Go, deploy them, and call them over HTTP with secrets, logs and versions.

Functions run your server-side code — webhooks, payments, calls to AI APIs, anything that needs a secret. Each function gets an HTTPS endpoint, versioned deploys, logs and its own secrets. Functions run **Python 3** or **Node.js** in an isolated sandbox.

(Diagram: Calling a function)

## Write a function

Define `handler(event, context)`. `event` is the JSON body of the request; `context` tells you who called and which version is running. Return any JSON value. The entry file picks the language: `main.py` for Python, `index.mjs` / `index.js` for Node.js (exporting `handler`, or a default function), `index.ts` for TypeScript on Bun, `main.go` for Go.

main.py:
```python
import os

def handler(event, context):
    caller = context["caller"]          # {"user_id", "role": "authenticated" | "anon" | "service_role", "app_roles"}
    if caller["role"] == "anon":
        return {"error": "sign in first"}
    name = (event or {}).get("name", "world")
    return {"message": f"Hello, {name}!", "version": context["version"]}
```

index.mjs:
```js
export async function handler(event, context) {
  const caller = context.caller            // { user_id, role, app_roles }
  if (caller.role === 'anon') return { error: 'sign in first' }
  const name = event?.name ?? 'world'
  return { message: `Hello, ${name}!`, version: context.version }
}
```

index.ts (Bun):
```ts
type Event = { name?: string }

export async function handler(event: Event, context: { caller: { role: string }; version: number }) {
  if (context.caller.role === 'anon') return { error: 'sign in first' }
  return { message: `Hello, ${event?.name ?? 'world'}!`, version: context.version }
}
```

main.go:
```bash
package main

import "fmt"

// Sovaria adds func main and type Context (a map) when it builds the function.
func Handler(event any, ctx Context) (any, error) {
    caller, _ := ctx["caller"].(map[string]any)
    if caller["role"] == "anon" {
        return map[string]any{"error": "sign in first"}, nil
    }
    m, _ := event.(map[string]any)
    return map[string]any{"message": fmt.Sprintf("Hello, %v!", m["name"]), "version": ctx["version"]}, nil
}
```

| `context` key | Value |
|---|---|
| `caller` | Who made the request: user id, role and app roles. |
| `project_id` | The project. |
| `function_name`, `version`, `deploy_id` | Which deploy is running. |
| `invocation_id` | Unique id for this call — also shown in logs. |

## Languages

| Language | Entry file | Handler | Notes |
|---|---|---|---|
| Python 3.12.15 | `main.py` | `def handler(event, context)` (sync or async) | httpx, requests, pydantic, PyYAML, boto3, SQLAlchemy, asyncpg, psycopg (2 and 3) and google-cloud-storage without bundling; anything else ships in the bundle. |
| JavaScript (Node 24 LTS) | `index.mjs` / `index.js` | `export async function handler(event, context)` | zod, date-fns, lodash-es, nanoid, jose, uuid without bundling. |
| TypeScript (Bun 1.4) | `index.ts` | the same as JavaScript, typed | No build step: Bun runs TypeScript as is. The JavaScript libraries import the same way; `Bun.*` APIs work. |
| Go 1.27 (language version 1.24) | `main.go` (any `.go` files in package `main`) | `func Handler(event any, ctx Context) (any, error)` | Compiled once when you deploy, by a separate build sandbox. Return an error to fail the call. Standard library; modules from a deployed `vendor/` folder. |

- **Go**: leave out `func main` and `type Context` — Sovaria adds a `main` that reads the request, calls `Handler` (or the handler you name, capitalised) and writes the result. `Context` is a `map[string]any` with the keys below.
- **Go modules** aren't downloaded at deploy. Run `go mod vendor` and deploy the `vendor/` folder with the function (shipping dependencies needs a paid plan), or stay on the standard library.
- **Go builds** count toward the plan's Go builds a month. A build failure fails the deploy and shows the compiler output; the version serving traffic stays. Promoting from an environment reuses the binary.
- Streaming responses and durable workflow steps (`context.step`) are available in Python, JavaScript and TypeScript.
- Every language runs in the same sandbox with the same limits: memory, CPU time, timeout, and no network unless you allow hosts.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Go function builds per month | 50 | 1,000 | 5,000 | 20,000 | 100,000 |
| Bundling your own function dependencies | — | ✓ | ✓ | ✓ | ✓ |

## Deploy

CLI:
```bash
sov fn deploy ./hello --name hello --note "first version"
sov fn versions hello
sov fn rollback hello        # back to the previous version
```

Console:
```bash
# Functions → New function → pick a template or start empty
# Edit main.py, then "Save & deploy"
```

Every deploy creates a new version. Owners and admins are notified when a deploy succeeds or fails; a failed deploy never replaces the version that is serving traffic.

## Call it

JavaScript:
```js
const result = await sovaria.functions.call('hello', { name: 'Ada' })
```

cURL:
```bash
curl -s -X POST https://<project-ref>.sovarias.in/functions/v1/hello \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' -d '{"name":"Ada"}'
```

CLI:
```bash
sov fn invoke hello --data '{"name":"Ada"}'
sov fn invoke hello --async --wait     # queue it and wait for the result
```

### Who can call a function

| Setting | Who can call it | Use for |
|---|---|---|
| Default | Any request with one of the project's keys or a user session — **including visitors using the anon key**. | Functions your app calls. To require sign-in, save a policy with `invoke_permission: authenticated` (below) or check `context["caller"]["role"]` in code, as in the example above. |
| Public | Anyone, even without a key. | Webhooks from Stripe, GitHub and similar. A function gets the JSON body but not the request headers, so it can't check a signature header yet: confirm the event with the sender's API instead (fetch it back by id), as in [Tutorial: a store with Stripe or Razorpay](https://sovaria.in/docs/tutorial-store-payments#webhook). |

Change it under **Edge Functions → your function → Run → Who can call it**. Only project owners and admins can make a function public.

### Per-function limits

Save an invoke policy to tighten one function. Nothing applies until you save one; afterwards every call is checked.

| Setting | Effect |
|---|---|
| `invoke_permission` | `public` — anyone who can reach it; `authenticated` — signed-in users, console members and the service key (anon-key visitors get `401`); `service_role` — only the service key and console members (`403` otherwise). |
| `max_payload_bytes` | Larger request bodies are refused with `413` (1 KB – 10 MB). |
| `allowed_origins` | `*` or a comma-separated list such as `https://shop.example.com`. Browser calls from other sites get `403`; server-to-server calls (no `Origin`) are not affected. |
| `rate_limit_per_minute` | Calls per minute across all callers; over it returns `429` with `Retry-After`. |
| `timeout` | Lowers the maximum run time for this function (seconds). It never goes above your plan's limit. |

CLI:
```bash
sov fn policy-set send-receipt '{"invoke_permission":"authenticated","rate_limit_per_minute":30,"max_payload_bytes":65536,"allowed_origins":"https://shop.example.com","timeout":10}'
sov fn policy-get send-receipt      # "saved": true once a policy applies
```

## Secrets

Store API keys as secrets; they are encrypted, never shown again after saving, and available to your code as environment variables.

CLI:
```bash
sov secrets set hello --name OPENAI_API_KEY --value sk-...
sov secrets list hello            # values are masked
sov secrets import hello .env
```

Python:
```python
import os
api_key = os.environ["OPENAI_API_KEY"]
```

## Network access

Functions can only reach the hosts you allow in the function's settings (for example `api.openai.com`). Everything else is blocked, which stops a compromised dependency from sending your data elsewhere.

## Logs and limits

- Logs: **Functions → your function → Logs**, or `sov fn logs hello`. Each line carries the invocation id.
- Timeout, memory and invocations per month depend on your plan.
- Use `--async` (or `functions.invokeAsync`) for long work; poll the job or let it notify your app through realtime.
- Run functions on database, auth, storage and realtime events with [Event triggers](https://sovaria.in/docs/function-triggers); develop locally, tail logs live and stream responses with [Local development, logs and streaming](https://sovaria.in/docs/functions-local-development).
