Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 42 additions & 61 deletions src/content/docs/durable-objects/api/alarms.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
title: Alarms
pcx_content_type: concept
sidebar:
order: 1

order: 6
---

import { Type } from "~/components";
Expand All @@ -20,18 +19,16 @@ Durable Objects alarms allow you to schedule the Durable Object to be woken up a

Notably:

* Each Durable Object instance is able to schedule a single alarm at a time by calling `setAlarm()`.
* Alarms have guaranteed at-least-once execution and are retried automatically when the `alarm()` handler throws.
* Retries are performed using exponential backoff starting at a two second delay from the first failure with up to six retries allowed.
- Each Durable Object instance is able to schedule a single alarm at a time by calling `setAlarm()`.
- Alarms have guaranteed at-least-once execution and are retried automatically when the `alarm()` handler throws.
- Retries are performed using exponential backoff starting at a 2 second delay from the first failure with up to 6 retries allowed.

:::note[How are alarms different from Cron Triggers?]


Alarms are more fine grained than [Cron Triggers](/workers/configuration/cron-triggers/#cron-triggers). A Worker can have up to three Cron Triggers configured at once, but it can have an unlimited amount of Durable Objects, each of which can have an alarm set.

Alarms are directly scheduled from within your Durable Object. Cron Triggers, on the other hand, are not programmatic. [Cron Triggers](/workers/configuration/cron-triggers/#cron-triggers) execute based on their schedules, which have to be configured through the Cloudflare dashboard or API.


:::

Alarms can be used to build distributed primitives, like queues or batching of work atop Durable Objects. Alarms also provide a mechanism to guarantee that operations within a Durable Object will complete without relying on incoming requests to keep the Durable Object alive. For a complete example, refer to [Use the Alarms API](/durable-objects/examples/alarms-api/).
Expand All @@ -40,94 +37,78 @@ Alarms can be used to build distributed primitives, like queues or batching of w

### getAlarm

- <code>getAlarm()</code>: <Type text ='number | null' />


* `getAlarm()`: <Type text ='number | null' />

* If there is an alarm set, then return the currently set alarm time in number of milliseconds elapsed since the UNIX epoch. Otherwise, return `null`.


- If there is an alarm set, then return the currently set alarm time as the number of milliseconds elapsed since the UNIX epoch. Otherwise, return `null`.

### setAlarm

- <code> setAlarm(scheduledTimeMs <Type text="number" />)</code>: <Type text="void" />


* <code>setAlarm(scheduledTimeMs <Type text='number'/>)</code>: <Type text='void' />

* Set the time for the alarm to run at in number of milliseconds elapsed since the UNIX epoch.


- Set the time for the alarm to run. Specify the time as the number of milliseconds elapsed since the UNIX epoch.

### deleteAlarm

- `deleteAlarm()`: <Type text='void' />

- Unset the alarm if there is a currently set alarm.

* `deleteAlarm()`: <Type text='void' />

* Unset the alarm if there is a currently set alarm.

* Calling `deleteAlarm()` inside the `alarm()` handler may prevent retries on a best-effort basis, but is not guaranteed.


- Calling `deleteAlarm()` inside the `alarm()` handler may prevent retries on a best-effort basis, but is not guaranteed.

## Handler methods

### alarm

- `alarm()`: <Type text='void' />

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

* `alarm()`: <Type text='void' />

* Called by the system when a scheduled alarm time is reached.

* The `alarm()` handler has guaranteed at-least-once execution and will be retried upon failure using exponential backoff, starting at two second delays for up to six retries. Retries will be performed if the method fails with an uncaught exception.

* This method can be `async`.

- The `alarm()` handler has guaranteed at-least-once execution and will be retried upon failure using exponential backoff, starting at 2 second delays for up to 6 retries. Retries will be performed if the method fails with an uncaught exception.

- This method can be `async`.

## Example

This example shows how to both set alarms with the `setAlarm(timestamp)` method and handle alarms with the `alarm()` handler within your Durable Object.

* The `alarm()` handler will be called once every time an alarm fires.
* If an unexpected error terminates the Durable Object, the `alarm()` handler will be re-instantiated on another machine.
* Following a short delay, the `alarm()` handler will run from the beginning on the other machine.
- The `alarm()` handler will be called once every time an alarm fires.
- If an unexpected error terminates the Durable Object, the `alarm()` handler will be re-instantiated on another machine.
- Following a short delay, the `alarm()` handler will run from the beginning on the other machine.

```js
import { DurableObject } from 'cloudflare:workers';
import { DurableObject } from "cloudflare:workers";

export default {
async fetch(request, env) {
let id = env.ALARM_EXAMPLE.idFromName("foo");
return await env.ALARM_EXAMPLE.get(id).fetch(request);
},
async fetch(request, env) {
let id = env.ALARM_EXAMPLE.idFromName("foo");
return await env.ALARM_EXAMPLE.get(id).fetch(request);
},
};

const SECONDS = 1000;

export class AlarmExample extends DurableObject {
constructor(ctx, env) {
this.ctx = ctx;
this.storage = ctx.storage;
}
async fetch(request) {
// If there is no alarm currently set, set one for 10 seconds from now
let currentAlarm = await this.storage.getAlarm();
if (currentAlarm == null) {
this.storage.setAlarm(Date.now() + 10 * SECONDS);
}
}
async alarm() {
// The alarm handler will be invoked whenever an alarm fires.
// You can use this to do work, read from the Storage API, make HTTP calls
// and set future alarms to run using this.storage.setAlarm() from within this handler.
}
constructor(ctx, env) {
this.ctx = ctx;
this.storage = ctx.storage;
}
async fetch(request) {
// If there is no alarm currently set, set one for 10 seconds from now
let currentAlarm = await this.storage.getAlarm();
if (currentAlarm == null) {
this.storage.setAlarm(Date.now() + 10 * SECONDS);
}
}
async alarm() {
// The alarm handler will be invoked whenever an alarm fires.
// You can use this to do work, read from the Storage API, make HTTP calls
// and set future alarms to run using this.storage.setAlarm() from within this handler.
}
}
```

## Related resources

* Understand how to [use the Alarms API](/durable-objects/examples/alarms-api/) in an end-to-end example.
* Read the [Durable Objects alarms announcement blog post](https://blog.cloudflare.com/durable-objects-alarms/).
* Review the [Storage API](/durable-objects/api/storage-api/) documentation for Durable Objects.
- Understand how to [use the Alarms API](/durable-objects/examples/alarms-api/) in an end-to-end example.
- Read the [Durable Objects alarms announcement blog post](https://blog.cloudflare.com/durable-objects-alarms/).
- Review the [Storage API](/durable-objects/api/storage-api/) documentation for Durable Objects.
84 changes: 84 additions & 0 deletions src/content/docs/durable-objects/api/id.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
title: Durable Object ID
pcx_content_type: concept
sidebar:
order: 2
---

import { Tabs, TabItem } from "~/components";

## Description

The `DurableObjectId` interface refers to a new or existing Durable Object instance. This interface is most frequently used by [`DurableObjectNamespace::get`](/durable-objects/api/namespace/#get) to obtain a stub for submitting requests to a Durable Object instance.

Note that creating an ID for a Durable Object instance does not create the Durable Object. The Durable Object is created lazily after calling [`DurableObjectNamespace::get`](/durable-objects/api/namespace/#get) to create a [`DurableObjectStub`](/durable-objects/api/stub) from a `DurableObjectId`. This ensures that objects are not constructed until they are actually accessed.

:::note[`DurableObjectId`]

If you are experiencing an issue with a particular Durable Object instance, you may wish to log the `DurableObjectId` from your Worker and include it in your Cloudflare support request.

:::

## Methods

### `toString`

#### Description

`toString` converts a `DurableObjectId` to a 64 digit hex string. This string is useful for logging purposes or storing the `DurableObjectId` elsewhere, for example, in a session cookie. This string can be used to reconstruct a `DurableObjectId` via `DurableObjectNamespace::idFromString`.

```js
// Create a new unique ID
const id = env.MY_DURABLE_OBJECT.newUniqueId();
// Save the unique ID elsewhere, e.g. a session cookie via id.toString()
...
// Recreate the ID from the string
const id = env.MY_DURABLE_OBJECT.idFromString(session_id);
```

#### Parameters

None.

#### Return value

A 64 digit hex string.

### `equals`

#### Description

`equals` is used to compare equality between two instances of `DurableObjectId`.

```js
const id1 = env.MY_DURABLE_OBJECT.newUniqueId();
const id2 = env.MY_DURABLE_OBJECT.newUniqueId();
console.assert(!id1.equals(id2), "Different unique ids should never be equal.");
```

#### Parameters

A required `DurableObjectId` to compare against.

#### Return value

A boolean. True if equal and false otherwise.

## Properties

### `name`

#### Description

`name` is an optional property of a `DurableObjectId`, which returns the name that was used to create the `DurableObjectId` via [`DurableObjectNamespace::idFromName`](/durable-objects/api/namespace/#idfromname). This value is undefined if the `DurableObjectId` was constructed using [`DurableObjectNamespace::newUniqueId`](/durable-objects/api/namespace/#newuniqueid).

```js
const uniqueId = env.MY_DURABLE_OBJECT.newUniqueId();
const fromNameId = env.MY_DURABLE_OBJECT.idFromName("foo");
console.assert(uniqueId.name === undefined, "unique ids have no name");
console.assert(fromNameId.name === "foo", "name matches parameter to idFromName");
```

## Related resources

- [Durable Objects: Easy, Fast, Correct – Choose Three](https://blog.cloudflare.com/durable-objects-easy-fast-correct-choose-three/).
2 changes: 1 addition & 1 deletion src/content/docs/durable-objects/api/index.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: API
title: Runtime APIs
pcx_content_type: navigation
sidebar:
order: 4
Expand Down
Loading
Loading