repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / test
Eric Bower · 06 Feb 24

supervisor.test.ts

 1import { describe, expect, it } from "../test.ts";
 2import {
 3  call,
 4  Operation,
 5  run,
 6  spawn,
 7  supervise,
 8  superviseBackoff,
 9} from "../mod.ts";
10import { ActionWithPayload } from "../types.ts";
11import { take } from "../action.ts";
12import { API_ACTION_PREFIX } from "../action.ts";
13
14const test = describe("supervise()");
15
16describe("superviseBackoff", () => {
17  it("should increase number exponentially", () => {
18    const actual: number[] = [];
19    for (let i = 1; i < 15; i += 1) {
20      actual.push(superviseBackoff(i));
21    }
22    expect(actual).toEqual([
23      20,
24      40,
25      80,
26      160,
27      320,
28      640,
29      1280,
30      2560,
31      5120,
32      10240,
33      -1,
34      -1,
35      -1,
36      -1,
37    ]);
38  });
39});
40
41type LogAction = ActionWithPayload<{ message: string }>;
42
43it(test, "should recover with backoff pressure", async () => {
44  const err = console.error;
45  console.error = () => {};
46
47  const actions: LogAction[] = [];
48  const backoff = (attempt: number) => {
49    if (attempt === 4) return -1;
50    return attempt;
51  };
52
53  await run(function* () {
54    function* op(): Operation<void> {
55      throw new Error("boom!");
56    }
57    yield* spawn(function* () {
58      while (true) {
59        const action = yield* take<LogAction["payload"]>("*");
60        actions.push(action);
61      }
62    });
63    yield* call(supervise(op, backoff));
64  });
65
66  expect(actions.length).toEqual(3);
67  expect(actions[0].type).toEqual(`${API_ACTION_PREFIX}supervise`);
68  expect(actions[0].meta).toEqual(
69    "Exception caught, waiting 1ms before restarting operation",
70  );
71  expect(actions[1].type).toEqual(`${API_ACTION_PREFIX}supervise`);
72  expect(actions[1].meta).toEqual(
73    "Exception caught, waiting 2ms before restarting operation",
74  );
75  expect(actions[2].type).toEqual(`${API_ACTION_PREFIX}supervise`);
76  expect(actions[2].meta).toEqual(
77    "Exception caught, waiting 3ms before restarting operation",
78  );
79
80  console.error = err;
81});