Docs
文档目录

函数

这是什么 / 何时用

服务端无服务器函数响应 HTTP / SDK 调用、平台事件和定时任务,运行在隔离沙箱中(托管环境经 ACS Agent Sandbox,本地 Docker 基于 OpenRuntimes)。适用于后端逻辑代理、事件驱动处理、定时任务和轻量 API;涉及复杂授权时,先阅读权限说明。

前置

使用骨架

  1. 查能力:创建或修改前分别查询 functions.listRuntimes() 和 functions.listSpecifications():从运行时列表选择 runtime,从已启用的规格中选择 runtimeSpecification。SDK 枚举只是候选,实际可用值还受实例配置和套餐限制。

  2. 创建函数:调用 functions.create,指定标识、名称、运行时与权限;配置项见下方参数表。以下为参数结构示意,? 表示可选项,完整调用见「各语言调用示例」。

    functions.create({
      functionId, name, runtime,
      execute?, events?, schedule?, timeout?, enabled?, logging?,
      entrypoint?, commands?, scopes?, runtimeSpecification?,
      runtimeReplicas?, runtimeKeepAliveMode?, ...
    })
  3. 部署:上传源码归档并创建 Deployment。

    functions.createDeployment({
      functionId,
      code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
      activate: true,
      entrypoint,
      commands,
    });

    状态流转为 waiting → processing → building → ready,failed / canceled 是异常路径。取消或长时间等待后,应重新读取 Deployment 并结合构建日志判断,不要只信一次 API 响应。

  4. 调用:

    • Client / Server SDK:functions.createExecution({ functionId, body, async, xpath, method, headers, scheduledAt })(xpath、method、headers、scheduledAt 均可选)。

    • 同步(async: false)等待执行结果,具体等待时限受函数和部署环境配置影响;异步返回 execution ID,可用 getExecution 轮询;scheduledAt 支持未来定时(ISO 8601,分钟精度)。

    • HTTP 直访函数 URL(需 execute 权限包含相应来源)。

  5. 函数内再调 Agentbase:动态 API Key(req.headers['x-appwrite-key'],权限 = 函数 scopes 参数,管理员视角)或调用者 JWT(x-appwrite-user-jwt,受行级权限约束);Client 的 endpoint 用运行时注入的 APPWRITE_FUNCTION_API_ENDPOINT(不是自己拼外部域名,自托管沙箱内 DNS 解析不了)。

  6. 事件与定时:events 数组订阅平台事件(如 tablesdb.*.tables.*.rows.*.create、users.*.create);schedule 填 Cron 表达式。

  7. 变量:createVariable / listVariables / updateVariable / deleteVariable(secret: true 加密存储,运行时经 process.env 读取)。

  8. 切换版本:updateFunctionDeployment({ functionId, deploymentId }) 切换活跃部署。

关键参数与返回

多语言 / 多规格 / 多副本

配置取值说明
runtime如 node-22、python-3.9、go-1.23(以 listRuntimes() 为准)对应 SDK Runtime 枚举
runtimeSpecification如 s-0.5vcpu-1gb、s-1vcpu-2gb、s-2vcpu-4gb、s-4vcpu-8gb、s-8vcpu-16gb直接传 slug 字符串,必须出现在 listSpecifications() 已启用列表;Node SDK 无该枚举
runtimeReplicas1 / 2 / 3 / 5 / 10,默认 1可复用运行时副本期望值
runtimeKeepAliveModedisabled / always / schedulewarm 策略;schedule 需 runtimeKeepAliveStart/End(HH:mm)+ IANA runtimeKeepAliveTimezone

warm 配置是 Function 级期望,不等于环境公共 warm pool 库存;公共池核查(warmPoolReplicas、库存 ready/available、createOnNoStock)属运维侧,SDK 不提供查询。

两套独立权限

配置控制什么典型值
execute谁可以触发(Client SDK / HTTP)['users']、['any']、['team:xxx']
scopes函数运行时动态 API Key 能访问的资源按函数内实际调用最小化,如 databases.read/write、tables.read/write、rows.read/write、users.read

与「部署脚本用的 API Key scopes」是两回事,不要互相顶替。

Execution 返回

$id、functionId、deploymentId、trigger(http/schedule/event)、status(waiting/processing/completed/failed/scheduled)、responseStatusCode、responseBody、duration、logs/errors(需 API Key 才可见,Client SDK 通常为空)。

错误与边界

SDK 类别差异

Java 17 预构建 JAR(Node.js Server)

管理脚本使用精确版本 agentbase-node-sdk@2.12.0。目标 Function 必须已选择 java-17.0;JAR 的 manifest 声明 Main-Class 且包内含该类,应用监听端口 3000 并提供 /__opr/health。部署 Key 需要 functions.write,回查还需要 functions.read;真正触发执行另需 execution.write。

import { Client, Functions, ArtifactMode } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT) // 包含 /v1
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
const functions = new Functions(client);

const deployment = await functions.createDeployment({
    functionId: process.env.APPBASE_FUNCTION_ID,
    code: InputFile.fromPath('./app.jar', 'app.jar'),
    artifactMode: ArtifactMode.Javajar,
    activate: false,
});
console.log(deployment.$id, deployment.status);

ArtifactMode.Javajar 对应 java-jar。此模式不用填写源码 entrypoint 或构建 commands,JAR 真实入口来自 manifest;响应中的 Index.java 是兼容标识。默认 JAR 上限为 100,000,000 字节,同时受套餐部署上限约束。SDK 负责分片上传;不要将上传进度 100% 当作创建部署成功。

示例使用 activate: false,便于先检查产物。收到部署 ID 后,用 getDeployment({ functionId, deploymentId }) 有界轮询并检查日志;到达 ready 后再按业务发布安排调用 updateFunctionDeployment。用 get({ functionId }) 回查 Function 的 deploymentId,确认与目标部署一致,再执行一次业务请求并检查实际响应。failed / canceled 或等待超时应停止发布并排查;部署 ready 不等于已经激活,也不保证业务请求成功。

筛选执行记录(Node.js Server)

读取执行记录需要 execution.read。HTTP 参数名是 path,Node Server 2.10.0 的对象参数名为 xpath;pathMatch 默认精确匹配。下面组合路径正则与 GET 方法,限定一页最多 20 条:

import { Client, Functions, Method, PathMatch, Query } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT)
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const functions = new Functions(client);

const page = await functions.listExecutions({
    functionId: process.env.APPBASE_FUNCTION_ID,
    xpath: '^/articles/[0-9]+$',
    pathMatch: PathMatch.Regex,
    method: Method.GET,
    queries: [Query.limit(20)],
});
console.log(page.executions.map(({ $id, status }) => ({ $id, status })));

路径包含查询字符串;上面的表达式不会匹配 /articles/42?draft=1,需要包含查询串时可改为 ^/articles/[0-9]+([?].*)?$。正则不带 /…/ 分隔符。按需用 Query.cursorAfter 继续分页,改变筛选条件时清空原游标;不要把当前一页或 total: false 返回的零计数当作全部结果。

listExecutionPaths 返回匹配的完整路径,listExecutionsByPath 返回该条件下的执行记录,两者也支持这些过滤条件。等待或处理中的 execution 不能仅因经过 timeout 就在客户端改写为失败,也不能删除;实际终态以服务端记录为准。

各语言调用示例

以下按使用骨架逐项给出各语言调用示例;每个卡片可切换语言(全页同步)。

查能力与创建函数

Go 示例以函数形式返回错误;先按 Go SDK 初始化创建 cl,再用 agentbase.NewFunctions(cl) 初始化服务并传给后续示例。调用方应按业务处理错误。

以下 Node.js、Java、Python、Go 示例均查询规格;运行包含规格查询和创建的完整示例,API Key 需要 functions.read 和 functions.write。只调用其中一项时按该操作授予相应权限。

import { Client, Functions, Runtime, Scopes } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // 必须包含 /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // 查询规格与创建分别需要 functions.read 和 functions.write
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const functions = new Functions(client);

const runtimes = await functions.listRuntimes();          // 实例实际开放的运行时
const specs = await functions.listSpecifications();       // 实例实际开放的构建/运行规格
// 分别选择运行时和已启用的规格;SDK 枚举只是候选
const fn = await functions.create({
    functionId: 'send-mailer',
    name: '发送邮件',
    runtime: Runtime.Node22,            // 以 listRuntimes() 实际返回为准
    execute: ['users'],            // 谁可以触发;默认不授予任何角色
    entrypoint: 'src/main.ts',
    commands: 'npm install',
    scopes: [Scopes.UsersRead],        // 函数内动态 API Key 的权限,按需最小化
});

部署代码包

createDeployment 上传 .tar.gz 代码包(multipart/form-data),构建异步进行(waiting → processing → building → ready),立即返回处于构建状态的部署记录。代码包上传仅 Node 与 REST 两面提供,Java / Python / Go 省略该页签。

import { Functions } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const dep = await functions.createDeployment({
    functionId: 'send-mailer',
    code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
    activate: true,
    entrypoint: 'src/main.ts',
    commands: 'npm install',
});
// 取消或长时间等待后应重新读取部署记录并结合构建日志判断,不要只信一次 API 响应

触发执行与轮询

同步(async: false)等待执行结果,时限受函数及环境配置影响;异步返回 execution ID,可用 getExecution 轮询;scheduledAt 支持未来定时(ISO 8601,分钟精度);也可经 HTTP 直访函数 URL 触发(需 execute 权限包含相应来源)。

同步和异步是两种调用方式;每次创建执行都会触发一次新执行。以下异步示例只触发一次并查询一次状态,查询成功不代表业务已完成。需要等待终态时,应按间隔设置等待期限并查询;期限到达仍未结束时先核对状态和副作用,不要盲目再次触发。

import { ExecutionMethod } from 'agentbase-node-sdk';

const execution = await functions.createExecution({
    functionId: 'send-mailer',
    body: JSON.stringify({ to: 'a@b.c' }),
    async: true,
    xpath: '/',
    method: ExecutionMethod.POST,
    headers: { 'X-Custom-Header': 'value' },
});
const current = await functions.getExecution({ functionId: 'send-mailer', executionId: execution.$id });

执行路径查询(2.9.0)

按请求路径回查执行记录:listExecutionPaths 列出已产生执行记录的去重请求路径(字符串升序、分页);listExecutionsByPath 按请求路径分页查询该路径下的执行(HTTP 参数 path 必填,≤2048 字符;Node.js 对象参数为 xpath)。两者都要求 execution.read。2.10.0 起两个方法新增过滤:HTTP path(Node.js 为 xpath,listExecutionPaths 可选)、pathMatch(exact / regex,默认 exact)与 method(HTTP 方法精确过滤)。

const paths = await functions.listExecutionPaths({ functionId: 'send-mailer' });   // { paths, total }
const onPath = await functions.listExecutionsByPath({
    functionId: 'send-mailer',
    xpath: '/webhook',          // 完整路径精确匹配
});                            // { executions, total }

函数内再调 Agentbase

这是函数代码内部的能力面,不是管理 API 调用——本卡仅 Node(函数运行时)页签,其他语言运行时与 REST 无对应页签。Client 的 endpoint 用运行时注入的 APPWRITE_FUNCTION_API_ENDPOINT(自托管沙箱内解析不了外部域名);凭据二选一:动态 API Key(权限 = 函数 scopes 参数,管理员视角)或调用者 JWT(受行级权限约束)。

// 函数代码内部(Node 运行时)
import { Client } from 'agentbase-node-sdk';

export default async ({ req, res }) => {
    // 方式一:动态 API Key(权限 = 函数 scopes 参数)
    const admin = new Client()
        .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)   // 运行时注入,始终优先
        .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
        .setKey(req.headers['x-appwrite-key']!);
    {
      const prepareRequest = admin.prepareRequest.bind(admin);
      admin.prepareRequest = (...args) => {
        const request = prepareRequest(...args);
        request.options.redirect = 'error';
        return request;
      };
    }

    // 方式二:调用者 JWT(SDK 触发时存在,受行级权限约束)
    const jwt = req.headers['x-appwrite-user-jwt'];
    if (jwt) {
        const asUser = new Client()
            .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)
            .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
            .setJWT(jwt);
        {
          const prepareRequest = asUser.prepareRequest.bind(asUser);
          asUser.prepareRequest = (...args) => {
            const request = prepareRequest(...args);
            request.options.redirect = 'error';
            return request;
          };
        }
    }
    return res.json({ ok: true });
};

事件与定时

events 订阅平台事件(如 users.*.create、tablesdb.*.tables.*.rows.*.create),schedule 填 CRON 表达式;两者也可在创建函数时一并传入。

更新函数前,先读取当前配置,并按更新接口的参数要求提交需要保留的配置;部分未传字段会采用接口默认值,不能假定所有未传字段保持原值。更新时必须提供函数名称;将 schedule 更新为非空值前,须已有唯一的 compact 执行定时规则。若不存在,可考虑通过定时规则接口单独管理调度;该接口新建的独立规则不等同于 compact 规则。存在多条时应先核对规则再处理。

环境变量

构建与运行时以环境变量形式注入函数进程(函数内经 process.env 读取);secret: true 机密变量可更新/删除但读不回明文;修改后需重新部署(或重新激活部署)才对后续执行生效。

const variable = await functions.createVariable({
    functionId: 'send-mailer',
    key: 'DATABASE_URL',
    value: 'postgres://...',
    secret: true,            // true = 加密存储,不可回读
});
const vars = await functions.listVariables({ functionId: 'send-mailer' });
await functions.updateVariable({
    functionId: 'send-mailer',
    variableId: variable.$id,
    key: 'DATABASE_URL',
    value: 'postgres://new',
});
await functions.deleteVariable({ functionId: 'send-mailer', variableId: variable.$id });

切换活跃部署

updateFunctionDeployment 把激活部署指针切到既有部署,此后该函数的访问与执行都使用新激活部署的代码。

await functions.updateFunctionDeployment({
    functionId: 'send-mailer',
    deploymentId: '<deploymentId>',
});

示例指引

2.12.0 — 多定时任务

使用 SDK 2.12.0 的 Projects 管理函数任务,项目 Key 需要 schedules.read / schedules.write。每条任务使用同一函数的当前活动部署。旧 Functions.schedule 只投影 compact 任务,不能列出全部调度。规则类型创建后固定,interval / cron / quartz 可各有多条;active 默认为 false,参数 data 是 JSON 对象字符串,响应 data 已是对象。列表默认 25、最大 100,hasMore 时使用最后一条 ID 作游标。请求路径模式指定 data.inputType=requestpath 与 data.requestPath,通过 GET 当前函数路径调用;省略 inputType 使用 POST JSON 模式。

停用与删除不会撤销已准入执行;运行时保活是独立系统任务,不能经普通调度 CRUD 修改。先部署 ready 再启用任务,变更后检查执行记录,不能用下次时间当作执行成功。

import { Client, Projects, Query, ResourceType, ScheduleType } from 'agentbase-node-sdk';
const projectId = process.env.AGENTBASE_PROJECT_ID;
const client = new Client().setEndpoint(process.env.AGENTBASE_ENDPOINT)
  .setProject(projectId).setKey(process.env.AGENTBASE_API_KEY);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const projects = new Projects(client);
const task = await projects.createSchedule({ projectId,
  resourceType: ResourceType.Functions, resourceId: process.env.AGENTBASE_FUNCTION_ID,
  scheduleType: ScheduleType.Quartz,
  schedule: JSON.stringify({ expression: '0 0 9 * * ?', timezone: 'Asia/Shanghai' }),
  data: JSON.stringify({ body: JSON.stringify({ task: 'daily-report' }) }), active: false });
const saved = await projects.getSchedule({ projectId, scheduleId: task.$id });
const page = await projects.listSchedules({ projectId,
  queries: [Query.equal('resourceId', process.env.AGENTBASE_FUNCTION_ID), Query.limit(25)], total: false });
console.log(saved.active, page.hasMore);
await projects.updateSchedule({ projectId, scheduleId: task.$id, active: false });
await projects.deleteSchedule({ projectId, scheduleId: task.$id });