Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: clean up legacy trpc calls (#1787)
Maximilian Kaske4160059956a6
diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.tsindex a3d000ff0..6357dfa57 100644--- a/packages/api/src/router/incident.ts+++ b/packages/api/src/router/incident.ts@@ -1,15 +1,6 @@import { z } from "zod";-import {- type SQL,- and,- asc,- desc,- eq,- gte,- isNull,- schema,-} from "@openstatus/db";+import { type SQL, and, asc, desc, eq, gte, schema } from "@openstatus/db";import {incidentTable,selectIncidentSchema,@@ -22,138 +13,6 @@ import { createTRPCRouter, protectedProcedure } from "../trpc";import { getPeriodDate, periods } from "./utils";export const incidentRouter = createTRPCRouter({- // TODO: rename getIncidentsByWorkspace to make it consistent with the other methods- getIncidentsByWorkspace: protectedProcedure- .output(z.array(selectIncidentSchema))- .query(async (opts) => {- const result = await opts.ctx.db- .select()- .from(schema.incidentTable)- .where(eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id))- .leftJoin(- schema.monitor,- eq(schema.incidentTable.monitorId, schema.monitor.id),- )- .all();- return z- .array(selectIncidentSchema)- .parse(- result.map((r) => ({ ...r.incident, monitorName: r.monitor?.name })),- );- }),-- getIncidentById: protectedProcedure- .input(z.object({ id: z.number() }))- .output(selectIncidentSchema)- .query(async (opts) => {- const result = await opts.ctx.db- .select()- .from(schema.incidentTable)- .where(- and(- eq(schema.incidentTable.id, opts.input.id),- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- ),- )- .leftJoin(- schema.monitor,- eq(schema.incidentTable.monitorId, schema.monitor.id),- )- .get();-- return selectIncidentSchema.parse({- ...result?.incident,- monitorName: result?.monitor?.name,- });- }),-- getOpenIncidents: protectedProcedure.query(async (opts) => {- return await opts.ctx.db- .select()- .from(schema.incidentTable)- .where(- and(- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- isNull(schema.incidentTable.resolvedAt),- ),- )- .all();- }),-- acknowledgeIncident: protectedProcedure- .meta({ track: Events.AcknowledgeIncident })- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const currentIncident = await opts.ctx.db- .select()- .from(schema.incidentTable)- .where(- and(- eq(schema.incidentTable.id, opts.input.id),- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- ),- )- .get();- if (!currentIncident) {- throw new Error("Incident not found");- }- if (currentIncident.acknowledgedAt) {- throw new Error("Incident already acknowledged");- }- await opts.ctx.db- .update(schema.incidentTable)- .set({- acknowledgedAt: new Date(),- acknowledgedBy: opts.ctx.user.id,- updatedAt: new Date(),- })- .where(- and(- eq(schema.incidentTable.id, opts.input.id),- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- ),- );- return true;- }),- resolvedIncident: protectedProcedure- .meta({ track: Events.ResolveIncident })- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const currentIncident = await opts.ctx.db- .select()- .from(schema.incidentTable)- .where(- and(- eq(schema.incidentTable.id, opts.input.id),- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- ),- )- .get();- if (!currentIncident) {- throw new Error("Incident not found");- }- if (!currentIncident.acknowledgedAt) {- throw new Error("Incident not acknowledged");- }- if (currentIncident.resolvedAt) {- throw new Error("Incident already resolved");- }- await opts.ctx.db- .update(schema.incidentTable)- .set({- resolvedAt: new Date(),- resolvedBy: opts.ctx.user.id,- updatedAt: new Date(),- })- .where(- and(- eq(schema.incidentTable.id, opts.input.id),- eq(schema.incidentTable.workspaceId, opts.ctx.workspace.id),- ),- );- return true;- }),-delete: protectedProcedure.meta({ track: Events.DeleteIncident }).input(z.object({ id: z.number() }))@@ -176,8 +35,6 @@ export const incidentRouter = createTRPCRouter({.run();}),- // DASHBOARD-list: protectedProcedure.input(zdiff --git a/packages/api/src/router/invitation.ts b/packages/api/src/router/invitation.tsindex 486113a9a..b80117c00 100644--- a/packages/api/src/router/invitation.ts+++ b/packages/api/src/router/invitation.ts@@ -8,12 +8,11 @@ import {invitation,selectInvitationSchema,selectWorkspaceSchema,- user,usersToWorkspaces,workspace,} from "@openstatus/db/src/schema";-import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";+import { createTRPCRouter, protectedProcedure } from "../trpc";export const invitationRouter = createTRPCRouter({create: protectedProcedure@@ -84,94 +83,6 @@ export const invitationRouter = createTRPCRouter({.run();}),- getWorkspaceOpenInvitations: protectedProcedure.query(async (opts) => {- const _invitations = await opts.ctx.db.query.invitation.findMany({- where: and(- eq(invitation.workspaceId, opts.ctx.workspace.id),- gte(invitation.expiresAt, new Date()),- isNull(invitation.acceptedAt),- ),- });- return _invitations;- }),-- getInvitationByToken: protectedProcedure- .input(z.object({ token: z.string() }))- .query(async (opts) => {- const _invitation = await opts.ctx.db.query.invitation.findFirst({- where: and(eq(invitation.token, opts.input.token)),- with: {- workspace: true,- },- });- return _invitation;- }),-- /**- * REMINDER: we are not using a protected procedure here of the `/invite` url- * instead of `/app/workspace-slug/invite` as the user is not allowed to it yet.- * We validate the auth token in the `acceptInvitation` procedure- */- acceptInvitation: publicProcedure- .input(z.object({ token: z.string() }))- .meta({ track: Events.AcceptInvite })- .output(- z.object({- message: z.string(),- data: selectWorkspaceSchema.optional(),- }),- )- .mutation(async (opts) => {- const _invitation = await opts.ctx.db.query.invitation.findFirst({- where: and(- eq(invitation.token, opts.input.token),- isNull(invitation.acceptedAt),- ),- with: {- workspace: true,- },- });-- if (!opts.ctx.session?.user?.id) return { message: "Missing user." };-- const _user = await opts.ctx.db.query.user.findFirst({- where: eq(user.id, Number(opts.ctx.session.user.id)),- });-- if (!_user) return { message: "Invalid user." };-- if (!_invitation) return { message: "Invalid invitation token." };-- if (_invitation.email !== _user.email)- return { message: "You are not invited to this workspace." };-- if (_invitation.expiresAt.getTime() < new Date().getTime()) {- return { message: "Invitation expired." };- }-- await opts.ctx.db- .update(invitation)- .set({ acceptedAt: new Date() })- .where(eq(invitation.id, _invitation.id))- .run();-- await opts.ctx.db- .insert(usersToWorkspaces)- .values({- userId: _user.id,- workspaceId: _invitation.workspaceId,- role: _invitation.role,- })- .run();-- return {- message: "Invitation accepted.",- data: _invitation.workspace,- };- }),-- // DASHBOARD-list: protectedProcedure.query(async (opts) => {const whereConditions: SQL[] = [eq(invitation.workspaceId, opts.ctx.workspace.id),diff --git a/packages/api/src/router/maintenance.test.ts b/packages/api/src/router/maintenance.test.tsdeleted file mode 100644index 62c85ae1d..000000000--- a/packages/api/src/router/maintenance.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { expect, test } from "bun:test";-import { appRouter } from "../root";-import { createInnerTRPCContext } from "../trpc";--function getTestContext() {- return createInnerTRPCContext({- req: undefined,- session: {- user: {- // @ts-expect-error- id: 1,- },- },- });-}--const from = new Date();-const to = new Date(from.getTime() + 1000 * 60 * 60);--test("Create Maintenance", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMaintenance = await caller.maintenance.new({- title: "Test Maintenance",- message: "This is a test maintenance.",- startDate: from,- endDate: to,- pageId: 1,- });-- expect(createdMaintenance).toMatchObject({- id: expect.any(Number),- title: "Test Maintenance",- message: "This is a test maintenance.",- from,- to,- workspaceId: 1,- });-});--test("Get Maintenance by ID", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMaintenance = await caller.maintenance.new({- title: "Test Maintenance",- message: "This is a test maintenance.",- startDate: from,- endDate: to,- pageId: 1,- });-- const createdMaintenanceId = createdMaintenance.id;-- const fetchedMaintenance = await caller.maintenance.getById({- id: createdMaintenanceId,- });-- expect(fetchedMaintenance).toMatchObject({- id: createdMaintenance.id,- title: "Test Maintenance",- message: "This is a test maintenance.",- from,- to,- workspaceId: 1,- });-});--test("Update Maintenance", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMaintenance = await caller.maintenance.new({- title: "Test Maintenance",- message: "This is a test maintenance.",- startDate: from,- endDate: to,- pageId: 1,- });-- const createdMaintenanceId = createdMaintenance.id;-- await caller.maintenance.update({- id: createdMaintenanceId,- title: "Updated Test Maintenance",- message: "This is an updated test maintenance.",- startDate: from,- endDate: to,- });-- const updatedMaintenance = await caller.maintenance.getById({- id: createdMaintenanceId,- });-- expect(updatedMaintenance).toMatchObject({- id: createdMaintenanceId,- title: "Updated Test Maintenance",- message: "This is an updated test maintenance.",- from,- to,- workspaceId: 1,- });-});--test("Delete Maintenance", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMaintenance = await caller.maintenance.new({- title: "Test Maintenance",- message: "This is a test maintenance.",- startDate: from,- endDate: to,- pageId: 1,- });-- const createdMaintenanceId = createdMaintenance.id;-- const deletedMaintenance = await caller.maintenance.delete({- id: createdMaintenanceId,- });-- expect(deletedMaintenance).toBeDefined();-});diff --git a/packages/api/src/router/maintenance.ts b/packages/api/src/router/maintenance.tsindex 2fe7e137f..33536e5a5 100644--- a/packages/api/src/router/maintenance.ts+++ b/packages/api/src/router/maintenance.ts@@ -8,13 +8,11 @@ import {eq,gte,inArray,- lte,syncMaintenanceToPageComponentDeleteByMaintenance,syncMaintenanceToPageComponentInsertMany,} from "@openstatus/db";import {maintenance,- maintenancesToMonitors,maintenancesToPageComponents,pageComponent,selectMaintenanceSchema,@@ -27,81 +25,6 @@ import { createTRPCRouter, protectedProcedure } from "../trpc";import { getPeriodDate, periods } from "./utils";export const maintenanceRouter = createTRPCRouter({- getById: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _maintenance = await opts.ctx.db- .select()- .from(maintenance)- .where(- and(- eq(maintenance.id, opts.input.id),- eq(maintenance.workspaceId, opts.ctx.workspace.id),- ),- )- .get();-- if (!_maintenance) return undefined;- // TODO: make it work with `with: { maintenacesToMonitors: true }`- const _monitors = await opts.ctx.db- .select()- .from(maintenancesToMonitors)- .where(eq(maintenancesToMonitors.maintenanceId, _maintenance.id))- .all();- return { ..._maintenance, monitors: _monitors.map((m) => m.monitorId) };- }),- getByWorkspace: protectedProcedure.query(async (opts) => {- const _maintenances = await opts.ctx.db- .select()- .from(maintenance)- .where(eq(maintenance.workspaceId, opts.ctx.workspace.id))- .all();- return _maintenances;- }),- getLast7DaysByWorkspace: protectedProcedure.query(async (opts) => {- const _maintenances = await opts.ctx.db.query.maintenance.findMany({- where: and(- eq(maintenance.workspaceId, opts.ctx.workspace.id),- gte(maintenance.from, new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)),- ),- with: { maintenancesToMonitors: true },- });- return _maintenances.map((m) => ({- ...m,- monitors: m.maintenancesToMonitors.map((m) => m.monitorId),- }));- }),- getByPage: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _maintenances = await opts.ctx.db- .select()- .from(maintenance)- .where(- and(- eq(maintenance.pageId, opts.input.id),- eq(maintenance.workspaceId, opts.ctx.workspace.id),- ),- )- .all();- // TODO:- return _maintenances;- }),- getActiveByWorkspace: protectedProcedure.query(async (opts) => {- const _maintenances = await opts.ctx.db- .select()- .from(maintenance)- .where(- and(- eq(maintenance.workspaceId, opts.ctx.workspace.id),- gte(maintenance.to, new Date()),- lte(maintenance.from, new Date()),- ),- )- .all();- return _maintenances;- }),-delete: protectedProcedure.meta({ track: Events.DeleteMaintenance }).input(z.object({ id: z.number() }))@@ -117,8 +40,6 @@ export const maintenanceRouter = createTRPCRouter({.returning();}),- // DASHBOARD-list: protectedProcedure.input(zdiff --git a/packages/api/src/router/monitor.test.ts b/packages/api/src/router/monitor.test.tsdeleted file mode 100644index b54f3c705..000000000--- a/packages/api/src/router/monitor.test.ts+++ /dev/null@@ -1,130 +0,0 @@-import { expect, test } from "bun:test";--import { flyRegions } from "@openstatus/db/src/schema/constants";-import { TRPCError } from "@trpc/server";-import { appRouter } from "../root";-import { createInnerTRPCContext } from "../trpc";--function getTestContext(limits?: unknown) {- return createInnerTRPCContext({- req: undefined,- session: {- user: {- id: "1",- },- },- workspace: {- id: 1,- // @ts-expect-error- limits: limits || {- monitors: 10,- periodicity: ["1m"],- regions: ["fra"],- },- },- });-}--const monitorData = {- name: "Test Monitor",- url: "https://example.com",- jobType: "http" as const,- method: "GET" as const,- periodicity: "1m" as const,- regions: [flyRegions[0]],- statusAssertions: [],- headerAssertions: [],- textBodyAssertions: [],- notifications: [],- pages: [],- tags: [],-};--test("Create Monitor", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMonitor = await caller.monitor.create(monitorData);-- expect(createdMonitor).toMatchObject({- id: expect.any(Number),- name: "Test Monitor",- url: "https://example.com",- workspaceId: 1,- });-});--test("Get Monitor by ID", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMonitor = await caller.monitor.create(monitorData);- const monitorId = createdMonitor.id;-- const fetchedMonitor = await caller.monitor.get({- id: monitorId,- });-- expect(fetchedMonitor).not.toBeNull();- expect(fetchedMonitor).toMatchObject({- id: monitorId,- name: "Test Monitor",- url: "https://example.com",- });-});--test("Update Monitor", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMonitor = await caller.monitor.create(monitorData);- const monitorId = createdMonitor.id;-- await caller.monitor.update({- ...monitorData,- id: monitorId,- name: "Updated Test Monitor",- });-- const updatedMonitor = await caller.monitor.get({- id: monitorId,- });-- expect(updatedMonitor).not.toBeNull();- expect(updatedMonitor?.name).toBe("Updated Test Monitor");-});--test("Delete Monitor", async () => {- const ctx = getTestContext();- const caller = appRouter.createCaller(ctx);-- const createdMonitor = await caller.monitor.create(monitorData);- const monitorId = createdMonitor.id;-- await caller.monitor.delete({- id: monitorId,- });-- const fetchedMonitor = await caller.monitor.get({- id: monitorId,- });- expect(fetchedMonitor).toBeNull();-});--test.todo("Monitor Limit Reached", async () => {- const ctx = getTestContext();- // @ts-expect-error- ctx.workspace.limits.monitors = 1;- const caller = appRouter.createCaller(ctx);-- await caller.monitor.create(monitorData);-- await caller.monitor.create(monitorData);-- await expect(await caller.monitor.create(monitorData)).rejects.toThrow(- new TRPCError({- code: "FORBIDDEN",- message: "You reached your monitor limits.",- }),- );-});diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.tsindex 73b53d6b7..292ed1943 100644--- a/packages/api/src/router/monitor.ts+++ b/packages/api/src/router/monitor.ts@@ -21,7 +21,6 @@ import {eq,inArray,isNull,- sql,syncMaintenanceToMonitorDeleteByMonitors,syncMonitorsToPageDelete,syncMonitorsToPageDeleteByMonitors,@@ -49,7 +48,6 @@ import {selectNotificationSchema,selectPageSchema,selectPrivateLocationSchema,- selectPublicMonitorSchema,} from "@openstatus/db/src/schema";import { Events } from "@openstatus/analytics";@@ -59,526 +57,10 @@ import {monitorRegions,} from "@openstatus/db/src/schema/constants";import { regionDict } from "@openstatus/regions";-import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";+import { createTRPCRouter, protectedProcedure } from "../trpc";import { testDns, testHttp, testTcp } from "./checker";export const monitorRouter = createTRPCRouter({- create: protectedProcedure- .meta({ track: Events.CreateMonitor, trackProps: ["url", "jobType"] })- .input(insertMonitorSchema)- .output(selectMonitorSchema)- .mutation(async (opts) => {- const monitorLimit = opts.ctx.workspace.limits.monitors;- const periodicityLimit = opts.ctx.workspace.limits.periodicity;- const regionsLimit = opts.ctx.workspace.limits.regions;-- const monitorNumbers = (- await opts.ctx.db.query.monitor.findMany({- where: and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- })- ).length;-- // the user has reached the limits- if (monitorNumbers >= monitorLimit) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You reached your monitor limits.",- });- }-- // the user is not allowed to use the cron job- if (- opts.input.periodicity &&- !periodicityLimit.includes(opts.input.periodicity)- ) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You reached your cron job limits.",- });- }-- if (- opts.input.regions !== undefined &&- opts.input.regions?.length !== 0- ) {- for (const region of opts.input.regions) {- if (!regionsLimit.includes(region)) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You don't have access to this region.",- });- }- }- }-- // FIXME: this is a hotfix- const {- regions,- headers,- notifications,- pages,- tags,- statusAssertions,- headerAssertions,- textBodyAssertions,- otelHeaders,- ...data- } = opts.input;-- const assertions: Assertion[] = [];- for (const a of statusAssertions ?? []) {- assertions.push(new StatusAssertion(a));- }- for (const a of headerAssertions ?? []) {- assertions.push(new HeaderAssertion(a));- }- for (const a of textBodyAssertions ?? []) {- assertions.push(new TextBodyAssertion(a));- }-- const newMonitor = await opts.ctx.db- .insert(monitor)- .values({- // REMINDER: We should explicitly pass the corresponding attributes- // otherwise, unexpected attributes will be passed- ...data,- workspaceId: opts.ctx.workspace.id,- regions: regions?.join(","),- headers: headers ? JSON.stringify(headers) : undefined,- otelHeaders: otelHeaders ? JSON.stringify(otelHeaders) : undefined,- assertions: assertions.length > 0 ? serialize(assertions) : undefined,- })- .returning()- .get();-- if (notifications.length > 0) {- const allNotifications = await opts.ctx.db.query.notification.findMany({- where: and(- eq(notification.workspaceId, opts.ctx.workspace.id),- inArray(notification.id, notifications),- ),- });-- const values = allNotifications.map((notification) => ({- monitorId: newMonitor.id,- notificationId: notification.id,- }));-- await opts.ctx.db.insert(notificationsToMonitors).values(values).run();- }-- if (tags.length > 0) {- const allTags = await opts.ctx.db.query.monitorTag.findMany({- where: and(- eq(monitorTag.workspaceId, opts.ctx.workspace.id),- inArray(monitorTag.id, tags),- ),- });-- const values = allTags.map((monitorTag) => ({- monitorId: newMonitor.id,- monitorTagId: monitorTag.id,- }));-- await opts.ctx.db.insert(monitorTagsToMonitors).values(values).run();- }-- if (pages.length > 0) {- const allPages = await opts.ctx.db.query.page.findMany({- where: and(- eq(page.workspaceId, opts.ctx.workspace.id),- inArray(page.id, pages),- ),- });-- const values = allPages.map((page) => ({- monitorId: newMonitor.id,- pageId: page.id,- }));-- await opts.ctx.db.insert(monitorsToPages).values(values).run();- // Sync to page components- await syncMonitorsToPageInsertMany(opts.ctx.db, values);- }-- return selectMonitorSchema.parse(newMonitor);- }),-- getMonitorById: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _monitor = await opts.ctx.db.query.monitor.findFirst({- where: and(- eq(monitor.id, opts.input.id),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- with: {- monitorTagsToMonitors: { with: { monitorTag: true } },- maintenancesToMonitors: {- with: { maintenance: true },- where: eq(maintenancesToMonitors.monitorId, opts.input.id),- },- monitorsToNotifications: { with: { notification: true } },- },- });-- const parsedMonitor = selectMonitorSchema- .extend({- monitorTagsToMonitors: z- .object({- monitorTag: selectMonitorTagSchema,- })- .array(),- maintenance: z.boolean().prefault(false).optional(),- monitorsToNotifications: z- .object({- notification: selectNotificationSchema,- })- .array(),- })- .safeParse({- ..._monitor,- maintenance: _monitor?.maintenancesToMonitors.some(- (item) =>- item.maintenance.from.getTime() <= Date.now() &&- item.maintenance.to.getTime() >= Date.now(),- ),- });-- if (!parsedMonitor.success) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "You are not allowed to access the monitor.",- });- }- return parsedMonitor.data;- }),-- getPublicMonitorById: publicProcedure- // REMINDER: if on status page, we should check if the monitor is associated with the page- // otherwise, using `/public` we don't need to check- .input(z.object({ id: z.number(), slug: z.string().optional() }))- .query(async (opts) => {- const _monitor = await opts.ctx.db- .select()- .from(monitor)- .where(- and(- eq(monitor.id, opts.input.id),- isNull(monitor.deletedAt),- eq(monitor.public, true),- ),- )- .get();-- if (!_monitor) return undefined;-- if (opts.input.slug) {- const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,- with: { monitorsToPages: true },- });-- const hasPageRelation = _page?.monitorsToPages.find(- ({ monitorId }) => _monitor.id === monitorId,- );-- if (!hasPageRelation) return undefined;- }-- return selectPublicMonitorSchema.parse(_monitor);- }),-- update: protectedProcedure- .meta({ track: Events.UpdateMonitor })- .input(insertMonitorSchema)- .mutation(async (opts) => {- if (!opts.input.id) return;-- const periodicityLimit = opts.ctx.workspace.limits.periodicity;-- const regionsLimit = opts.ctx.workspace.limits.regions;-- // the user is not allowed to use the cron job- if (- opts.input?.periodicity &&- !periodicityLimit.includes(opts.input?.periodicity)- ) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You reached your cron job limits.",- });- }-- if (- opts.input.regions !== undefined &&- opts.input.regions?.length !== 0- ) {- for (const region of opts.input.regions) {- if (!regionsLimit.includes(region)) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You don't have access to this region.",- });- }- }- }-- const {- regions,- headers,- notifications,- pages,- tags,- statusAssertions,- headerAssertions,- textBodyAssertions,- otelHeaders,-- ...data- } = opts.input;-- const assertions: Assertion[] = [];- for (const a of statusAssertions ?? []) {- assertions.push(new StatusAssertion(a));- }- for (const a of headerAssertions ?? []) {- assertions.push(new HeaderAssertion(a));- }- for (const a of textBodyAssertions ?? []) {- assertions.push(new TextBodyAssertion(a));- }-- const currentMonitor = await opts.ctx.db- .update(monitor)- .set({- ...data,- regions: regions?.join(","),- updatedAt: new Date(),- headers: headers ? JSON.stringify(headers) : undefined,- otelHeaders: otelHeaders ? JSON.stringify(otelHeaders) : undefined,- assertions: serialize(assertions),- })- .where(- and(- eq(monitor.id, opts.input.id),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- )- .returning()- .get();-- console.log({- currentMonitor,- id: opts.input.id,- workspaceId: opts.ctx.workspace.id,- });-- const currentMonitorNotifications = await opts.ctx.db- .select()- .from(notificationsToMonitors)- .where(eq(notificationsToMonitors.monitorId, currentMonitor.id))- .all();-- const addedNotifications = notifications.filter(- (x) =>- !currentMonitorNotifications- .map(({ notificationId }) => notificationId)- ?.includes(x),- );-- if (addedNotifications.length > 0) {- const values = addedNotifications.map((notificationId) => ({- monitorId: currentMonitor.id,- notificationId,- }));-- await opts.ctx.db.insert(notificationsToMonitors).values(values).run();- }-- const removedNotifications = currentMonitorNotifications- .map(({ notificationId }) => notificationId)- .filter((x) => !notifications?.includes(x));-- if (removedNotifications.length > 0) {- await opts.ctx.db- .delete(notificationsToMonitors)- .where(- and(- eq(notificationsToMonitors.monitorId, currentMonitor.id),- inArray(- notificationsToMonitors.notificationId,- removedNotifications,- ),- ),- )- .run();- }-- const currentMonitorTags = await opts.ctx.db- .select()- .from(monitorTagsToMonitors)- .where(eq(monitorTagsToMonitors.monitorId, currentMonitor.id))- .all();-- const addedTags = tags.filter(- (x) =>- !currentMonitorTags- .map(({ monitorTagId }) => monitorTagId)- ?.includes(x),- );-- if (addedTags.length > 0) {- const values = addedTags.map((monitorTagId) => ({- monitorId: currentMonitor.id,- monitorTagId,- }));-- await opts.ctx.db.insert(monitorTagsToMonitors).values(values).run();- }-- const removedTags = currentMonitorTags- .map(({ monitorTagId }) => monitorTagId)- .filter((x) => !tags?.includes(x));-- if (removedTags.length > 0) {- await opts.ctx.db- .delete(monitorTagsToMonitors)- .where(- and(- eq(monitorTagsToMonitors.monitorId, currentMonitor.id),- inArray(monitorTagsToMonitors.monitorTagId, removedTags),- ),- )- .run();- }-- const currentMonitorPages = await opts.ctx.db- .select()- .from(monitorsToPages)- .where(eq(monitorsToPages.monitorId, currentMonitor.id))- .all();-- const addedPages = pages.filter(- (x) => !currentMonitorPages.map(({ pageId }) => pageId)?.includes(x),- );-- if (addedPages.length > 0) {- const values = addedPages.map((pageId) => ({- monitorId: currentMonitor.id,- pageId,- }));-- await opts.ctx.db.insert(monitorsToPages).values(values).run();- // Sync to page components- await syncMonitorsToPageInsertMany(opts.ctx.db, values);- }-- const removedPages = currentMonitorPages- .map(({ pageId }) => pageId)- .filter((x) => !pages?.includes(x));-- if (removedPages.length > 0) {- await opts.ctx.db- .delete(monitorsToPages)- .where(- and(- eq(monitorsToPages.monitorId, currentMonitor.id),- inArray(monitorsToPages.pageId, removedPages),- ),- )- .run();- // Sync delete to page components- for (const pageId of removedPages) {- await syncMonitorsToPageDelete(opts.ctx.db, {- monitorId: currentMonitor.id,- pageId,- });- }- }- }),-- updateMonitors: protectedProcedure- .input(- insertMonitorSchema- .pick({ public: true, active: true })- .partial() // batched updates- .extend({ ids: z.number().array() }), // array of monitor ids to update- )- .mutation(async (opts) => {- const _monitors = await opts.ctx.db- .update(monitor)- .set(opts.input)- .where(- and(- inArray(monitor.id, opts.input.ids),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- );- }),-- updateMonitorsTag: protectedProcedure- .input(- z.object({- ids: z.number().array(),- tagId: z.number(),- action: z.enum(["add", "remove"]),- }),- )- .mutation(async (opts) => {- const _monitorTag = await opts.ctx.db.query.monitorTag.findFirst({- where: and(- eq(monitorTag.workspaceId, opts.ctx.workspace.id),- eq(monitorTag.id, opts.input.tagId),- ),- });-- const _monitors = await opts.ctx.db.query.monitor.findMany({- where: and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- inArray(monitor.id, opts.input.ids),- ),- });-- if (!_monitorTag || _monitors.length !== opts.input.ids.length) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid tag",- });- }-- if (opts.input.action === "add") {- await opts.ctx.db- .insert(monitorTagsToMonitors)- .values(- opts.input.ids.map((id) => ({- monitorId: id,- monitorTagId: opts.input.tagId,- })),- )- .onConflictDoNothing()- .run();- }-- if (opts.input.action === "remove") {- await opts.ctx.db- .delete(monitorTagsToMonitors)- .where(- and(- inArray(monitorTagsToMonitors.monitorId, opts.input.ids),- eq(monitorTagsToMonitors.monitorTagId, opts.input.tagId),- ),- )- .run();- }- }),-delete: protectedProcedure.meta({ track: Events.DeleteMonitor }).input(z.object({ id: z.number() }))@@ -678,184 +160,26 @@ export const monitorRouter = createTRPCRouter({});}),- getMonitorsByWorkspace: protectedProcedure.query(async (opts) => {- const monitors = await opts.ctx.db.query.monitor.findMany({- where: and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- with: {- monitorTagsToMonitors: { with: { monitorTag: true } },- },- orderBy: (monitor, { desc }) => [desc(monitor.active)],- });-- return z- .array(- selectMonitorSchema.extend({- monitorTagsToMonitors: z- .array(z.object({ monitorTag: selectMonitorTagSchema }))- .prefault([]),- }),- )- .parse(monitors);- }),-- getMonitorsByPageId: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _page = await opts.ctx.db.query.page.findFirst({- where: and(- eq(page.id, opts.input.id),- eq(page.workspaceId, opts.ctx.workspace.id),- ),- });-- if (!_page) return undefined;-- const monitors = await opts.ctx.db.query.monitor.findMany({- where: and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- with: {- monitorTagsToMonitors: { with: { monitorTag: true } },- monitorsToPages: {- where: eq(monitorsToPages.pageId, _page.id),- },- },- });-- return z- .array(- selectMonitorSchema.extend({- monitorTagsToMonitors: z- .array(z.object({ monitorTag: selectMonitorTagSchema }))- .prefault([]),- }),- )- .parse(- monitors.filter((monitor) =>- monitor.monitorsToPages- .map(({ pageId }) => pageId)- .includes(_page.id),- ),- );- }),-- toggleMonitorActive: protectedProcedure- .input(z.object({ id: z.number() }))+ updateMonitors: protectedProcedure+ .input(+ insertMonitorSchema+ .pick({ public: true, active: true })+ .partial() // batched updates+ .extend({ ids: z.number().array() }), // array of monitor ids to update+ ).mutation(async (opts) => {- const monitorToUpdate = await opts.ctx.db- .select()- .from(monitor)- .where(- and(- eq(monitor.id, opts.input.id),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- )- .get();-- if (!monitorToUpdate) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Monitor not found.",- });- }-await opts.ctx.db.update(monitor)- .set({- active: !monitorToUpdate.active,- })+ .set(opts.input).where(and(- eq(monitor.id, opts.input.id),+ inArray(monitor.id, opts.input.ids),eq(monitor.workspaceId, opts.ctx.workspace.id),+ isNull(monitor.deletedAt),),- )- .run();- }),-- // rename to getActiveMonitorsCount- getTotalActiveMonitors: publicProcedure.query(async (opts) => {- const monitors = await opts.ctx.db- .select({ count: sql<number>`count(*)` })- .from(monitor)- .where(eq(monitor.active, true))- .all();- if (monitors.length === 0) return 0;- return monitors[0].count;- }),-- // TODO: return the notifications inside of the `getMonitorById` like we do for the monitors on a status page- getAllNotificationsForMonitor: protectedProcedure- .input(z.object({ id: z.number() }))- // .output(selectMonitorSchema)- .query(async (opts) => {- const data = await opts.ctx.db- .select()- .from(notificationsToMonitors)- .innerJoin(- notification,- and(- eq(notificationsToMonitors.notificationId, notification.id),- eq(notification.workspaceId, opts.ctx.workspace.id),- ),- )- .where(eq(notificationsToMonitors.monitorId, opts.input.id))- .all();- return data.map((d) => selectNotificationSchema.parse(d.notification));- }),-- isMonitorLimitReached: protectedProcedure.query(async (opts) => {- const monitorLimit = opts.ctx.workspace.limits.monitors;- const monitorNumbers = (- await opts.ctx.db.query.monitor.findMany({- where: and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- })- ).length;-- return monitorNumbers >= monitorLimit;- }),- getMonitorRelationsById: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _monitor = await opts.ctx.db.query.monitor.findFirst({- where: and(- eq(monitor.id, opts.input.id),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- with: {- monitorTagsToMonitors: true,- monitorsToNotifications: true,- monitorsToPages: true,- },- });-- const parsedMonitorNotification = _monitor?.monitorsToNotifications.map(- ({ notificationId }) => notificationId,- );- const parsedPages = _monitor?.monitorsToPages.map((val) => val.pageId);- const parsedTags = _monitor?.monitorTagsToMonitors.map(- ({ monitorTagId }) => monitorTagId,- );-- return {- notificationIds: parsedMonitorNotification,- pageIds: parsedPages,- monitorTagIds: parsedTags,- };+ );}),- // DASHBOARD-list: protectedProcedure.input(zdiff --git a/packages/api/src/router/monitorTag.ts b/packages/api/src/router/monitorTag.tsindex 2abeb5ce4..702462675 100644--- a/packages/api/src/router/monitorTag.ts+++ b/packages/api/src/router/monitorTag.ts@@ -1,7 +1,7 @@import { z } from "zod";import { and, eq, inArray } from "@openstatus/db";-import { insertMonitorTagSchema, monitorTag } from "@openstatus/db/src/schema";+import { monitorTag } from "@openstatus/db/src/schema";import { createTRPCRouter, protectedProcedure } from "../trpc";@@ -12,64 +12,6 @@ const tagSchema = z.object({});export const monitorTagRouter = createTRPCRouter({- getMonitorTagsByWorkspace: protectedProcedure.query(async (opts) => {- return opts.ctx.db.query.monitorTag.findMany({- where: eq(monitorTag.workspaceId, opts.ctx.workspace.id),- with: { monitor: true },- });- }),-- update: protectedProcedure- .input(insertMonitorTagSchema)- .mutation(async (opts) => {- if (!opts.input.id) return;- return await opts.ctx.db- .update(monitorTag)- .set({- name: opts.input.name,- color: opts.input.color,- updatedAt: new Date(),- })- .where(- and(- eq(monitorTag.workspaceId, opts.ctx.workspace.id),- eq(monitorTag.id, opts.input.id),- ),- )- .returning()- .get();- }),-- delete: protectedProcedure- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- await opts.ctx.db- .delete(monitorTag)- .where(- and(- eq(monitorTag.id, opts.input.id),- eq(monitorTag.workspaceId, opts.ctx.workspace.id),- ),- )- .run();- }),-- create: protectedProcedure- .input(z.object({ name: z.string(), color: z.string() }))- .mutation(async (opts) => {- return opts.ctx.db- .insert(monitorTag)- .values({- name: opts.input.name,- color: opts.input.color,- workspaceId: opts.ctx.workspace.id,- })- .returning()- .get();- }),-- // DASHBOARD-list: protectedProcedure.query(async (opts) => {return opts.ctx.db.query.monitorTag.findMany({where: eq(monitorTag.workspaceId, opts.ctx.workspace.id),diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 74f5f66a9..63b52c819 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -6,10 +6,8 @@ import {and,desc,eq,- gte,inArray,isNull,- lte,sql,syncMonitorGroupDeleteMany,syncMonitorGroupInsert,@@ -32,7 +30,6 @@ import {selectMonitorSchema,selectPageComponentSchema,selectPageSchema,- selectPageSchemaWithMonitorsRelation,statusReport,subdomainSafeList,workspace,@@ -154,128 +151,7 @@ export const pageRouter = createTRPCRouter({return newPage;}),- getPageById: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const firstPage = await opts.ctx.db.query.page.findFirst({- where: and(- eq(page.id, opts.input.id),- eq(page.workspaceId, opts.ctx.workspace.id),- ),- with: {- monitorsToPages: {- with: { monitor: true },- orderBy: (monitorsToPages, { asc }) => [asc(monitorsToPages.order)],- },- },- });- return selectPageSchemaWithMonitorsRelation.parse(firstPage);- }),-- update: protectedProcedure- .meta({ track: Events.UpdatePage })- .input(insertPageSchema)- .mutation(async (opts) => {- const { monitors, ...pageInput } = opts.input;- if (!pageInput.id) return;-- const monitorIds = monitors?.map((item) => item.monitorId) || [];-- const limit = opts.ctx.workspace.limits;-- // the user is not eligible for password protection- if (- limit["password-protection"] === false &&- opts.input.passwordProtected === true- ) {- throw new TRPCError({- code: "FORBIDDEN",- message:- "Password protection is not available for your current plan.",- });- }-- const currentPage = await opts.ctx.db- .update(page)- .set({- ...pageInput,- updatedAt: new Date(),- authEmailDomains: pageInput.authEmailDomains?.join(","),- })- .where(- and(- eq(page.id, pageInput.id),- eq(page.workspaceId, opts.ctx.workspace.id),- ),- )- .returning()- .get();-- if (monitorIds.length) {- // We should make sure the user has access to the monitors- const allMonitors = await opts.ctx.db.query.monitor.findMany({- where: and(- inArray(monitor.id, monitorIds),- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- });- if (allMonitors.length !== monitorIds.length) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You don't have access to all the monitors.",- });- }- }-- // TODO: check for monitor order!- const currentMonitorsToPages = await opts.ctx.db- .select()- .from(monitorsToPages)- .where(eq(monitorsToPages.pageId, currentPage.id))- .all();-- const removedMonitors = currentMonitorsToPages- .map(({ monitorId }) => monitorId)- .filter((x) => !monitorIds?.includes(x));-- if (removedMonitors.length) {- await opts.ctx.db- .delete(monitorsToPages)- .where(- and(- inArray(monitorsToPages.monitorId, removedMonitors),- eq(monitorsToPages.pageId, currentPage.id),- ),- );- // Sync delete to page components- for (const monitorId of removedMonitors) {- await syncMonitorsToPageDelete(opts.ctx.db, {- monitorId,- pageId: currentPage.id,- });- }- }-- const values = monitors.map(({ monitorId }, index) => ({- pageId: currentPage.id,- order: index,- monitorId,- }));-- if (values.length) {- await opts.ctx.db- .insert(monitorsToPages)- .values(values)- .onConflictDoUpdate({- target: [monitorsToPages.monitorId, monitorsToPages.pageId],- set: { order: sql.raw("excluded.`order`") },- });- // Sync new monitors to page components (existing ones will be ignored due to onConflictDoNothing)- await syncMonitorsToPageInsertMany(opts.ctx.db, values);- }- }),delete: protectedProcedure.meta({ track: Events.DeletePage }).input(z.object({ id: z.number() }))@@ -290,31 +166,6 @@ export const pageRouter = createTRPCRouter({.where(and(...whereConditions)).run();}),-- getPagesByWorkspace: protectedProcedure.query(async (opts) => {- const allPages = await opts.ctx.db.query.page.findMany({- where: and(eq(page.workspaceId, opts.ctx.workspace.id)),- with: {- monitorsToPages: { with: { monitor: true } },- maintenances: {- where: and(- lte(maintenance.from, new Date()),- gte(maintenance.to, new Date()),- ),- },- statusReports: {- orderBy: (reports, { desc }) => desc(reports.updatedAt),- with: {- statusReportUpdates: {- orderBy: (updates, { desc }) => desc(updates.date),- },- },- },- },- });- return z.array(selectPageSchemaWithMonitorsRelation).parse(allPages);- }),-// public if we use trpc hooks to get the page from the urlgetPageBySlug: publicProcedure.input(z.object({ slug: z.string().toLowerCase() }))@@ -460,19 +311,6 @@ export const pageRouter = createTRPCRouter({.get();}),- isPageLimitReached: protectedProcedure.query(async (opts) => {- const pageLimit = opts.ctx.workspace.limits["status-pages"];- const pageNumbers = (- await opts.ctx.db.query.page.findMany({- where: eq(monitor.workspaceId, opts.ctx.workspace.id),- })- ).length;-- return pageNumbers >= pageLimit;- }),-- // DASHBOARD-list: protectedProcedure.input(zdiff --git a/packages/api/src/router/pageSubscriber.ts b/packages/api/src/router/pageSubscriber.tsindex cf5fb92f7..7549de442 100644--- a/packages/api/src/router/pageSubscriber.ts+++ b/packages/api/src/router/pageSubscriber.ts@@ -1,109 +1,11 @@-import { TRPCError } from "@trpc/server";-import { z } from "zod";--import { Events } from "@openstatus/analytics";import { and, eq } from "@openstatus/db";import { page, pageSubscriber } from "@openstatus/db/src/schema";+import { TRPCError } from "@trpc/server";+import { z } from "zod";import { createTRPCRouter, protectedProcedure } from "../trpc";export const pageSubscriberRouter = createTRPCRouter({- getPageSubscribersByPageId: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const _page = await opts.ctx.db.query.page.findFirst({- where: and(- eq(page.workspaceId, opts.ctx.workspace.id),- eq(page.id, opts.input.id),- ),- });-- if (!_page) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Unauthorized to get subscribers",- });- }-- const data = await opts.ctx.db.query.pageSubscriber.findMany({- where: and(eq(pageSubscriber.pageId, _page.id)),- });- return data;- }),-- unsubscribeById: protectedProcedure- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const subscriber = await opts.ctx.db.query.pageSubscriber.findFirst({- where: and(eq(pageSubscriber.id, opts.input.id)),- });-- if (!subscriber) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Subscriber not found",- });- }-- const _page = await opts.ctx.db.query.page.findFirst({- where: and(- eq(page.id, subscriber.pageId),- eq(page.workspaceId, opts.ctx.workspace.id),- ),- });-- if (!_page) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Unauthorized to unsubscribe",- });- }-- return await opts.ctx.db- .delete(pageSubscriber)- .where(eq(pageSubscriber.id, subscriber.id));- }),-- acceptSubscriberById: protectedProcedure- .meta({ track: Events.SubscribePage })- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const subscriber = await opts.ctx.db.query.pageSubscriber.findFirst({- where: and(eq(pageSubscriber.id, opts.input.id)),- });-- if (!subscriber) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Subscriber not found",- });- }-- const _page = await opts.ctx.db.query.page.findFirst({- where: and(- eq(page.id, subscriber.pageId),- eq(page.workspaceId, opts.ctx.workspace.id),- ),- });-- if (!_page) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Unauthorized to unsubscribe",- });- }-- return await opts.ctx.db- .update(pageSubscriber)- .set({- acceptedAt: new Date(),- updatedAt: new Date(),- })- .where(eq(pageSubscriber.id, subscriber.id));- }),-- // DASHBOARD-list: protectedProcedure.input(z.object({diff --git a/packages/api/src/router/statusPage.e2e.test.ts b/packages/api/src/router/statusPage.e2e.test.tsindex efd38857d..01b0c6982 100644--- a/packages/api/src/router/statusPage.e2e.test.ts+++ b/packages/api/src/router/statusPage.e2e.test.ts@@ -332,7 +332,6 @@ describe("Clicking confirm sets unsubscribedAt timestamp", () => {});describe("Unsubscribed user does not receive new emails", () => {- let _activeToken: string;let unsubscribedToken: string;let pendingToken: string;@@ -366,8 +365,6 @@ describe("Unsubscribed user does not receive new emails", () => {throw new Error("Active subscriber token is undefined");}- _activeToken = active.token;-// Unsubscribed subscriberconst unsubscribed = await db.insert(pageSubscriber)diff --git a/packages/api/src/router/statusPage.unsubscribe.test.ts b/packages/api/src/router/statusPage.unsubscribe.test.tsindex bf111bd07..9800d3fc4 100644--- a/packages/api/src/router/statusPage.unsubscribe.test.ts+++ b/packages/api/src/router/statusPage.unsubscribe.test.ts@@ -5,7 +5,6 @@ import { page, pageSubscriber } from "@openstatus/db/src/schema";// Test data setuplet testPageId: number;-let _testSubscriberId: number;let testToken: string;const testWorkspaceId = 1; // Use existing test workspace from seed data@@ -42,7 +41,7 @@ beforeAll(async () => {// Create a verified subscriber for testingtestToken = crypto.randomUUID();- const subscriber = await db+ await db.insert(pageSubscriber).values({pageId: testPageId,@@ -53,8 +52,6 @@ beforeAll(async () => {}).returning().get();-- _testSubscriberId = subscriber.id;});afterAll(async () => {@@ -86,11 +83,14 @@ describe("getSubscriberByToken", () => {// Manually mask the email to test the masking logicconst email = subscriber?.email;- const [localPart, domain] = email.split("@");- const maskedEmail =- localPart.length > 0 ? `${localPart[0]}***@${domain}` : `***@${domain}`;+ expect(email).toBeDefined();+ if (email) {+ const [localPart, domain] = email.split("@");+ const maskedEmail =+ localPart.length > 0 ? `${localPart[0]}***@${domain}` : `***@${domain}`;- expect(maskedEmail).toBe("t***@example.com");+ expect(maskedEmail).toBe("t***@example.com");+ }});test("should return null for non-existent token", async () => {diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.tsindex 3becd0fef..aa1488eab 100644--- a/packages/api/src/router/statusReport.ts+++ b/packages/api/src/router/statusReport.ts@@ -7,74 +7,28 @@ import {desc,eq,gte,- inArray,- sql,- syncStatusReportToMonitorDelete,- syncStatusReportToMonitorInsertMany,syncStatusReportToPageComponentDeleteByStatusReport,syncStatusReportToPageComponentInsertMany,} from "@openstatus/db";import {- insertStatusReportSchema,insertStatusReportUpdateSchema,- monitorsToStatusReport,- page,selectMonitorSchema,selectPageComponentSchema,selectPageSchema,- selectPublicStatusReportSchemaWithRelation,selectStatusReportSchema,selectStatusReportUpdateSchema,statusReport,statusReportStatus,- statusReportStatusSchema,statusReportUpdate,statusReportsToPageComponents,} from "@openstatus/db/src/schema";import { Events } from "@openstatus/analytics";import { TRPCError } from "@trpc/server";-import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";+import { createTRPCRouter, protectedProcedure } from "../trpc";import { getPeriodDate, periods } from "./utils";export const statusReportRouter = createTRPCRouter({- createStatusReport: protectedProcedure- .meta({ track: Events.CreateReport })- .input(insertStatusReportSchema)- .mutation(async (opts) => {- const { id, monitors, date, message, ...statusReportInput } = opts.input;-- const newStatusReport = await opts.ctx.db- .insert(statusReport)- .values({- workspaceId: opts.ctx.workspace.id,- ...statusReportInput,- })- .returning()- .get();-- if (monitors.length > 0) {- await opts.ctx.db- .insert(monitorsToStatusReport)- .values(- monitors.map((monitor) => ({- monitorId: monitor,- statusReportId: newStatusReport.id,- })),- )- .returning()- .get();- // Sync to page components- await syncStatusReportToMonitorInsertMany(- opts.ctx.db,- newStatusReport.id,- monitors,- );- }-- return newStatusReport;- }),-createStatusReportUpdate: protectedProcedure.meta({ track: Events.CreateReportUpdate }).input(@@ -112,84 +66,6 @@ export const statusReportRouter = createTRPCRouter({};}),- updateStatusReport: protectedProcedure- .meta({ track: Events.UpdateReport })- .input(insertStatusReportSchema)- .mutation(async (opts) => {- const { monitors, ...statusReportInput } = opts.input;-- if (!statusReportInput.id) return;-- const { title, status } = statusReportInput;-- const currentStatusReport = await opts.ctx.db- .update(statusReport)- .set({ title, status, updatedAt: new Date() })- .where(- and(- eq(statusReport.id, statusReportInput.id),- eq(statusReport.workspaceId, opts.ctx.workspace.id),- ),- )- .returning()- .get();-- const currentMonitorsToStatusReport = await opts.ctx.db- .select()- .from(monitorsToStatusReport)- .where(- eq(monitorsToStatusReport.statusReportId, currentStatusReport.id),- )- .all();-- const addedMonitors = monitors.filter(- (x) =>- !currentMonitorsToStatusReport- .map(({ monitorId }) => monitorId)- .includes(x),- );-- if (addedMonitors.length) {- const values = addedMonitors.map((monitorId) => ({- monitorId: monitorId,- statusReportId: currentStatusReport.id,- }));-- await opts.ctx.db.insert(monitorsToStatusReport).values(values).run();- // Sync to page components- await syncStatusReportToMonitorInsertMany(- opts.ctx.db,- currentStatusReport.id,- addedMonitors,- );- }-- const removedMonitors = currentMonitorsToStatusReport- .map(({ monitorId }) => monitorId)- .filter((x) => !monitors?.includes(x));-- if (removedMonitors.length) {- await opts.ctx.db- .delete(monitorsToStatusReport)- .where(- and(- eq(monitorsToStatusReport.statusReportId, currentStatusReport.id),- inArray(monitorsToStatusReport.monitorId, removedMonitors),- ),- )- .run();- // Sync delete to page components for each removed monitor- for (const monitorId of removedMonitors) {- await syncStatusReportToMonitorDelete(opts.ctx.db, {- statusReportId: currentStatusReport.id,- monitorId,- });- }- }-- return currentStatusReport;- }),-updateStatusReportUpdate: protectedProcedure.meta({ track: Events.UpdateReportUpdate }).input(insertStatusReportUpdateSchema)@@ -208,193 +84,6 @@ export const statusReportRouter = createTRPCRouter({return selectStatusReportUpdateSchema.parse(currentStatusReportUpdate);}),- deleteStatusReport: protectedProcedure- .meta({ track: Events.DeleteReport })- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const statusReportToDelete = await opts.ctx.db- .select()- .from(statusReport)- .where(- and(- eq(statusReport.id, opts.input.id),- eq(statusReport.workspaceId, opts.ctx.workspace.id),- ),- )- .get();- if (!statusReportToDelete) return;-- await opts.ctx.db- .delete(statusReport)- .where(eq(statusReport.id, statusReportToDelete.id))- .run();- }),-- deleteStatusReportUpdate: protectedProcedure- .meta({ track: Events.DeleteReportUpdate })- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const statusReportUpdateToDelete = await opts.ctx.db- .select()- .from(statusReportUpdate)- .where(and(eq(statusReportUpdate.id, opts.input.id)))- .get();-- if (!statusReportUpdateToDelete) return;-- await opts.ctx.db- .delete(statusReportUpdate)- .where(eq(statusReportUpdate.id, opts.input.id))- .run();- }),-- getStatusReportById: protectedProcedure- .input(z.object({ id: z.number(), pageId: z.number().optional() }))- .query(async (opts) => {- const selectPublicStatusReportSchemaWithRelation =- selectStatusReportSchema.extend({- status: statusReportStatusSchema.prefault("investigating"), // TODO: remove!- monitorsToStatusReports: z- .array(- z.object({- statusReportId: z.number(),- monitorId: z.number(),- monitor: selectMonitorSchema,- }),- )- .prefault([]),- statusReportUpdates: z.array(selectStatusReportUpdateSchema),- date: z.date().prefault(new Date()),- });-- const data = await opts.ctx.db.query.statusReport.findFirst({- where: and(- eq(statusReport.id, opts.input.id),- eq(statusReport.workspaceId, opts.ctx.workspace.id),- // only allow to fetch status report if it belongs to the page- opts.input.pageId- ? eq(statusReport.pageId, opts.input.pageId)- : undefined,- ),- with: {- monitorsToStatusReports: { with: { monitor: true } },- statusReportUpdates: {- orderBy: (statusReportUpdate, { desc }) => [- desc(statusReportUpdate.createdAt),- ],- },- },- });-- return selectPublicStatusReportSchemaWithRelation.parse(data);- }),-- getStatusReportUpdateById: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- const data = await opts.ctx.db.query.statusReportUpdate.findFirst({- where: and(eq(statusReportUpdate.id, opts.input.id)),- });- return selectStatusReportUpdateSchema.parse(data);- }),-- getStatusReportByWorkspace: protectedProcedure.query(async (opts) => {- // FIXME: can we get rid of that?- const selectStatusSchemaWithRelation = selectStatusReportSchema.extend({- status: statusReportStatusSchema.prefault("investigating"), // TODO: remove!- monitorsToStatusReports: z- .array(- z.object({- statusReportId: z.number(),- monitorId: z.number(),- monitor: selectMonitorSchema,- }),- )- .prefault([]),- statusReportUpdates: z.array(selectStatusReportUpdateSchema),- });-- const result = await opts.ctx.db.query.statusReport.findMany({- where: eq(statusReport.workspaceId, opts.ctx.workspace.id),- with: {- monitorsToStatusReports: { with: { monitor: true } },- statusReportUpdates: {- orderBy: (statusReportUpdate, { desc }) => [- desc(statusReportUpdate.createdAt),- ],- },- },- orderBy: (statusReport, { desc }) => [desc(statusReport.updatedAt)],- });- return z.array(selectStatusSchemaWithRelation).parse(result);- }),-- getStatusReportByPageId: protectedProcedure- .input(z.object({ id: z.number() }))- .query(async (opts) => {- // FIXME: can we get rid of that?- const selectStatusSchemaWithRelation = selectStatusReportSchema.extend({- status: statusReportStatusSchema.prefault("investigating"), // TODO: remove!- monitorsToStatusReports: z- .array(- z.object({- statusReportId: z.number(),- monitorId: z.number(),- monitor: selectMonitorSchema,- }),- )- .prefault([]),- statusReportUpdates: z.array(selectStatusReportUpdateSchema),- });-- const result = await opts.ctx.db.query.statusReport.findMany({- where: and(- eq(statusReport.workspaceId, opts.ctx.workspace.id),- eq(statusReport.pageId, opts.input.id),- ),- with: {- monitorsToStatusReports: { with: { monitor: true } },- statusReportUpdates: {- orderBy: (statusReportUpdate, { desc }) => [- desc(statusReportUpdate.createdAt),- ],- },- },- orderBy: (statusReport, { desc }) => [desc(statusReport.updatedAt)],- });- return z.array(selectStatusSchemaWithRelation).parse(result);- }),-- getPublicStatusReportById: publicProcedure- .input(z.object({ slug: z.string().toLowerCase(), id: z.number() }))- .query(async (opts) => {- const result = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,- });-- if (!result) return;-- const _statusReport = await opts.ctx.db.query.statusReport.findFirst({- where: and(- eq(statusReport.id, opts.input.id),- eq(statusReport.pageId, result.id),- eq(statusReport.workspaceId, result.workspaceId),- ),- with: {- monitorsToStatusReports: { with: { monitor: true } },- statusReportUpdates: {- orderBy: (reports, { desc }) => desc(reports.date),- },- },- });-- if (!_statusReport) return;-- return selectPublicStatusReportSchemaWithRelation.parse(_statusReport);- }),-- // DASHBOARD-list: protectedProcedure.input(z.object({diff --git a/packages/api/src/router/sync.test.ts b/packages/api/src/router/sync.test.tsindex 127384db0..25039baf4 100644--- a/packages/api/src/router/sync.test.ts+++ b/packages/api/src/router/sync.test.ts@@ -108,7 +108,16 @@ beforeAll(async () => {// Create test monitor using tRPCconst ctx = getTestContext();const caller = appRouter.createCaller(ctx);- const createdMonitor = await caller.monitor.create(monitorData);+ const createdMonitor = await caller.monitor.new({+ name: monitorData.name,+ url: monitorData.url,+ jobType: monitorData.jobType,+ method: monitorData.method,+ headers: [],+ assertions: [],+ active: false,+ skipCheck: true,+ });testMonitorId = createdMonitor.id;const createdPageComponent = await db@@ -189,10 +198,9 @@ describe("Sync: monitors_to_pages -> page_component", () => {const caller = appRouter.createCaller(ctx);// Update monitor to add it to the test page- await caller.monitor.update({- ...monitorData,+ await caller.monitor.updateStatusPages({id: testMonitorId,- pages: [testPageId],+ statusPages: [testPageId],});// Verify monitors_to_pages was created@@ -221,10 +229,9 @@ describe("Sync: monitors_to_pages -> page_component", () => {const caller = appRouter.createCaller(ctx);// First add the monitor to page if not already- await caller.monitor.update({- ...monitorData,+ await caller.monitor.updateStatusPages({id: testMonitorId,- pages: [testPageId],+ statusPages: [testPageId],});// Verify page_component exists@@ -237,10 +244,9 @@ describe("Sync: monitors_to_pages -> page_component", () => {expect(component).toBeDefined();// Remove monitor from page- await caller.monitor.update({- ...monitorData,+ await caller.monitor.updateStatusPages({id: testMonitorId,- pages: [],+ statusPages: [],});// Verify page_component was deleted@@ -357,10 +363,9 @@ describe("Sync: maintenance_to_monitor -> maintenance_to_page_component", () =>const caller = appRouter.createCaller(ctx);// Ensure monitor is on the page first- await caller.monitor.update({- ...monitorData,+ await caller.monitor.updateStatusPages({id: testMonitorId,- pages: [testPageId],+ statusPages: [testPageId],});});@@ -475,10 +480,9 @@ describe("Sync: status_report_to_monitors -> status_report_to_page_component", (const caller = appRouter.createCaller(ctx);// Ensure monitor is on the page first- await caller.monitor.update({- ...monitorData,+ await caller.monitor.updateStatusPages({id: testMonitorId,- pages: [testPageId],+ statusPages: [testPageId],});});@@ -591,13 +595,23 @@ describe("Sync: monitor deletion cascades to page_component tables", () => {const caller = appRouter.createCaller(ctx);// Create a monitor specifically for deletion tests- const deletableMonitor = await caller.monitor.create({- ...monitorData,+ const deletableMonitor = await caller.monitor.new({name: `${TEST_PREFIX}-deletable-monitor`,url: "https://delete-test.example.com",- pages: [testPageId],+ jobType: "http" as const,+ method: "GET" as const,+ headers: [],+ assertions: [],+ active: false,+ skipCheck: true,});deletableMonitorId = deletableMonitor.id;++ // Add monitor to page+ await caller.monitor.updateStatusPages({+ id: deletableMonitorId,+ statusPages: [testPageId],+ });});test("Deleting monitor removes related page_component entries", async () => {diff --git a/packages/api/src/router/workspace.test.ts b/packages/api/src/router/workspace.test.tsindex ca7e76ce0..9c1eb5ece 100644--- a/packages/api/src/router/workspace.test.ts+++ b/packages/api/src/router/workspace.test.ts@@ -62,47 +62,3 @@ test("by default we get the first workspace", async () => {endsAt: null,});});--test("All workspaces", async () => {- const ctx = createInnerTRPCContext({- req: undefined,- session: {- user: {- id: "1",- },- },- });-- const caller = edgeRouter.createCaller(ctx);- const result = await caller.workspace.getUserWithWorkspace();- expect(result).toMatchObject([- {- createdAt: expect.any(Date),- email: "[email protected]",- firstName: "Speed",- id: 1,- lastName: "Matters",- photoUrl: "",- tenantId: "1",- updatedAt: expect.any(Date),- usersToWorkspaces: [- {- userId: 1,- workspace: {- createdAt: expect.any(Date),- endsAt: null,- id: 1,- name: "test",- paidUntil: null,- plan: "team",- slug: "love-openstatus",- stripeId: "stripeId1",- subscriptionId: "subscriptionId",- updatedAt: expect.any(Date),- },- workspaceId: 1,- },- ],- },- ]);-});diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.tsindex b436ec5ba..bb7d5a09a 100644--- a/packages/api/src/router/workspace.ts+++ b/packages/api/src/router/workspace.ts@@ -1,77 +1,17 @@-import { TRPCError } from "@trpc/server";-import * as randomWordSlugs from "random-word-slugs";import { z } from "zod";import { Events } from "@openstatus/analytics";-import { type SQL, and, eq, gte, isNull, sql } from "@openstatus/db";+import { type SQL, and, eq, isNull } from "@openstatus/db";import {- application,monitor,- monitorRun,- notification,- page,- selectApplicationSchema,- selectUserSchema,selectWorkspaceSchema,- user,usersToWorkspaces,workspace,- workspacePlanSchema,- workspaceRole,} from "@openstatus/db/src/schema";-import type { Limits } from "@openstatus/db/src/schema/plan/schema";import { createTRPCRouter, protectedProcedure } from "../trpc";export const workspaceRouter = createTRPCRouter({- createWorkspace: protectedProcedure- .input(z.object({ userId: z.string() }))- .mutation(async (opts) => {- // guarantee the slug is unique accross our workspace entries- let slug: string | undefined = undefined;-- while (!slug) {- slug = randomWordSlugs.generateSlug(2);- const slugAlreadyExists = await opts.ctx.db- .select()- .from(workspace)- .where(eq(workspace.slug, slug))- .get();- if (slugAlreadyExists) {- console.log(`slug already exists: '${slug}'`);- slug = undefined;- }- }-- const _workspace = await opts.ctx.db- .insert(workspace)- .values({ slug, name: "" })- .returning({ id: workspace.id })- .get();-- await opts.ctx.db- .insert(usersToWorkspaces)- .values({- userId: opts.ctx.user.id,- workspaceId: _workspace.id,- role: "owner",- })- .returning()- .get();- }),- getUserWithWorkspace: protectedProcedure.query(async (opts) => {- return await opts.ctx.db.query.user.findMany({- with: {- usersToWorkspaces: {- with: {- workspace: true,- },- },- },- where: eq(user.id, opts.ctx.user.id),- });- }),-getWorkspace: protectedProcedure.query(async (opts) => {const result = await opts.ctx.db.query.workspace.findFirst({where: eq(workspace.id, opts.ctx.workspace.id),@@ -80,170 +20,6 @@ export const workspaceRouter = createTRPCRouter({return selectWorkspaceSchema.parse(result);}),- getApplicationWorkspaces: protectedProcedure.query(async (opts) => {- const result = await opts.ctx.db.query.application.findMany({- where: eq(application.workspaceId, opts.ctx.workspace.id),- });-- return selectApplicationSchema.array().parse(result);- }),-- getUserWorkspaces: protectedProcedure.query(async (opts) => {- const result = await opts.ctx.db.query.usersToWorkspaces.findMany({- where: eq(usersToWorkspaces.userId, opts.ctx.user.id),- with: {- workspace: true,- },- });-- return selectWorkspaceSchema- .array()- .parse(result.map(({ workspace }) => workspace));- }),-- getWorkspaceUsers: protectedProcedure.query(async (opts) => {- const result = await opts.ctx.db.query.usersToWorkspaces.findMany({- with: {- user: true,- },- where: eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),- });- return result;- }),-- updateWorkspace: protectedProcedure- .meta({ track: Events.UpdateWorkspace })- .input(z.object({ name: z.string() }))- .mutation(async (opts) => {- return await opts.ctx.db- .update(workspace)- .set({ name: opts.input.name, updatedAt: new Date() })- .where(eq(workspace.id, opts.ctx.workspace.id));- }),-- removeWorkspaceUser: protectedProcedure- .input(z.object({ id: z.number() }))- .mutation(async (opts) => {- const _userToWorkspace =- await opts.ctx.db.query.usersToWorkspaces.findFirst({- where: and(- eq(usersToWorkspaces.userId, opts.ctx.user.id),- eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),- ),- });-- if (!_userToWorkspace) throw new Error("No user to workspace found");-- if (!["owner"].includes(_userToWorkspace.role))- throw new Error("Not authorized to remove user from workspace");-- if (opts.input.id === opts.ctx.user.id)- throw new Error("Cannot remove yourself from workspace");-- await opts.ctx.db- .delete(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.userId, opts.input.id),- eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),- ),- )- .run();- }),-- changePlan: protectedProcedure- .input(z.object({ plan: workspacePlanSchema }))- .mutation(async (opts) => {- const _userToWorkspace =- await opts.ctx.db.query.usersToWorkspaces.findFirst({- where: and(- eq(usersToWorkspaces.userId, opts.ctx.user.id),- eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),- ),- });-- if (!_userToWorkspace) throw new Error("No user to workspace found");-- if (!["owner"].includes(_userToWorkspace.role))- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: "Not authorized to change plan",- });-- if (!opts.ctx.workspace.stripeId) {- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: "No Stripe ID found for workspace",- });- }-- // TODO: Create subscription- switch (opts.input.plan) {- case "free": {- break;- }- case "starter": {- break;- }- case "team": {- break;- }- default: {- }- }-- await opts.ctx.db- .update(workspace)- .set({ plan: opts.input.plan, updatedAt: new Date() })- .where(eq(workspace.id, opts.ctx.workspace.id));- }),-- getCurrentWorkspaceNumbers: protectedProcedure.query(async (opts) => {- const lastMonth = new Date().setMonth(new Date().getMonth() - 1);-- const currentNumbers = await opts.ctx.db.transaction(async (tx) => {- const notifications = await tx- .select({ count: sql<number>`count(*)` })- .from(notification)- .where(eq(notification.workspaceId, opts.ctx.workspace.id));- const monitors = await tx- .select({ count: sql<number>`count(*)` })- .from(monitor)- .where(- and(- eq(monitor.workspaceId, opts.ctx.workspace.id),- isNull(monitor.deletedAt),- ),- );- const pages = await tx- .select({ count: sql<number>`count(*)` })- .from(page)- .where(eq(page.workspaceId, opts.ctx.workspace.id));-- const runs = await tx- .select({ count: sql<number>`count(*)` })- .from(monitorRun)- .where(- and(- eq(monitorRun.workspaceId, opts.ctx.workspace.id),- gte(monitorRun.createdAt, new Date(lastMonth)),- ),- )- .all();-- return {- "notification-channels": notifications?.[0].count || 0,- monitors: monitors?.[0].count || 0,- "status-pages": pages?.[0].count || 0,- "synthetic-checks": runs?.[0].count || 0,- } satisfies Partial<Limits>;- });-- return currentNumbers;- }),-- // DASHBOARD-get: protectedProcedure.query(async (opts) => {const whereConditions: SQL[] = [eq(workspace.id, opts.ctx.workspace.id)];@@ -270,24 +46,6 @@ export const workspaceRouter = createTRPCRouter({});}),- getMembers: protectedProcedure.query(async (opts) => {- const result = await opts.ctx.db.query.usersToWorkspaces.findMany({- where: eq(usersToWorkspaces.userId, opts.ctx.workspace.id),- with: {- user: true,- },- });-- return z- .object({- role: z.enum(workspaceRole),- createdAt: z.coerce.date(),- user: selectUserSchema,- })- .array()- .parse(result);- }),-list: protectedProcedure.query(async (opts) => {const result = await opts.ctx.db.query.usersToWorkspaces.findMany({where: eq(usersToWorkspaces.userId, opts.ctx.user.id),