@checkstack/dashboards-backend 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/router.ts ADDED
@@ -0,0 +1,157 @@
1
+ import { implement, ORPCError } from "@orpc/server";
2
+ import {
3
+ autoAuthMiddleware,
4
+ correlationMiddleware,
5
+ type RpcContext,
6
+ } from "@checkstack/backend-api";
7
+ import { dashboardsContract } from "@checkstack/dashboards-common";
8
+ import type { DashboardService } from "./service";
9
+ import { GLOBAL_HOME_SCOPE, toSummary, userHomeScope } from "./service";
10
+ import { filterDashboardsForCaller, resolveHomeDashboard } from "./read-access";
11
+
12
+ function callerUserId(user: RpcContext["user"]): string | null {
13
+ return user && user.type === "user" ? user.id : null;
14
+ }
15
+
16
+ export function createRouter({ service }: { service: DashboardService }) {
17
+ const os = implement(dashboardsContract)
18
+ .$context<RpcContext>()
19
+ .use(correlationMiddleware)
20
+ .use(autoAuthMiddleware);
21
+
22
+ return os.router({
23
+ listDashboards: os.listDashboards.handler(async ({ context }) => {
24
+ const rows = await service.list();
25
+ const visible = await filterDashboardsForCaller({
26
+ user: context.user,
27
+ auth: context.auth,
28
+ rows,
29
+ });
30
+ return { dashboards: visible.map((d) => toSummary(d)) };
31
+ }),
32
+
33
+ listDashboardsForSystem: os.listDashboardsForSystem.handler(
34
+ async ({ input, context }) => {
35
+ const rows = await service.listForSystem({ systemId: input.systemId });
36
+ const visible = await filterDashboardsForCaller({
37
+ user: context.user,
38
+ auth: context.auth,
39
+ rows,
40
+ });
41
+ return { dashboards: visible.map((d) => toSummary(d)) };
42
+ },
43
+ ),
44
+
45
+ getDashboard: os.getDashboard.handler(async ({ input, context }) => {
46
+ const dashboard = await service.get({ id: input.id });
47
+ if (!dashboard) return null;
48
+ const [visible] = await filterDashboardsForCaller({
49
+ user: context.user,
50
+ auth: context.auth,
51
+ rows: [dashboard],
52
+ });
53
+ return visible ?? null;
54
+ }),
55
+
56
+ getPublishedDashboard: os.getPublishedDashboard.handler(
57
+ async ({ input, context }) => {
58
+ const dashboard = await service.get({ id: input.id });
59
+ if (!dashboard || dashboard.visibility !== "public") return null;
60
+ const [visible] = await filterDashboardsForCaller({
61
+ user: context.user,
62
+ auth: context.auth,
63
+ rows: [dashboard],
64
+ });
65
+ return visible ?? null;
66
+ },
67
+ ),
68
+
69
+ createDashboard: os.createDashboard.handler(async ({ input, context }) => {
70
+ const createdBy =
71
+ context.user && "id" in context.user ? context.user.id : null;
72
+ return service.create({ input, createdBy });
73
+ }),
74
+
75
+ updateDashboard: os.updateDashboard.handler(async ({ input }) => {
76
+ const updated = await service.update({ input });
77
+ if (!updated) {
78
+ throw new ORPCError("NOT_FOUND", { message: "Dashboard not found" });
79
+ }
80
+ return updated;
81
+ }),
82
+
83
+ deleteDashboard: os.deleteDashboard.handler(async ({ input }) => {
84
+ const success = await service.delete({ id: input.id });
85
+ if (!success) {
86
+ throw new ORPCError("NOT_FOUND", { message: "Dashboard not found" });
87
+ }
88
+ return { success };
89
+ }),
90
+
91
+ getHomeDashboard: os.getHomeDashboard.handler(async ({ context }) => {
92
+ const { userChoiceId, globalChoiceId } = await service.getHomeChoices({
93
+ userId: callerUserId(context.user),
94
+ });
95
+ const candidates = await service.getMany({
96
+ ids: [userChoiceId, globalChoiceId].filter((id): id is string => id !== null),
97
+ });
98
+ const readable = await filterDashboardsForCaller({
99
+ user: context.user,
100
+ auth: context.auth,
101
+ rows: candidates,
102
+ });
103
+ const { source, dashboard } = resolveHomeDashboard({
104
+ userChoiceId,
105
+ globalChoiceId,
106
+ readable,
107
+ });
108
+ return { source, userDashboardId: userChoiceId, globalDashboardId: globalChoiceId, dashboard };
109
+ }),
110
+
111
+ setMyHomeDashboard: os.setMyHomeDashboard.handler(async ({ input, context }) => {
112
+ const userId = callerUserId(context.user);
113
+ if (!userId) {
114
+ throw new ORPCError("FORBIDDEN", { message: "Only users have a home dashboard" });
115
+ }
116
+ // Only a dashboard the caller can view may become their home.
117
+ const dashboard = await service.get({ id: input.dashboardId });
118
+ const [visible] = dashboard
119
+ ? await filterDashboardsForCaller({
120
+ user: context.user,
121
+ auth: context.auth,
122
+ rows: [dashboard],
123
+ })
124
+ : [];
125
+ const success =
126
+ visible !== undefined &&
127
+ (await service.setHomeChoice({
128
+ scope: userHomeScope(userId),
129
+ dashboardId: input.dashboardId,
130
+ }));
131
+ if (!success) {
132
+ throw new ORPCError("NOT_FOUND", { message: "Dashboard not found" });
133
+ }
134
+ return { success };
135
+ }),
136
+
137
+ resetMyHomeDashboard: os.resetMyHomeDashboard.handler(async ({ context }) => {
138
+ const userId = callerUserId(context.user);
139
+ if (!userId) {
140
+ throw new ORPCError("FORBIDDEN", { message: "Only users have a home dashboard" });
141
+ }
142
+ await service.setHomeChoice({ scope: userHomeScope(userId), dashboardId: null });
143
+ return { success: true };
144
+ }),
145
+
146
+ setGlobalHomeDashboard: os.setGlobalHomeDashboard.handler(async ({ input }) => {
147
+ const success = await service.setHomeChoice({
148
+ scope: GLOBAL_HOME_SCOPE,
149
+ dashboardId: input.dashboardId,
150
+ });
151
+ if (!success) {
152
+ throw new ORPCError("NOT_FOUND", { message: "Dashboard not found" });
153
+ }
154
+ return { success };
155
+ }),
156
+ });
157
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { index, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
2
+ import type {
3
+ DashboardSettings,
4
+ DashboardVisibility,
5
+ Panel,
6
+ } from "@checkstack/dashboards-common";
7
+
8
+ /**
9
+ * User-built dashboards, one row per dashboard. The panel layout is a single
10
+ * JSONB document (validated by `PanelListSchema` at the RPC boundary) - panels
11
+ * are always read and written as a whole, never queried individually.
12
+ */
13
+ export const dashboards = pgTable(
14
+ "dashboards",
15
+ {
16
+ id: text("id").primaryKey(),
17
+ /** Owning catalog system; null for a global (system-less) dashboard. */
18
+ systemId: text("system_id"),
19
+ title: text("title").notNull(),
20
+ description: text("description"),
21
+ tags: jsonb("tags").$type<string[]>().notNull().default([]),
22
+ panels: jsonb("panels").$type<Panel[]>().notNull().default([]),
23
+ /** Who can view it besides its teams (see `DashboardVisibilitySchema`). */
24
+ visibility: text("visibility")
25
+ .$type<DashboardVisibility>()
26
+ .notNull()
27
+ .default("authenticated"),
28
+ visibleRoleIds: jsonb("visible_role_ids").$type<string[]>().notNull().default([]),
29
+ settings: jsonb("settings").$type<DashboardSettings>().notNull(),
30
+ createdBy: text("created_by"),
31
+ createdAt: timestamp("created_at").defaultNow().notNull(),
32
+ updatedAt: timestamp("updated_at").defaultNow().notNull(),
33
+ },
34
+ (t) => [index("dashboards_system_id_idx").on(t.systemId)],
35
+ );
36
+
37
+ /**
38
+ * Home-dashboard choices. `scope` is `"global"` for the organization-wide
39
+ * default or `"user:<userId>"` for one user's personal choice, so both levels
40
+ * live in one shared table (every pod reads the same answer). Deleting a
41
+ * dashboard drops every choice that pointed at it.
42
+ */
43
+ export const homeDashboards = pgTable("home_dashboards", {
44
+ scope: text("scope").primaryKey(),
45
+ dashboardId: text("dashboard_id")
46
+ .notNull()
47
+ .references(() => dashboards.id, { onDelete: "cascade" }),
48
+ updatedAt: timestamp("updated_at").defaultNow().notNull(),
49
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Integration test (real Postgres) for the DashboardService. Gated behind
3
+ * `CHECKSTACK_IT=1`; see `core/test-utils-backend/src/with-test-db.ts`.
4
+ */
5
+ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dirname, resolve } from "node:path";
8
+ import {
9
+ isIntegrationEnabled,
10
+ withTestDb,
11
+ type TestDb,
12
+ } from "@checkstack/test-utils-backend";
13
+ import { CreateDashboardInputSchema, PanelSchema } from "@checkstack/dashboards-common";
14
+ import * as schema from "./schema";
15
+ import { DashboardService, toSummary } from "./service";
16
+
17
+ const migrationsFolder = resolve(
18
+ dirname(fileURLToPath(import.meta.url)),
19
+ "..",
20
+ "drizzle",
21
+ );
22
+
23
+ describe.skipIf(!isIntegrationEnabled())("DashboardService (real Postgres)", () => {
24
+ let testDb: TestDb<typeof schema>;
25
+ let service: DashboardService;
26
+
27
+ beforeAll(async () => {
28
+ testDb = await withTestDb({ schema, migrationsFolder });
29
+ service = new DashboardService(testDb.db);
30
+ });
31
+
32
+ afterAll(async () => {
33
+ await testDb.dispose();
34
+ });
35
+
36
+ const panel = PanelSchema.parse({
37
+ id: "p1",
38
+ type: "dashboards.stat",
39
+ gridPos: { x: 0, y: 0, w: 6, h: 4 },
40
+ });
41
+
42
+ it("round-trips a dashboard with panels and settings", async () => {
43
+ const created = await service.create({
44
+ input: CreateDashboardInputSchema.parse({
45
+ systemId: "sys-1",
46
+ title: "API",
47
+ tags: ["prod"],
48
+ panels: [panel],
49
+ }),
50
+ createdBy: "user-1",
51
+ });
52
+ const loaded = await service.get({ id: created.id });
53
+ expect(loaded?.panels).toEqual([panel]);
54
+ expect(loaded?.settings.timeRange).toEqual({ from: "now-6h", to: "now" });
55
+ expect(loaded && toSummary(loaded).panelCount).toBe(1);
56
+ });
57
+
58
+ it("patches only the given fields", async () => {
59
+ const created = await service.create({
60
+ input: CreateDashboardInputSchema.parse({ systemId: "sys-1", title: "Keep" }),
61
+ createdBy: null,
62
+ });
63
+ const updated = await service.update({
64
+ input: { id: created.id, description: "new" },
65
+ });
66
+ expect(updated?.title).toBe("Keep");
67
+ expect(updated?.description).toBe("new");
68
+ expect(await service.update({ input: { id: "missing", title: "x" } })).toBeUndefined();
69
+ });
70
+
71
+ it("lists per system and cleans up a deleted system", async () => {
72
+ await service.create({
73
+ input: CreateDashboardInputSchema.parse({ systemId: "sys-2", title: "Other" }),
74
+ createdBy: null,
75
+ });
76
+ expect((await service.listForSystem({ systemId: "sys-2" })).length).toBe(1);
77
+ expect(await service.deleteForSystem({ systemId: "sys-1" })).toBe(2);
78
+ expect(await service.listForSystem({ systemId: "sys-1" })).toEqual([]);
79
+ expect((await service.list()).map((d) => d.systemId)).toEqual(["sys-2"]);
80
+ });
81
+
82
+ it("searches titles with LIKE wildcards escaped", async () => {
83
+ await service.create({
84
+ input: CreateDashboardInputSchema.parse({ systemId: "sys-3", title: "100% uptime" }),
85
+ createdBy: null,
86
+ });
87
+ expect((await service.search({ query: "100%", limit: 5 })).map((r) => r.name)).toEqual([
88
+ "100% uptime",
89
+ ]);
90
+ expect(await service.search({ query: "_", limit: 5 })).toEqual([]);
91
+ });
92
+ });
package/src/service.ts ADDED
@@ -0,0 +1,226 @@
1
+ import { desc, eq, ilike, inArray } from "drizzle-orm";
2
+ import type { SafeDatabase } from "@checkstack/backend-api";
3
+ import {
4
+ DashboardSettingsSchema,
5
+ type CreateDashboardInput,
6
+ type Dashboard,
7
+ type DashboardSummary,
8
+ type UpdateDashboardInput,
9
+ } from "@checkstack/dashboards-common";
10
+ import * as schema from "./schema";
11
+ import { dashboards, homeDashboards } from "./schema";
12
+
13
+ type Db = SafeDatabase<typeof schema>;
14
+
15
+ /** `home_dashboards.scope` of the organization-wide home dashboard. */
16
+ export const GLOBAL_HOME_SCOPE = "global";
17
+ /** `home_dashboards.scope` of one user's personal home dashboard. */
18
+ export const userHomeScope = (userId: string): string => `user:${userId}`;
19
+ type Row = typeof dashboards.$inferSelect;
20
+
21
+ export function mapDashboardRow(row: Row): Dashboard {
22
+ return {
23
+ id: row.id,
24
+ systemId: row.systemId,
25
+ title: row.title,
26
+ description: row.description,
27
+ tags: row.tags,
28
+ panels: row.panels,
29
+ visibility: row.visibility,
30
+ visibleRoleIds: row.visibleRoleIds,
31
+ // Older rows / hand-edited JSON get defaults rather than failing the read.
32
+ settings: DashboardSettingsSchema.parse(row.settings ?? {}),
33
+ createdBy: row.createdBy,
34
+ createdAt: row.createdAt,
35
+ updatedAt: row.updatedAt,
36
+ };
37
+ }
38
+
39
+ export function toSummary(dashboard: Dashboard): DashboardSummary {
40
+ return {
41
+ id: dashboard.id,
42
+ systemId: dashboard.systemId,
43
+ title: dashboard.title,
44
+ description: dashboard.description,
45
+ tags: dashboard.tags,
46
+ visibility: dashboard.visibility,
47
+ visibleRoleIds: dashboard.visibleRoleIds,
48
+ panelCount: dashboard.panels.length,
49
+ createdBy: dashboard.createdBy,
50
+ createdAt: dashboard.createdAt,
51
+ updatedAt: dashboard.updatedAt,
52
+ };
53
+ }
54
+
55
+ export class DashboardService {
56
+ constructor(private readonly db: Db) {}
57
+
58
+ async list(): Promise<Dashboard[]> {
59
+ const rows = await this.db
60
+ .select()
61
+ .from(dashboards)
62
+ .orderBy(desc(dashboards.updatedAt));
63
+ return rows.map((r) => mapDashboardRow(r));
64
+ }
65
+
66
+ async listForSystem({ systemId }: { systemId: string }): Promise<Dashboard[]> {
67
+ const rows = await this.db
68
+ .select()
69
+ .from(dashboards)
70
+ .where(eq(dashboards.systemId, systemId))
71
+ .orderBy(dashboards.title);
72
+ return rows.map((r) => mapDashboardRow(r));
73
+ }
74
+
75
+ async get({ id }: { id: string }): Promise<Dashboard | undefined> {
76
+ const [row] = await this.db
77
+ .select()
78
+ .from(dashboards)
79
+ .where(eq(dashboards.id, id));
80
+ return row ? mapDashboardRow(row) : undefined;
81
+ }
82
+
83
+ async create({
84
+ input,
85
+ createdBy,
86
+ }: {
87
+ input: CreateDashboardInput;
88
+ createdBy: string | null;
89
+ }): Promise<Dashboard> {
90
+ const [row] = await this.db
91
+ .insert(dashboards)
92
+ .values({
93
+ id: crypto.randomUUID(),
94
+ systemId: input.systemId ?? null,
95
+ title: input.title,
96
+ description: input.description ?? null,
97
+ tags: input.tags,
98
+ panels: input.panels,
99
+ settings: input.settings,
100
+ visibility: input.visibility,
101
+ visibleRoleIds: input.visibleRoleIds,
102
+ createdBy,
103
+ })
104
+ .returning();
105
+ return mapDashboardRow(row);
106
+ }
107
+
108
+ async update({
109
+ input,
110
+ }: {
111
+ input: UpdateDashboardInput;
112
+ }): Promise<Dashboard | undefined> {
113
+ const { id, ...patch } = input;
114
+ const [row] = await this.db
115
+ .update(dashboards)
116
+ .set({
117
+ ...(patch.title === undefined ? {} : { title: patch.title }),
118
+ ...(patch.description === undefined
119
+ ? {}
120
+ : { description: patch.description }),
121
+ ...(patch.tags === undefined ? {} : { tags: patch.tags }),
122
+ ...(patch.panels === undefined ? {} : { panels: patch.panels }),
123
+ ...(patch.settings === undefined ? {} : { settings: patch.settings }),
124
+ ...(patch.visibility === undefined ? {} : { visibility: patch.visibility }),
125
+ ...(patch.visibleRoleIds === undefined
126
+ ? {}
127
+ : { visibleRoleIds: patch.visibleRoleIds }),
128
+ updatedAt: new Date(),
129
+ })
130
+ .where(eq(dashboards.id, id))
131
+ .returning();
132
+ return row ? mapDashboardRow(row) : undefined;
133
+ }
134
+
135
+ async delete({ id }: { id: string }): Promise<boolean> {
136
+ const rows = await this.db
137
+ .delete(dashboards)
138
+ .where(eq(dashboards.id, id))
139
+ .returning({ id: dashboards.id });
140
+ return rows.length > 0;
141
+ }
142
+
143
+ /** Remove every dashboard of a deleted system. Returns the removed count. */
144
+ async deleteForSystem({ systemId }: { systemId: string }): Promise<number> {
145
+ const rows = await this.db
146
+ .delete(dashboards)
147
+ .where(eq(dashboards.systemId, systemId))
148
+ .returning({ id: dashboards.id });
149
+ return rows.length;
150
+ }
151
+
152
+ /** The stored home choices (unvalidated) for a user and the organization. */
153
+ async getHomeChoices({
154
+ userId,
155
+ }: {
156
+ userId: string | null;
157
+ }): Promise<{ userChoiceId: string | null; globalChoiceId: string | null }> {
158
+ const scopes = [GLOBAL_HOME_SCOPE, ...(userId ? [userHomeScope(userId)] : [])];
159
+ const rows = await this.db
160
+ .select({ scope: homeDashboards.scope, dashboardId: homeDashboards.dashboardId })
161
+ .from(homeDashboards)
162
+ .where(inArray(homeDashboards.scope, scopes));
163
+ const byScope = new Map(rows.map((r) => [r.scope, r.dashboardId]));
164
+ return {
165
+ userChoiceId: userId ? (byScope.get(userHomeScope(userId)) ?? null) : null,
166
+ globalChoiceId: byScope.get(GLOBAL_HOME_SCOPE) ?? null,
167
+ };
168
+ }
169
+
170
+ /** Point a home scope at a dashboard (null clears it). False if no such dashboard. */
171
+ async setHomeChoice({
172
+ scope,
173
+ dashboardId,
174
+ }: {
175
+ scope: string;
176
+ dashboardId: string | null;
177
+ }): Promise<boolean> {
178
+ if (dashboardId === null) {
179
+ await this.db.delete(homeDashboards).where(eq(homeDashboards.scope, scope));
180
+ return true;
181
+ }
182
+ if (!(await this.get({ id: dashboardId }))) return false;
183
+ await this.db
184
+ .insert(homeDashboards)
185
+ .values({ scope, dashboardId })
186
+ .onConflictDoUpdate({
187
+ target: homeDashboards.scope,
188
+ set: { dashboardId, updatedAt: new Date() },
189
+ });
190
+ return true;
191
+ }
192
+
193
+ async getMany({ ids }: { ids: string[] }): Promise<Dashboard[]> {
194
+ if (ids.length === 0) return [];
195
+ const rows = await this.db
196
+ .select()
197
+ .from(dashboards)
198
+ .where(inArray(dashboards.id, ids));
199
+ return rows.map((r) => mapDashboardRow(r));
200
+ }
201
+
202
+ async resolveNames({ ids }: { ids: string[] }): Promise<Map<string, string>> {
203
+ if (ids.length === 0) return new Map();
204
+ const rows = await this.db
205
+ .select({ id: dashboards.id, title: dashboards.title })
206
+ .from(dashboards)
207
+ .where(inArray(dashboards.id, ids));
208
+ return new Map(rows.map((r) => [r.id, r.title]));
209
+ }
210
+
211
+ async search({
212
+ query,
213
+ limit,
214
+ }: {
215
+ query: string;
216
+ limit: number;
217
+ }): Promise<Array<{ id: string; name: string }>> {
218
+ const escaped = query.replaceAll(/[\\%_]/g, (c) => `\\${c}`);
219
+ return this.db
220
+ .select({ id: dashboards.id, name: dashboards.title })
221
+ .from(dashboards)
222
+ .where(ilike(dashboards.title, `%${escaped}%`))
223
+ .orderBy(dashboards.title)
224
+ .limit(limit);
225
+ }
226
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "extends": "@checkstack/tsconfig/backend.json",
3
+ "include": [
4
+ "src"
5
+ ],
6
+ "references": [
7
+ {
8
+ "path": "../ai-backend"
9
+ },
10
+ {
11
+ "path": "../ai-common"
12
+ },
13
+ {
14
+ "path": "../auth-common"
15
+ },
16
+ {
17
+ "path": "../automation-backend"
18
+ },
19
+ {
20
+ "path": "../backend-api"
21
+ },
22
+ {
23
+ "path": "../catalog-backend"
24
+ },
25
+ {
26
+ "path": "../catalog-common"
27
+ },
28
+ {
29
+ "path": "../command-backend"
30
+ },
31
+ {
32
+ "path": "../common"
33
+ },
34
+ {
35
+ "path": "../dashboards-common"
36
+ },
37
+ {
38
+ "path": "../drizzle-helper"
39
+ },
40
+ {
41
+ "path": "../test-utils-backend"
42
+ }
43
+ ]
44
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.