函数
这是什么 / 何时用
服务端无服务器函数响应 HTTP / SDK 调用、平台事件和定时任务,运行在隔离沙箱中(托管环境经 ACS Agent Sandbox,本地 Docker 基于 OpenRuntimes)。适用于后端逻辑代理、事件驱动处理、定时任务和轻量 API;涉及复杂授权时,先阅读权限说明。
前置
Server API Key:按实际操作授予 scope:管理需
functions.write,触发执行需execution.write,读取记录需execution.read,查看函数需functions.read;无需为只读查询额外授予写权限。源码部署包为
.tar.gz(含入口文件与依赖清单,如package.json);Java 17 可另选预构建 JAR 模式,见下文。Node 侧InputFile必须从 SDK 的file子路径导入(主模块不导出)。
使用骨架
查能力:创建或修改前分别查询
functions.listRuntimes()和functions.listSpecifications():从运行时列表选择runtime,从已启用的规格中选择runtimeSpecification。SDK 枚举只是候选,实际可用值还受实例配置和套餐限制。创建函数:调用
functions.create,指定标识、名称、运行时与权限;配置项见下方参数表。以下为参数结构示意,?表示可选项,完整调用见「各语言调用示例」。functions.create({ functionId, name, runtime, execute?, events?, schedule?, timeout?, enabled?, logging?, entrypoint?, commands?, scopes?, runtimeSpecification?, runtimeReplicas?, runtimeKeepAliveMode?, ... })部署:上传源码归档并创建 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 响应。调用:
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 权限包含相应来源)。
函数内再调 Agentbase:动态 API Key(
req.headers['x-appwrite-key'],权限 = 函数scopes参数,管理员视角)或调用者 JWT(x-appwrite-user-jwt,受行级权限约束);Client的 endpoint 用运行时注入的APPWRITE_FUNCTION_API_ENDPOINT(不是自己拼外部域名,自托管沙箱内 DNS 解析不了)。事件与定时:
events数组订阅平台事件(如tablesdb.*.tables.*.rows.*.create、users.*.create);schedule填 Cron 表达式。变量:
createVariable/listVariables/updateVariable/deleteVariable(secret: true加密存储,运行时经process.env读取)。切换版本:
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 无该枚举 |
runtimeReplicas | 1 / 2 / 3 / 5 / 10,默认 1 | 可复用运行时副本期望值 |
runtimeKeepAliveMode | disabled / always / schedule | warm 策略;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 通常为空)。
错误与边界
触发执行报缺 scope:
createExecution要的是execution.write,不是functions.write。同步执行返回 408:结合错误类型、执行记录、日志和业务副作用排查,不能仅凭状态码断定是冷启动或负载均衡超时。结果未知时先确认业务状态,并按业务幂等策略决定是否重试;后续长任务可考虑异步执行和轮询。
自托管 DNS 失败(
curl error 6):函数内用了外部 URL 初始化 Client;改用APPWRITE_FUNCTION_API_ENDPOINT。2.6.0 安全默认值(升级注意):
Function / Site 受限身份运行:用户安装 / 构建命令不满足受限身份安全条件时直接失败,不回退为高权限执行。
Function API Key 不再接受 query string 传递:用受保护 header(
x-appwrite-key)或平台运行时注入路径,避免 URL、日志、代理泄露。
修改
scopes/execute不需要重新部署代码,下一次createExecution起生效。部署构建超时(
_APP_COMPUTE_BUILD_TIMEOUT,默认 900 秒)同时是构建期动态 API Key 的有效期。构建失败优先看 Console 构建日志里的
commands与entrypoint。
SDK 类别差异
Client SDK(Web):可按函数执行权限触发
createExecution并按 ID 查询执行;执行记录列表与路径查询的客户端限制见下文。执行记录读取限制(2.9.0):当
X-AppBase-SDK标记启用,且X-SDK-Name=web、X-SDK-Platform=client同时成立时,执行记录列表(/executions)和路径查询(/execution-paths*)被守卫拦截并返回 403general_resource_blocked。Console SDK、服务端及不带该标记的原生请求不因这一守卫被拦截,但仍须满足各自的认证与授权。Server SDK:全管理面(创建 / 部署 / 变量 / 触发 / 记录);Node
InputFile从file子路径导入。Console SDK:函数的站点级兄弟能力(Sites 部署、执行计划)同形管理,函数本体管理一般走 Server SDK。
差异入口:client-sdk/web.md、
server-sdk/nodejs.md。
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。只调用其中一项时按该操作授予相应权限。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
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 的权限,按需最小化
});import io.agentbase.services.Functions;
Functions functions = new Functions(client); // client 初始化见 server-sdk/java.md
functions.listRuntimes(); // 实例实际开放的运行时
functions.listSpecifications(); // 实例的构建/运行规格;按 enabled 选择规格,与运行时分别选择
// functions.create(functionId, name, runtime, execute, events, schedule, timeout, ...,
// entrypoint, commands, scopes, ...):位置参数、可空位传 null;全签名见 Functions.javafrom agentbase.services.functions import Functions # 模块路径同 services.<功能> 约定
functions = Functions(client)
functions.list_runtimes() # 实例实际开放的运行时
functions.list_specifications() # 实例的构建/运行规格;按 enabled 选择规格,与运行时分别选择
functions.create(
function_id='send-mailer', name='发送邮件', runtime='node-22',
execute=['users'], # 谁可以触发;默认不授予任何角色
entrypoint='src/main.ts', commands='npm install',
scopes=['users.read']) # 函数内动态 API Key 的权限,按需最小化import (
"agentbase-go-sdk/agentbase"
"agentbase-go-sdk/client"
)
func createFunction(cl client.Client) error {
functions := agentbase.NewFunctions(cl)
runtimes, err := functions.ListRuntimes()
if err != nil { return err }
specs, err := functions.ListSpecifications()
if err != nil { return err }
fn, err := functions.Create("send-mailer", "发送邮件", "node-22",
functions.WithCreateExecute([]string{"users"}),
functions.WithCreateEntrypoint("src/main.ts"),
functions.WithCreateCommands("npm install"),
functions.WithCreateScopes([]string{"users.read"}))
if err != nil { return err }
_, _, _ = runtimes, specs, fn
return nil
}curl -sS -X POST "$APPBASE_ENDPOINT/functions" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"functionId":"send-mailer","name":"发送邮件","runtime":"node-22","execute":["users"],"entrypoint":"src/main.ts","commands":"npm install","scopes":["users.read"]}'
# 返回 201;可提交 runtime 全量以 GET /functions/runtimes 为准部署代码包
createDeployment 上传 .tar.gz 代码包(multipart/form-data),构建异步进行(waiting → processing → building → ready),立即返回处于构建状态的部署记录。代码包上传仅 Node 与 REST 两面提供,Java / Python / Go 省略该页签。
- Node.js(Server)
- REST(curl)
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 响应curl -sS -X POST "$APPBASE_ENDPOINT/functions/send-mailer/deployments" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-F "code=@./code.tar.gz" \
-F "activate=true" \
-F "entrypoint=src/main.ts" \
-F "commands=npm install"
# 返回 202(构建中);GET /functions/{functionId}/deployments/{deploymentId} 轮询状态触发执行与轮询
同步(async: false)等待执行结果,时限受函数及环境配置影响;异步返回 execution ID,可用 getExecution 轮询;scheduledAt 支持未来定时(ISO 8601,分钟精度);也可经 HTTP 直访函数 URL 触发(需 execute 权限包含相应来源)。
同步和异步是两种调用方式;每次创建执行都会触发一次新执行。以下异步示例只触发一次并查询一次状态,查询成功不代表业务已完成。需要等待终态时,应按间隔设置等待期限并查询;期限到达仍未结束时先核对状态和副作用,不要盲目再次触发。
- Node.js(Server)
- Web(用户 Session)
- Java
- Python
- Go
- REST(curl)
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 });import { Functions } from 'agentbase-web-sdk'; // 前提:用户已登录
const functions = new Functions(client);
const execution = await functions.createExecution({
functionId: 'send-mailer',
body: JSON.stringify({ to: 'a@b.c' }),
async: false, // 需函数 execute 权限包含用户角色,否则 403;看不到日志
});import io.agentbase.models.Execution;
import io.agentbase.enums.ExecutionMethod;
Execution bg = functions.createExecution("send-mailer",
"{\"to\":\"a@b.c\"}", true, "/", ExecutionMethod.POST, null, null);
Execution latest = functions.getExecution(bg.getFunctionId(), bg.getId());
// 这里仅查询一次;latest 可能仍处于等待或处理中。execution = functions.create_execution(
function_id='send-mailer',
body='{"to":"a@b.c"}',
path='/', method='POST',
headers={'X-Custom-Header': 'value'},
xasync=True)
current = functions.get_execution(function_id='send-mailer', execution_id=execution.id)import (
functionsvc "agentbase-go-sdk/functions"
"agentbase-go-sdk/models"
)
func executeFunction(functions *functionsvc.Functions) (*models.Execution, error) {
execution, err := functions.CreateExecution("send-mailer",
functions.WithCreateExecutionBody(`{"to":"a@b.c"}`),
functions.WithCreateExecutionAsync(true),
functions.WithCreateExecutionPath("/"),
functions.WithCreateExecutionMethod("POST"))
if err != nil { return nil, err }
current, err := functions.GetExecution("send-mailer", execution.Id)
if err != nil { return nil, err }
return current, nil
}curl -sS -X POST "$APPBASE_ENDPOINT/functions/send-mailer/executions" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"body":"{\"to\":\"a@b.c\"}","async":false,"path":"/","method":"POST","headers":{"X-Custom-Header":"value"}}'
# 返回 201;async=true 后用 GET /functions/{functionId}/executions/{executionId} 轮询
# scheduledAt 支持未来定时(ISO 8601,分钟精度)执行路径查询(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 方法精确过滤)。
- Node.js(Server)
- REST(curl)
const paths = await functions.listExecutionPaths({ functionId: 'send-mailer' }); // { paths, total }
const onPath = await functions.listExecutionsByPath({
functionId: 'send-mailer',
xpath: '/webhook', // 完整路径精确匹配
}); // { executions, total }curl -sS "$APPBASE_ENDPOINT/functions/send-mailer/execution-paths" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
curl -sS "$APPBASE_ENDPOINT/functions/send-mailer/execution-paths/executions?path=/webhook" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
# path 为完整路径精确匹配(≤2048 字符)函数内再调 Agentbase
这是函数代码内部的能力面,不是管理 API 调用——本卡仅 Node(函数运行时)页签,其他语言运行时与 REST 无对应页签。Client 的 endpoint 用运行时注入的 APPWRITE_FUNCTION_API_ENDPOINT(自托管沙箱内解析不了外部域名);凭据二选一:动态 API Key(权限 = 函数 scopes 参数,管理员视角)或调用者 JWT(受行级权限约束)。
- Node.js(Server)
// 函数代码内部(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 机密变量可更新/删除但读不回明文;修改后需重新部署(或重新激活部署)才对后续执行生效。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
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 });io.agentbase.models.Variable variable = functions.createVariable("send-mailer", "DATABASE_URL",
"postgres://...", true); // secret=true 加密存储,不可回读
functions.listVariables("send-mailer");
functions.updateVariable("send-mailer", variable.getId(),
"DATABASE_URL", "postgres://new", null); // null 保留既有 secret 设置
functions.deleteVariable("send-mailer", variable.getId());variable = functions.create_variable(function_id='send-mailer', key='DATABASE_URL',
value='postgres://...', secret=True) # True = 加密存储,不可回读
functions.list_variables(function_id='send-mailer')
functions.update_variable(function_id='send-mailer', variable_id=variable.id,
key='DATABASE_URL', value='postgres://new') # key 必填
functions.delete_variable(function_id='send-mailer', variable_id=variable.id)import functionsvc "agentbase-go-sdk/functions"
func manageVariables(functions *functionsvc.Functions) error {
variable, err := functions.CreateVariable("send-mailer", "DATABASE_URL", "postgres://...",
functions.WithCreateVariableSecret(true))
if err != nil { return err }
_, err = functions.ListVariables("send-mailer")
if err != nil { return err }
_, err = functions.UpdateVariable("send-mailer", variable.Id, "DATABASE_URL",
functions.WithUpdateVariableValue("postgres://new"))
if err != nil { return err }
_, err = functions.DeleteVariable("send-mailer", variable.Id)
if err != nil { return err }
return nil
}curl -sS -X POST "$APPBASE_ENDPOINT/functions/send-mailer/variables" -H 'Content-Type: application/json' -H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY" -d '{"key":"DATABASE_URL","value":"postgres://...","secret":true}'
# 返回 201;列表 GET /functions/{functionId}/variables(机密变量值掩码)
# 更新 PUT、删除 DELETE 走 /functions/{functionId}/variables/{variableId}(更新时 key 必填)切换活跃部署
updateFunctionDeployment 把激活部署指针切到既有部署,此后该函数的访问与执行都使用新激活部署的代码。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
await functions.updateFunctionDeployment({
functionId: 'send-mailer',
deploymentId: '<deploymentId>',
});functions.updateFunctionDeployment("send-mailer", "<deploymentId>"); // 切换激活部署指针functions.update_function_deployment(function_id='send-mailer',
deployment_id='<deployment_id>') # 切换激活部署指针import functionsvc "agentbase-go-sdk/functions"
func activateDeployment(functions *functionsvc.Functions) error {
_, err := functions.UpdateFunctionDeployment("send-mailer", "<deploymentId>")
if err != nil { return err }
return nil
}curl -sS -X PATCH "$APPBASE_ENDPOINT/functions/send-mailer/deployment" -H 'Content-Type: application/json' -H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY" -d '{"deploymentId":"<deploymentId>"}'
# 路径是单数 deployment(切换激活),与列部署的 deployments 区分示例指引
各语言写法集中在语言树
examples/;v5 函数入口(context 对象)、注入 header / 环境变量清单、事件与 VCS 部署变量见skills/ob-agentbase/references/functions.md。
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 });