Skip to content
File

Blob: src/workerd/api/tests/actor-alarms-test.js

javascript73 lines
1// Copyright (c) 2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import * as assert from 'node:assert';
6 
7export class DurableObjectExample {
8 constructor(state, env) {
9 this.state = state;
10 }
11 
12 async waitForAlarm(scheduledTime) {
13 // eslint-disable-next-line @typescript-eslint/no-this-alias
14 let self = this;
15 const { promise, resolve, reject } = Promise.withResolvers();
16 self.resolve = resolve;
17 self.reject = reject;
18 
19 try {
20 await promise;
21 if (Date.now() < scheduledTime.valueOf()) {
22 throw new Error(
23 `Date.now() is before scheduledTime! ${Date.now()} vs ${scheduledTime.valueOf()}`
24 );
25 }
26 } catch (e) {
27 throw new Error(
28 `error waiting for alarm at ${scheduledTime.valueOf()}: ${e}`
29 );
30 }
31 
32 let alarm = await this.state.storage.getAlarm();
33 if (alarm != null) {
34 throw new Error(`alarm time not cleared when handler ends. ${alarm}`);
35 }
36 }
37 
38 async fetch() {
39 const time = Date.now() + 50;
40 this.scheduledTime = time;
41 await this.state.storage.setAlarm(time);
42 assert.equal(await this.state.storage.getAlarm(), time);
43 
44 await this.waitForAlarm(time);
45 
46 return new Response('OK');
47 }
48 
49 async alarm(alarmInfo) {
50 try {
51 let time = await this.state.storage.getAlarm();
52 if (time !== null) {
53 throw new Error(`time not null inside alarm handler ${time}`);
54 }
55 assert.strictEqual(typeof alarmInfo.scheduledTime, 'number');
56 assert.strictEqual(alarmInfo.scheduledTime, this.scheduledTime);
57 this.resolve();
58 } catch (e) {
59 this.reject(e);
60 }
61 }
62}
63 
64export const test = {
65 async test(ctrl, env, ctx) {
66 let id = env.ns.idFromName('A');
67 let obj = env.ns.get(id);
68 let res = await obj.fetch('http://foo/test');
69 let text = await res.text();
70 assert.equal(text, 'OK');
71 },
72};