aboutsummaryrefslogtreecommitdiffstats
path: root/packages/plugins/queue-restate/src/admin.ts
blob: dddc8f004c5e2d73da47398d240f542a73f1efcc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { z } from "zod";

export class AdminClient {
  constructor(private addr: string) {}

  async upsertDeployment(deploymentAddr: string) {
    const res = await fetch(`${this.addr}/deployments`, {
      method: "POST",
      body: JSON.stringify({
        uri: deploymentAddr,
        force: true,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (!res.ok) {
      throw new Error(`Failed to upsert deployment: ${res.status}`);
    }
  }

  async getStats(serviceName: string) {
    const query = `select status, count(*) as count from sys_invocation where target_service_name='${serviceName}' group by status`;
    const res = await fetch(`${this.addr}/query`, {
      method: "POST",
      body: JSON.stringify({
        query,
      }),
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    if (!res.ok) {
      throw new Error(`Failed to get stats: ${res.status}`);
    }
    const zStatus = z.enum([
      "pending",
      "scheduled",
      "ready",
      "running",
      "paused",
      "backing-off",
      "suspended",
      "completed",
    ]);
    const zSchema = z.object({
      rows: z.array(
        z.object({
          status: zStatus,
          count: z.number(),
        }),
      ),
    });

    return zSchema.parse(await res.json()).rows.reduce(
      (acc, cur) => {
        acc[cur.status] = cur.count;
        return acc;
      },
      {
        pending: 0,
        scheduled: 0,
        ready: 0,
        running: 0,
        paused: 0,
        "backing-off": 0,
        suspended: 0,
        completed: 0,
      } as Record<z.infer<typeof zStatus>, number>,
    );
  }
}