跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

获取当前 Agent

最后更新 查看 MarkdownAgent 设置

getCurrentAgent() 会返回正在处理当前调用的 Durable Object,以及相应的请求或 WebSocket 连接。可在无法访问 this 的共享代码中使用它,例如工具、日志辅助函数或库函数。

import { DurableObject } from "cloudflare:workers";
import { getCurrentAgent, Lifecycle } from "agents/lifecycle";

function requestOrigin() {
	const { request } = getCurrentAgent();
	return request ? new URL(request.url).origin : undefined;
}

export class MyAgent extends DurableObject {
	lifecycle = Lifecycle.install(this);

	onRequest() {
		return Response.json({ origin: requestOrigin() });
	}

	greeting() {
		return "hello";
	}
}

export function greet() {
	const { agent } = getCurrentAgent();
	return agent?.greeting();
}
import { DurableObject } from "cloudflare:workers";
import { getCurrentAgent, Lifecycle } from "agents/lifecycle";

function requestOrigin(): string | undefined {
    const { request } = getCurrentAgent();
    return request ? new URL(request.url).origin : undefined;
}

export class MyAgent extends DurableObject<Env> {
    readonly lifecycle = Lifecycle.install(this);

    onRequest(): Response {
        return Response.json({ origin: requestOrigin() });
    }

    greeting(): string {
        return "hello";
    }
}

export function greet(): string | undefined {
    const { agent } = getCurrentAgent<MyAgent>();
    return agent?.greeting();
}

当共享代码需要调用类方法时,请像 greet() 一样将类作为类型参数传入。若不指定类型参数,agent 的类型为 LifecycleObject。在类自身内部,请优先使用 this。

返回值

getCurrentAgent<Host>() 会返回 CurrentAgentContext<Host>:

属性 类型 描述
agent Host | undefined 处理当前调用的 Durable Object
connection Connection | undefined 在 WebSockets 能力处理程序中使用的 WebSocket 连接
request Request | undefined 在 onRequest() 或连接处理程序中使用的 HTTP 请求
email unknown 在 Agent 类电子邮件处理程序中使用的电子邮件

在 Lifecycle 启动的调用之外,所有值均为 undefined。使用前请检查 agent。

上下文可用范围

Lifecycle 调用宿主钩子和用户回调时会设置上下文:

调用 agent connection request
onStart(), onAlarm(), onJob(), onAlarmMemoryLimit() 是 否 否
onRequest() 是 否 是
WebSockets 的 onConnect 处理程序 是 是 是
WebSockets 的 onMessage、onClose 和 onError 处理程序 是 是 否
Scheduler 回调 是 否 否
能力钩子,例如某项能力上的 onJob() 否 否 否
原生 RPC 方法 否 否 否

Scheduler 回调由闹钟在新的调用中运行,因此无法访问创建该计划的请求或连接:

import { DurableObject } from "cloudflare:workers";
import { getCurrentAgent, Lifecycle } from "agents/lifecycle";
import { Scheduler } from "agents/schedules";

function log(message) {
	const { agent } = getCurrentAgent();
	console.log(`[${agent?.lifecycle.name}] ${message}`);
}

export class Reminders extends DurableObject {
	scheduler = new Scheduler({
		callbacks: {
			remind: (payload) => log(payload.text),
		},
	});
	lifecycle = Lifecycle.install(this).use(this.scheduler);

	async onRequest() {
		await this.scheduler.set(60, "remind", { text: "Stand up" });
		return new Response("Scheduled", { status: 202 });
	}
}
import { DurableObject } from "cloudflare:workers";
import { getCurrentAgent, Lifecycle } from "agents/lifecycle";
import { Scheduler } from "agents/schedules";

function log(message: string): void {
    const { agent } = getCurrentAgent<Reminders>();
    console.log(`[${agent?.lifecycle.name}] ${message}`);
}

export class Reminders extends DurableObject<Env> {
    readonly scheduler = new Scheduler({
        callbacks: {
            remind: (payload: { text: string }) => log(payload.text),
        },
    });
    readonly lifecycle = Lifecycle.install(this).use(this.scheduler);

    async onRequest(): Promise<Response> {
        await this.scheduler.set(60, "remind", { text: "Stand up" });
        return new Response("Scheduled", { status: 202 });
    }
}

能力钩子

能力钩子运行时会清除上下文,不会继承调用方的上下文。若能力要调用用户代码,请使用 this.lifecycle.runInHostContext() 包装调用,以便回调中的 getCurrentAgent() 返回宿主。拥有某个连接或请求的能力可以将其作为第二个参数传入。更多信息,请参阅构建能力。

原生 RPC 和其他入口

上下文仅沿着 Lifecycle 已启动调用的调用树传递。Lifecycle 不会包装原生 Durable Object RPC 方法,因此在这些方法及其调用的所有代码中,getCurrentAgent() 返回的值都是 undefined。通过服务绑定、Worker Loader 子隔离区或持有该对象引用的其他入口访问的代码也一样。

在 Agent 类上使用

agents 中的 getCurrentAgent() 是同一个函数,但类型针对 Agent 类。与普通 Lifecycle 对象相比,Agent 类会设置更多上下文:

  • 自定义方法。 Agent 类会在初始化期间包装类自己的方法,因此这些方法及其调用的所有函数中都可以使用 getCurrentAgent(),包括通过 RPC 运行时。若要从通过 RPC 到达的回调中恢复上下文,请调用 Agent 的公共方法。通过此方式恢复的上下文不会设置 connection、request 和 email。
  • 电子邮件。 在 onEmail() 中,email 包含收到的电子邮件。
  • 连接。 在 onConnect() 和 onMessage() 中,connection 包含发起调用的 WebSocket 连接。

更多信息,请参阅 Agent 类。

这篇文档对您有帮助吗?