Skip to content

Commit b4d58dd

Browse files
joshthowardOxyjun
andauthored
Document prefered method getByName for creating Durable Object stubs (#24586)
* Document prefered method getByName for creating Durable Object stubs * Apply suggestions from code review * Fixing chapter * Removing redundant line * Fixing compilation error --------- Co-authored-by: Jun Lee <[email protected]>
1 parent 65476b0 commit b4d58dd

File tree

27 files changed

+868
-896
lines changed

27 files changed

+868
-896
lines changed

src/content/docs/browser-rendering/workers-bindings/browser-rendering-with-DO.mdx

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,7 @@ import puppeteer from "@cloudflare/puppeteer";
107107

108108
export default {
109109
async fetch(request, env) {
110-
let id = env.BROWSER.idFromName("browser");
111-
let obj = env.BROWSER.get(id);
110+
let obj = env.BROWSER.getByName("browser");
112111

113112
// Send a request to the Durable Object, then await its response.
114113
let resp = await obj.fetch(request.url);

src/content/docs/containers/examples/env-vars-and-secrets.mdx

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
---
2-
32
summary: Pass in environment variables and secrets to your container
43
pcx_content_type: example
54
title: Env Vars and Secrets
@@ -125,11 +124,8 @@ export class MyContainer extends Container {
125124
export default {
126125
async fetch(request, env) {
127126
if (new URL(request.url).pathname === "/launch-instances") {
128-
let idOne = env.MY_CONTAINER.idFromName("foo");
129-
let instanceOne = env.MY_CONTAINER.get(idOne);
130-
131-
let idTwo = env.MY_CONTAINER.idFromName("foo");
132-
let instanceTwo = env.MY_CONTAINER.get(idTwo);
127+
let instanceOne = env.MY_CONTAINER.getByName("foo");
128+
let instanceTwo = env.MY_CONTAINER.getByName("foo");
133129

134130
// Each instance gets a different set of environment variables
135131

src/content/docs/containers/get-started.mdx

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,6 @@ the `docker info` command will hang or return an error including the message "Ca
2727

2828
## Deploy your first Container
2929

30-
31-
3230
Run the following command to create and deploy a new Worker with a container, from the starter template:
3331

3432
```sh
@@ -102,7 +100,6 @@ on container status changes, and more.
102100
See the [documentation for Durable Object container methods](/durable-objects/api/container/) and the
103101
[`Container` class repository](https://github.com/cloudflare/containers) for more details.
104102

105-
106103
### Configuration
107104

108105
Your [Wrangler configuration file](/workers/wrangler/configuration/) defines the configuration for both your Worker and your container:
@@ -204,9 +201,8 @@ When a request enters Cloudflare, your Worker's [`fetch` handler](/workers/runti
204201

205202
```js
206203
if (pathname.startsWith("/container")) {
207-
const id = env.MY_CONTAINER.idFromName(pathname);
208-
const container = env.MY_CONTAINER.get(id);
209-
return await container.fetch(request);
204+
const container = env.MY_CONTAINER.getByName(pathname);
205+
return await container.fetch(request);
210206
}
211207
```
212208

src/content/docs/durable-objects/api/alarms.mdx

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ Alarms can be used to build distributed primitives, like queues or batching of w
3939

4040
### `setAlarm`
4141

42-
- <code>{" "}setAlarm(scheduledTimeMs <Type text="number" />)</code>
42+
- <code>
43+
{" "}
44+
setAlarm(scheduledTimeMs <Type text="number" />)
45+
</code>
4346
: <Type text="void" />
4447

4548
- Set the time for the alarm to run. Specify the time as the number of milliseconds elapsed since the UNIX epoch.
@@ -63,11 +66,16 @@ This is due to the fact that, if the Durable Object wakes up after being inactiv
6366

6467
### `alarm`
6568

66-
- <code>alarm(`alarmInfo`<Type text="Object"/>)</code>: <Type text='void' />
69+
- <code>
70+
alarm(`alarmInfo`
71+
<Type text="Object" />)
72+
</code>
73+
: <Type text="void" />
6774

6875
- Called by the system when a scheduled alarm time is reached.
6976

7077
- The optional parameter `alarmInfo` object has two properties:
78+
7179
- `retryCount` <Type text="number"/>: The number of times this alarm event has been retried.
7280
- `isRetry` <Type text="boolean"/>: A boolean value to indicate if the alarm has been retried. This value is `true` if this alarm event is a retry.
7381

@@ -89,8 +97,7 @@ import { DurableObject } from "cloudflare:workers";
8997

9098
export default {
9199
async fetch(request, env) {
92-
let id = env.ALARM_EXAMPLE.idFromName("foo");
93-
return await env.ALARM_EXAMPLE.get(id).fetch(request);
100+
return await env.ALARM_EXAMPLE.getByName("foo").fetch(request);
94101
},
95102
};
96103

@@ -120,11 +127,13 @@ The following example shows how to use the `alarmInfo` property to identify if t
120127

121128
```js
122129
class MyDurableObject extends DurableObject {
123-
async alarm(alarmInfo) {
124-
if (alarmInfo?.retryCount != 0) {
125-
console.log("This alarm event has been attempted ${alarmInfo?.retryCount} times before.");
126-
}
127-
}
130+
async alarm(alarmInfo) {
131+
if (alarmInfo?.retryCount != 0) {
132+
console.log(
133+
"This alarm event has been attempted ${alarmInfo?.retryCount} times before.",
134+
);
135+
}
136+
}
128137
}
129138
```
130139

src/content/docs/durable-objects/api/namespace.mdx

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,8 @@ export class MyDurableObject extends DurableObject {
2828
// Worker
2929
export default {
3030
async fetch(request, env) {
31-
// Every unique ID refers to an individual instance of the Durable Object class
32-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
33-
3431
// A stub is a client Object used to invoke methods defined by the Durable Object
35-
const stub = env.MY_DURABLE_OBJECT.get(id);
32+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
3633
...
3734
}
3835
}
@@ -55,11 +52,8 @@ export class MyDurableObject extends DurableObject {
5552
// Worker
5653
export default {
5754
async fetch(request, env) {
58-
// Every unique ID refers to an individual instance of the Durable Object class
59-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
60-
6155
// A stub is a client Object used to invoke methods defined by the Durable Object
62-
const stub = env.MY_DURABLE_OBJECT.get(id);
56+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
6357
...
6458
}
6559
} satisfies ExportedHandler<Env>;
@@ -145,13 +139,32 @@ const stub = env.MY_DURABLE_OBJECT.get(id);
145139

146140
- A [`DurableObjectStub`](/durable-objects/api/stub) referring to an instance of a Durable Object class.
147141

142+
### `getByName`
143+
144+
`getByName` obtains a [`DurableObjectStub`](/durable-objects/api/stub) from a provided name, which can be used to invoke methods on a Durable Object.
145+
146+
This method returns the <GlossaryTooltip term="stub">stub</GlossaryTooltip> immediately, often before a connection has been established to the Durable Object. This allows requests to be sent to the instance right away, without waiting for a network round trip.
147+
148+
```js
149+
const fooStub = env.MY_DURABLE_OBJECT.getByName("foo");
150+
const barStub = env.MY_DURABLE_OBJECT.getByName("bar");
151+
```
152+
153+
#### Parameters
154+
155+
- A required string to be used to generate a [`DurableObjectStub`](/durable-objects/api/stub) corresponding to an instance of the Durable Object class with the provided name.
156+
157+
#### Return values
158+
159+
- A [`DurableObjectStub`](/durable-objects/api/stub) referring to an instance of a Durable Object class.
160+
148161
### `jurisdiction`
149162

150163
`jurisdiction` creates a subnamespace from a namespace where all Durable Object IDs and references created from that subnamespace will be restricted to the specified [jurisdiction](/durable-objects/reference/data-location/#restrict-durable-objects-to-a-jurisdiction).
151164

152165
```js
153166
const subnamespace = env.MY_DURABLE_OBJECT.jurisdiction("eu");
154-
const euId = subnamespace.idFromName("foo");
167+
const euStub = subnamespace.getByName("foo");
155168
```
156169

157170
#### Parameters

src/content/docs/durable-objects/api/stub.mdx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,10 @@ console.assert(id.equals(stub.id), "This should always be true");
3131

3232
### `name`
3333

34-
`name` is an optional property of a `DurableObjectStub`, which returns the name that was used to create the [`DurableObjectId`](/durable-objects/api/id) via [`DurableObjectNamespace::idFromName`](/durable-objects/api/namespace/#idfromname) which was then used to create the `DurableObjectStub`. This value is undefined if the [`DurableObjectId`](/durable-objects/api/id) used to create the `DurableObjectStub` was constructed using [`DurableObjectNamespace::newUniqueId`](/durable-objects/api/namespace/#newuniqueid).
34+
`name` is an optional property of a `DurableObjectStub`, which returns a name if it was provided upon stub creation either directly via [`DurableObjectNamespace::getByName`](/durable-objects/api/namespace/#getbyname) or indirectly via a [`DurableObjectId`](/durable-objects/api/id) created by [`DurableObjectNamespace::idFromName`](/durable-objects/api/namespace/#idfromname). This value is undefined if the [`DurableObjectId`](/durable-objects/api/id) used to create the `DurableObjectStub` was constructed using [`DurableObjectNamespace::newUniqueId`](/durable-objects/api/namespace/#newuniqueid).
3535

3636
```js
37-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
38-
const stub = env.MY_DURABLE_OBJECT.get(id);
37+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
3938
console.assert(stub.name === "foo", "This should always be true");
4039
```
4140

src/content/docs/durable-objects/best-practices/create-durable-object-stubs-and-send-requests.mdx

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,8 @@ export class MyDurableObject extends DurableObject {
5050
// Worker
5151
export default {
5252
async fetch(request, env) {
53-
// Every unique ID refers to an individual instance of the Durable Object class
54-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
55-
5653
// A stub is a client used to invoke methods on the Durable Object
57-
const stub = env.MY_DURABLE_OBJECT.get(id);
54+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
5855

5956
// Methods on the Durable Object are invoked via the stub
6057
const response = await stub.fetch(request);
@@ -87,11 +84,8 @@ export class MyDurableObject extends DurableObject {
8784
// Worker
8885
export default {
8986
async fetch(request, env) {
90-
// Every unique ID refers to an individual instance of the Durable Object class
91-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
92-
9387
// A stub is a client used to invoke methods on the Durable Object
94-
const stub = env.MY_DURABLE_OBJECT.get(id);
88+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
9589

9690
// Methods on the Durable Object are invoked via the stub
9791
const response = await stub.fetch(request);
@@ -147,11 +141,8 @@ export class MyDurableObject extends DurableObject {
147141
// Worker
148142
export default {
149143
async fetch(_request, env, _ctx) {
150-
// Every unique ID refers to an individual instance of the Durable Object class
151-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
152-
153144
// A stub is a client used to invoke methods on the Durable Object
154-
const stub = env.MY_DURABLE_OBJECT.get(id);
145+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
155146

156147
// Invoke the fetch handler on the Durable Object stub
157148
let response = await stub.fetch("http://do/hello?name=World");
@@ -205,11 +196,8 @@ export class MyDurableObject extends DurableObject {
205196
// Worker
206197
export default {
207198
async fetch(_request, env, _ctx) {
208-
// Every unique ID refers to an individual instance of the Durable Object class
209-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
210-
211199
// A stub is a client used to invoke methods on the Durable Object
212-
const stub = env.MY_DURABLE_OBJECT.get(id);
200+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
213201

214202
// Invoke the fetch handler on the Durable Object stub
215203
let response = await stub.fetch("http://do/hello?name=World");

src/content/docs/durable-objects/best-practices/error-handling.mdx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ sidebar:
77

88
import { GlossaryTooltip } from "~/components";
99

10-
1110
Any uncaught exceptions thrown by a <GlossaryTooltip term="Durable Object">Durable Object</GlossaryTooltip> or thrown by Durable Objects' infrastructure (such as overloads or network errors) will be propagated to the callsite of the client. Catching these exceptions allows you to retry creating the [`DurableObjectStub`](/durable-objects/api/stub) and sending requests.
1211

1312
JavaScript Errors with the property `.retryable` set to True are suggested to be retried if requests to the Durable Object are idempotent, or can be applied multiple times without changing the response. If requests are not idempotent, then you will need to decide what is best for your application.
@@ -39,7 +38,6 @@ export interface Env {
3938
export default {
4039
async fetch(request, env, ctx) {
4140
let userId = new URL(request.url).searchParams.get("userId") || "";
42-
const id = env.ErrorThrowingObject.idFromName(userId);
4341

4442
// Retry behavior can be adjusted to fit your application.
4543
let maxAttempts = 3;
@@ -52,7 +50,7 @@ export default {
5250
try {
5351
// Create a Durable Object stub for each attempt, because certain types of
5452
// errors will break the Durable Object stub.
55-
const doStub = env.ErrorThrowingObject.get(id);
53+
const doStub = env.ErrorThrowingObject.getByName(userId);
5654
const resp = await doStub.fetch("http://your-do/");
5755

5856
return Response.json(resp);

src/content/docs/durable-objects/best-practices/websockets.mdx

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,11 @@ The following are methods available on the **Native Durable Object WebSocket API
168168

169169
#### `WebSocket.serializeAttachment()`
170170

171-
- <code> serializeAttachment(value <Type text="any" />)</code>: <Type text="void" />
171+
- <code>
172+
{" "}
173+
serializeAttachment(value <Type text="any" />)
174+
</code>
175+
: <Type text="void" />
172176

173177
- Keeps a copy of `value` associated with the WebSocket to survive hibernation. The value can be any type supported by the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), which is true of most types. If the value needs to be durable please use [Durable Object Storage](/durable-objects/api/storage-api/).
174178

@@ -180,7 +184,6 @@ The following are methods available on the **Native Durable Object WebSocket API
180184

181185
- Retrieves the most recent value passed to `serializeAttachment()`, or `null` if none exists.
182186

183-
184187
## WebSocket Standard API
185188

186189
WebSocket connections are established by making an HTTP GET request with the `Upgrade: websocket` header. A Cloudflare Worker is commonly used to validate the request, proxy the request to the Durable Object to accept the server side connection, and return the client side connection in the response.
@@ -213,8 +216,7 @@ export default {
213216

214217
// This example will refer to a single Durable Object instance, since the name "foo" is
215218
// hardcoded
216-
let id = env.WEBSOCKET_SERVER.idFromName("foo");
217-
let stub = env.WEBSOCKET_SERVER.get(id);
219+
let stub = env.WEBSOCKET_SERVER.getByName("foo");
218220

219221
// The Durable Object's fetch handler will accept the server side connection and return
220222
// the client
@@ -254,8 +256,7 @@ export default {
254256

255257
// This example will refer to a single Durable Object instance, since the name "foo" is
256258
// hardcoded
257-
let id = env.WEBSOCKET_SERVER.idFromName("foo");
258-
let stub = env.WEBSOCKET_SERVER.get(id);
259+
let stub = env.WEBSOCKET_SERVER.getByName("foo");
259260

260261
// The Durable Object's fetch handler will accept the server side connection and return
261262
// the client

src/content/docs/durable-objects/concepts/durable-object-lifecycle.mdx

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ Simply creating the Durable Object Stub does not send a request to the Durable O
1414
A request is sent to the Durable Object and its lifecycle begins only once a method is invoked on the Durable Object Stub.
1515

1616
```js
17-
const id = env.MY_DURABLE_OBJECT.idFromName("foo");
18-
const stub = env.MY_DURABLE_OBJECT.get(id);
17+
const stub = env.MY_DURABLE_OBJECT.getByName("foo");
1918
// Now the request is sent to the remote Durable Object.
2019
const rpcResponse = await stub.sayHello();
2120
```

0 commit comments

Comments
 (0)