Skip to content

Open-source status page, incident response and uptime monitoring

chore: link email templates (#1208)

Maximilian Kaske1af6c3eb43e3
diff --git a/apps/checker/handlers/checker.go b/apps/checker/handlers/checker.go
index 230a12157..189eb88b5 100644
--- a/apps/checker/handlers/checker.go
+++ b/apps/checker/handlers/checker.go
@@ -202,6 +202,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
Message: res.Error,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
// Check if the status is degraded
@@ -212,6 +213,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
StatusCode: res.Status,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
}
@@ -225,6 +227,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
StatusCode: res.Status,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
@@ -246,6 +249,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
StatusCode: res.Status,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
}
@@ -259,6 +263,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
StatusCode: res.Status,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
@@ -269,6 +274,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
Region: h.Region,
StatusCode: res.Status,
CronTimestamp: req.CronTimestamp,
+ Latency: res.Latency,
})
}
}
diff --git a/apps/checker/handlers/tcp.go b/apps/checker/handlers/tcp.go
index a14cfc306..539c53dae 100644
--- a/apps/checker/handlers/tcp.go
+++ b/apps/checker/handlers/tcp.go
@@ -133,6 +133,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
Status: "degraded",
Region: h.Region,
CronTimestamp: req.CronTimestamp,
+ Latency: latency,
})
}
@@ -142,6 +143,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
Status: "active",
Region: h.Region,
CronTimestamp: req.CronTimestamp,
+ Latency: latency,
})
}
@@ -152,6 +154,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
Status: "active",
Region: h.Region,
CronTimestamp: req.CronTimestamp,
+ Latency: latency,
})
}
@@ -161,6 +164,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
Status: "degraded",
Region: h.Region,
CronTimestamp: req.CronTimestamp,
+ Latency: latency,
})
}
diff --git a/apps/checker/update.go b/apps/checker/update.go
index b6e7ce8cb..788b6f145 100644
--- a/apps/checker/update.go
+++ b/apps/checker/update.go
@@ -18,6 +18,7 @@ type UpdateData struct {
Region string `json:"region"`
CronTimestamp int64 `json:"cronTimestamp"`
StatusCode int `json:"statusCode,omitempty"`
+ Latency int64 `json:"latency,omitempty"`
}
func UpdateStatus(ctx context.Context, updateData UpdateData) {
diff --git a/apps/server/src/env.ts b/apps/server/src/env.ts
index dd54daade..dbaa3cf81 100644
--- a/apps/server/src/env.ts
+++ b/apps/server/src/env.ts
@@ -15,6 +15,7 @@ export const env = createEnv({
QSTASH_TOKEN: z.string(),
NODE_ENV: z.string().default("development"),
SUPER_ADMIN_TOKEN: z.string(),
+ RESEND_API_KEY: z.string(),
},
/**
diff --git a/apps/server/src/libs/cache/memory.ts b/apps/server/src/libs/cache/memory.ts
index e46680d41..8022938bf 100644
--- a/apps/server/src/libs/cache/memory.ts
+++ b/apps/server/src/libs/cache/memory.ts
@@ -48,4 +48,4 @@ export class MemoryCache {
}
}
-const cache = new MemoryCache();
+const _cache = new MemoryCache();
diff --git a/apps/server/src/routes/checker/alerting.ts b/apps/server/src/routes/checker/alerting.ts
index aca3b1c7e..27357977c 100644
--- a/apps/server/src/routes/checker/alerting.ts
+++ b/apps/server/src/routes/checker/alerting.ts
@@ -6,7 +6,10 @@ import {
} from "@openstatus/db/src/schema";
import { checkerAudit } from "@/utils/audit-log";
-import type { MonitorFlyRegion } from "@openstatus/db/src/schema/constants";
+import type {
+ MonitorFlyRegion,
+ Region,
+} from "@openstatus/db/src/schema/constants";
import { Redis } from "@openstatus/upstash";
import { providerToFunction } from "./utils";
@@ -19,6 +22,8 @@ export const triggerNotifications = async ({
notifType,
cronTimestamp,
incidentId,
+ region,
+ latency,
}: {
monitorId: string;
statusCode?: number;
@@ -26,6 +31,8 @@ export const triggerNotifications = async ({
notifType: "alert" | "recovery" | "degraded";
cronTimestamp: number;
incidentId: string;
+ region?: Region;
+ latency?: number;
}) => {
console.log(`πŸ’Œ triggerAlerting for ${monitorId}`);
const notifications = await db
@@ -64,6 +71,8 @@ export const triggerNotifications = async ({
message,
incidentId,
cronTimestamp,
+ region,
+ latency,
});
break;
case "recovery":
@@ -74,6 +83,8 @@ export const triggerNotifications = async ({
message,
incidentId,
cronTimestamp,
+ region,
+ latency,
});
break;
case "degraded":
@@ -83,6 +94,8 @@ export const triggerNotifications = async ({
statusCode,
message,
cronTimestamp,
+ region,
+ latency,
});
break;
}
diff --git a/apps/server/src/routes/checker/index.ts b/apps/server/src/routes/checker/index.ts
index 6cf504763..ab8812a02 100644
--- a/apps/server/src/routes/checker/index.ts
+++ b/apps/server/src/routes/checker/index.ts
@@ -33,6 +33,7 @@ checkerRoute.post("/updateStatus", async (c) => {
region: z.enum(flyRegions),
cronTimestamp: z.number(),
status: monitorStatusSchema,
+ latency: z.number().optional(),
});
const result = payloadSchema.safeParse(json);
@@ -40,8 +41,15 @@ checkerRoute.post("/updateStatus", async (c) => {
if (!result.success) {
return c.text("Unprocessable Entity", 422);
}
- const { monitorId, message, region, statusCode, cronTimestamp, status } =
- result.data;
+ const {
+ monitorId,
+ message,
+ region,
+ statusCode,
+ cronTimestamp,
+ status,
+ latency,
+ } = result.data;
console.log(`πŸ“ update monitor status ${JSON.stringify(result.data)}`);
@@ -103,6 +111,8 @@ checkerRoute.post("/updateStatus", async (c) => {
notifType: "degraded",
cronTimestamp,
incidentId: `${cronTimestamp}`,
+ region,
+ latency,
});
}
}
@@ -182,6 +192,8 @@ checkerRoute.post("/updateStatus", async (c) => {
incidentId: newIncident.length
? String(newIncident[0]?.id)
: `${cronTimestamp}`,
+ region,
+ latency,
});
if (newIncident.length > 0) {
@@ -287,6 +299,8 @@ checkerRoute.post("/updateStatus", async (c) => {
notifType: "recovery",
cronTimestamp,
incidentId: String(incident.id),
+ region,
+ latency,
});
const monitor = await db
diff --git a/apps/server/src/routes/checker/utils.ts b/apps/server/src/routes/checker/utils.ts
index 1b0fe6ba5..be6d123db 100644
--- a/apps/server/src/routes/checker/utils.ts
+++ b/apps/server/src/routes/checker/utils.ts
@@ -30,6 +30,7 @@ import {
sendAlert as sendPagerdutyAlert,
} from "@openstatus/notification-pagerduty";
+import type { Region } from "@openstatus/db/src/schema/constants";
import {
sendAlert as sendOpsGenieAlert,
sendDegraded as sendOpsGenieDegraded,
@@ -43,6 +44,8 @@ type SendNotification = ({
message,
incidentId,
cronTimestamp,
+ latency,
+ region,
}: {
monitor: Monitor;
notification: Notification;
@@ -50,6 +53,8 @@ type SendNotification = ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => Promise<void>;
type Notif = {
diff --git a/apps/server/src/routes/v1/statusReportUpdates/post.ts b/apps/server/src/routes/v1/statusReportUpdates/post.ts
index 004bc2059..2e2537ad4 100644
--- a/apps/server/src/routes/v1/statusReportUpdates/post.ts
+++ b/apps/server/src/routes/v1/statusReportUpdates/post.ts
@@ -7,12 +7,15 @@ import {
statusReport,
statusReportUpdate,
} from "@openstatus/db/src/schema";
-import { sendEmailHtml } from "@openstatus/emails";
+import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
+import { EmailClient } from "@openstatus/emails";
import type { statusReportUpdatesApi } from "./index";
import { StatusReportUpdateSchema } from "./schema";
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
+
const createStatusUpdate = createRoute({
method: "post",
tags: ["status_report_update"],
@@ -89,21 +92,27 @@ export function registerPostStatusReportUpdate(
)
.all();
- const pageInfo = await db
- .select()
- .from(page)
- .where(eq(page.id, _statusReport.pageId))
- .get();
- if (pageInfo) {
- const subscribersEmails = subscribers.map((subscriber) => ({
- to: subscriber.email,
- subject: `New status update for ${pageInfo.title}`,
- html: `<p>Hi,</p><p>${pageInfo.title} just posted an update on their status page:</p><p>New Status : ${statusReportUpdate.status}</p><p>${statusReportUpdate.message}</p></p><p></p><p>Powered by OpenStatus</p><p></p><p></p><p></p><p></p><p></p>
- `,
- from: "Notification OpenStatus <[email protected]>",
- }));
+ const _page = await db.query.page.findFirst({
+ where: eq(page.id, _statusReport.pageId),
+ with: {
+ monitorsToPages: {
+ with: {
+ monitor: true,
+ },
+ },
+ },
+ });
- await sendEmailHtml(subscribersEmails);
+ if (_page && subscribers.length > 0) {
+ await emailClient.sendStatusReportUpdate({
+ to: subscribers.map((subscriber) => subscriber.email),
+ pageTitle: _page.title,
+ reportTitle: _statusReport.title,
+ status: _statusReport.status,
+ message: _statusReportUpdate.message,
+ date: _statusReportUpdate.date.toISOString(),
+ monitors: _page.monitorsToPages.map((i) => i.monitor.name),
+ });
}
}
diff --git a/apps/server/src/routes/v1/statusReports/post.ts b/apps/server/src/routes/v1/statusReports/post.ts
index 58ece9249..4a2e95b42 100644
--- a/apps/server/src/routes/v1/statusReports/post.ts
+++ b/apps/server/src/routes/v1/statusReports/post.ts
@@ -10,11 +10,14 @@ import {
statusReportUpdate,
} from "@openstatus/db/src/schema";
+import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
-import { sendBatchEmailHtml } from "@openstatus/emails/src/send";
+import { EmailClient } from "@openstatus/emails";
import type { statusReportsApi } from "./index";
import { StatusReportSchema } from "./schema";
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
+
const postRoute = createRoute({
method: "post",
tags: ["status_report"],
@@ -142,24 +145,27 @@ export function registerPostStatusReport(api: typeof statusReportsApi) {
)
.all();
- const pageInfo = await db
- .select()
- .from(page)
- .where(eq(page.id, _newStatusReport.pageId))
- .get();
-
- if (pageInfo) {
- const emails = subscribers.map((subscriber) => {
- return {
- to: subscriber.email,
- subject: `New status update for ${pageInfo.title}`,
- html: `<p>Hi,</p><p>${pageInfo.title} just posted an update on their status page:</p><p>New Status : ${statusReportUpdate.status}</p><p>${statusReportUpdate.message}</p></p><p></p><p>Powered by OpenStatus</p><p></p><p></p><p></p><p></p><p></p>
- `,
- from: "Notification OpenStatus <[email protected]>",
- };
- });
+ const pageInfo = await db.query.page.findFirst({
+ where: eq(page.id, _newStatusReport.pageId),
+ with: {
+ monitorsToPages: {
+ with: {
+ monitor: true,
+ },
+ },
+ },
+ });
- await sendBatchEmailHtml(emails);
+ if (pageInfo && subscribers.length > 0) {
+ await emailClient.sendStatusReportUpdate({
+ to: subscribers.map((subscriber) => subscriber.email),
+ pageTitle: pageInfo.title,
+ reportTitle: _newStatusReport.title,
+ status: _newStatusReport.status,
+ message: _newStatusReportUpdate.message,
+ date: _newStatusReportUpdate.date.toISOString(),
+ monitors: pageInfo.monitorsToPages.map((i) => i.monitor.name),
+ });
}
}
diff --git a/apps/server/src/routes/v1/statusReports/update/post.ts b/apps/server/src/routes/v1/statusReports/update/post.ts
index 6c6e47634..5598b886c 100644
--- a/apps/server/src/routes/v1/statusReports/update/post.ts
+++ b/apps/server/src/routes/v1/statusReports/update/post.ts
@@ -1,17 +1,22 @@
+import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
import { createRoute } from "@hono/zod-openapi";
import { and, db, eq, isNotNull } from "@openstatus/db";
import {
+ monitor,
page,
pageSubscriber,
statusReport,
statusReportUpdate,
} from "@openstatus/db/src/schema";
+import { EmailClient } from "@openstatus/emails/src/client";
import { sendBatchEmailHtml } from "@openstatus/emails/src/send";
import { StatusReportUpdateSchema } from "../../statusReportUpdates/schema";
import type { statusReportsApi } from "../index";
import { ParamsSchema, StatusReportSchema } from "../schema";
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
+
const postRouteUpdate = createRoute({
method: "post",
tags: ["status_report"],
@@ -82,6 +87,18 @@ export function registerStatusReportUpdateRoutes(api: typeof statusReportsApi) {
.get();
if (limits.notifications && _statusReport.pageId) {
+ const allInfo = await db.query.statusReport.findFirst({
+ where: eq(statusReport.id, Number(id)),
+ with: {
+ monitorsToStatusReports: {
+ with: {
+ monitor: true,
+ },
+ },
+ page: true,
+ },
+ });
+
const subscribers = await db
.select()
.from(pageSubscriber)
@@ -92,22 +109,19 @@ export function registerStatusReportUpdateRoutes(api: typeof statusReportsApi) {
),
)
.all();
- const pageInfo = await db
- .select()
- .from(page)
- .where(eq(page.id, _statusReport.pageId))
- .get();
- if (pageInfo) {
- const subscribersEmails = subscribers.map((subscriber) => {
- return {
- to: subscriber.email,
- subject: `New status update for ${pageInfo.title}`,
- html: `<p>Hi,</p><p>${pageInfo.title} just posted an update on their status page:</p><p>New Status : ${statusReportUpdate.status}</p><p>${statusReportUpdate.message}</p></p><p></p><p>Powered by OpenStatus</p><p></p><p></p><p></p><p></p><p></p>
- `,
- from: "Notification OpenStatus <[email protected]>",
- };
+
+ if (allInfo?.page) {
+ await emailClient.sendStatusReportUpdate({
+ to: subscribers.map((subscriber) => subscriber.email),
+ pageTitle: allInfo.page.title,
+ reportTitle: allInfo.title,
+ status: allInfo.status,
+ message: _statusReportUpdate.message,
+ date: _statusReportUpdate.date.toISOString(),
+ monitors: allInfo.monitorsToStatusReports.map(
+ (monitor) => monitor.monitor.name,
+ ),
});
- await sendBatchEmailHtml(subscribersEmails);
}
}
diff --git a/apps/server/src/routes/v1/utils.ts b/apps/server/src/routes/v1/utils.ts
index bf452fae5..6872eb5b9 100644
--- a/apps/server/src/routes/v1/utils.ts
+++ b/apps/server/src/routes/v1/utils.ts
@@ -7,7 +7,7 @@ export const isoDate = z.preprocess((val) => {
return new Date(String(val)).toISOString();
}
return new Date().toISOString();
- } catch (e) {
+ } catch (_e) {
throw new ZodError([
{ code: "invalid_date", message: "Invalid date", path: [] },
]);
diff --git a/apps/web/src/app/api/checker/cron/10m/route.ts b/apps/web/src/app/api/checker/cron/10m/route.ts
index f3088d3d5..09222f99b 100644
--- a/apps/web/src/app/api/checker/cron/10m/route.ts
+++ b/apps/web/src/app/api/checker/cron/10m/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "10m", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/api/checker/cron/1h/route.ts b/apps/web/src/app/api/checker/cron/1h/route.ts
index c710f1772..f470d2d71 100644
--- a/apps/web/src/app/api/checker/cron/1h/route.ts
+++ b/apps/web/src/app/api/checker/cron/1h/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "1h", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/api/checker/cron/1m/route.ts b/apps/web/src/app/api/checker/cron/1m/route.ts
index 3f216eaff..017973c59 100644
--- a/apps/web/src/app/api/checker/cron/1m/route.ts
+++ b/apps/web/src/app/api/checker/cron/1m/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "1m", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/api/checker/cron/30m/route.ts b/apps/web/src/app/api/checker/cron/30m/route.ts
index e07fdc782..ee763b1c0 100644
--- a/apps/web/src/app/api/checker/cron/30m/route.ts
+++ b/apps/web/src/app/api/checker/cron/30m/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "30m", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/api/checker/cron/30s/route.ts b/apps/web/src/app/api/checker/cron/30s/route.ts
index 3105a32d9..afcf1c977 100644
--- a/apps/web/src/app/api/checker/cron/30s/route.ts
+++ b/apps/web/src/app/api/checker/cron/30s/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "30s", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/api/checker/cron/5m/route.ts b/apps/web/src/app/api/checker/cron/5m/route.ts
index 1e65e22c8..000bf79e0 100644
--- a/apps/web/src/app/api/checker/cron/5m/route.ts
+++ b/apps/web/src/app/api/checker/cron/5m/route.ts
@@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
try {
await cron({ periodicity: "5m", req });
await cronCompleted();
- } catch (error) {
+ } catch (_error) {
await cronFailed();
}
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/team/_components/invite-button.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/team/_components/invite-button.tsx
index 65ff4f7bc..20f611056 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/team/_components/invite-button.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/team/_components/invite-button.tsx
@@ -50,7 +50,8 @@ export function InviteButton({
async function onSubmit(data: Schema) {
startTransition(async () => {
try {
- api.invitation.create.mutate(data);
+ const invitation = await api.invitation.create.mutate(data);
+ await api.emailRouter.sendTeamInvitation.mutate({ id: invitation.id });
toastAction("saved");
router.refresh();
} catch {
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/(overview)/_components/status-report-button.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/(overview)/_components/status-report-button.tsx
index e1a6f0193..ffcb99f8a 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/(overview)/_components/status-report-button.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/(overview)/_components/status-report-button.tsx
@@ -33,9 +33,9 @@ export function StatusReportButton({ pages }: { pages: Page[] }) {
"mt-2",
)}
>
- <Megaphone className="h-4 w-4 mr-1 pb-0.5" />
+ <Megaphone className="mr-1 h-4 w-4 pb-0.5" />
New Status Report
- <span className="h-8 w-px bg-background mx-2" />
+ <span className="mx-2 h-8 w-px bg-background" />
<ChevronDown className="h-4 w-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
diff --git a/apps/web/src/app/status-page/[domain]/_components/actions.ts b/apps/web/src/app/status-page/[domain]/_components/actions.ts
index f1eb5f608..a5cfc9ed6 100644
--- a/apps/web/src/app/status-page/[domain]/_components/actions.ts
+++ b/apps/web/src/app/status-page/[domain]/_components/actions.ts
@@ -2,11 +2,14 @@
import { z } from "zod";
+import { env } from "@/env";
import { Events, setupAnalytics } from "@openstatus/analytics";
import { and, eq, sql } from "@openstatus/db";
import { db } from "@openstatus/db/src/db";
import { page, pageSubscriber } from "@openstatus/db/src/schema";
-import { SubscribeEmail, sendEmail } from "@openstatus/emails";
+import { EmailClient } from "@openstatus/emails";
+
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
const subscribeSchema = z.object({
email: z
@@ -76,15 +79,11 @@ export async function handleSubscribe(formData: FormData) {
})
.execute();
- await sendEmail({
- react: SubscribeEmail({
- domain: pageData.slug,
- token: token,
- page: pageData.title,
- }),
- from: "OpenStatus <[email protected]>",
- to: [validatedFields.data.email],
- subject: `Verify your subscription to ${pageData.title}`,
+ await emailClient.sendPageSubscription({
+ domain: pageData.slug,
+ token,
+ page: pageData.title,
+ to: validatedFields.data.email,
});
const analytics = await setupAnalytics({});
diff --git a/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx b/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx
index 48a9bf28e..3b4066291 100644
--- a/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx
+++ b/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx
@@ -76,7 +76,7 @@ export function SubscribeButton({
) : null}
{isSubscribers ? (
<DropdownMenuItem onClick={() => setShowModal(true)}>
- <Mail className="h-4 w-4 mr-2" />
+ <Mail className="mr-2 h-4 w-4" />
Email
</DropdownMenuItem>
) : null}
diff --git a/apps/web/src/components/content/article.tsx b/apps/web/src/components/content/article.tsx
index c1e81021b..b7ac3b914 100644
--- a/apps/web/src/components/content/article.tsx
+++ b/apps/web/src/components/content/article.tsx
@@ -40,7 +40,7 @@ export function Article({ post }: { post: Post }) {
>
{post.author.name}
</Link>
- <div className="flex items-center gap-1.5 flex-wrap">
+ <div className="flex flex-wrap items-center gap-1.5">
<time className="font-mono">{formatDate(post.publishedAt)}</time>
<span className="text-muted-foreground/70">&bull;</span>
<span className="font-mono">{post.readingTime}</span>
diff --git a/apps/web/src/components/content/changelog.tsx b/apps/web/src/components/content/changelog.tsx
index ef51b953a..0273043c0 100644
--- a/apps/web/src/components/content/changelog.tsx
+++ b/apps/web/src/components/content/changelog.tsx
@@ -6,7 +6,7 @@ import { formatDate } from "@/lib/utils";
export function ChangelogCard({ post }: { post: Changelog }) {
return (
- <article className="relative mx-auto flex max-w-prose w-full flex-col gap-8">
+ <article className="relative mx-auto flex w-full max-w-prose flex-col gap-8">
<div className="grid w-full gap-3">
<p className="font-mono text-muted-foreground text-sm">
{formatDate(new Date(post.publishedAt))}
diff --git a/apps/web/src/components/content/mdx.tsx b/apps/web/src/components/content/mdx.tsx
index 844f34b00..0216096f4 100644
--- a/apps/web/src/components/content/mdx.tsx
+++ b/apps/web/src/components/content/mdx.tsx
@@ -13,7 +13,7 @@ export function Mdx({ code, className }: MdxProps) {
// FIXME: weird behaviour when `prose-headings:font-cal` and on mouse movement font gets bigger
<div
className={cn(
- "prose prose-slate dark:prose-invert prose-pre:my-0 prose-img:rounded-lg prose-pre:bg-background prose-pre:rounded-lg prose-img:border prose-pre:border prose-img:border-border prose-pre:border-border prose-headings:font-cal prose-headings:font-normal prose-blockquote:font-light prose-blockquote:border-l-2",
+ "prose prose-slate dark:prose-invert prose-pre:my-0 prose-img:rounded-lg prose-pre:rounded-lg prose-img:border prose-pre:border prose-img:border-border prose-pre:border-border prose-blockquote:border-l-2 prose-pre:bg-background prose-blockquote:font-light prose-headings:font-cal prose-headings:font-normal",
className,
)}
>
diff --git a/apps/web/src/components/data-table/status-page/columns.tsx b/apps/web/src/components/data-table/status-page/columns.tsx
index d95b10c68..8558aed94 100644
--- a/apps/web/src/components/data-table/status-page/columns.tsx
+++ b/apps/web/src/components/data-table/status-page/columns.tsx
@@ -112,7 +112,7 @@ export const columns: ColumnDef<
<span className="group-hover:text-muted-foreground/70">
{formatDate(date)}
</span>
- <div className="absolute -inset-x-2 -inset-y-1 invisible group-hover:visible backdrop-blur-sm flex items-center px-2 py-1">
+ <div className="-inset-x-2 -inset-y-1 invisible absolute flex items-center px-2 py-1 backdrop-blur-sm group-hover:visible">
<Link
href={`./status-pages/${row.original.id}/reports/${lastReport.id}`}
className="hover:underline"
diff --git a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx b/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx
index f20e388e6..9a2939145 100644
--- a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx
+++ b/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx
@@ -150,7 +150,7 @@ export function DataTableRowActions<TData>({
Create an uptime badge for your status page.
</DialogDescription>
<div className="flex items-center justify-center">
- <div className="flex items-center justify-center p-4 border rounded-md w-full">
+ <div className="flex w-full items-center justify-center rounded-md border p-4">
<img
src={`/status-page/${page.slug}/badge?size=${size}&theme=${theme}`}
alt="Badge"
@@ -175,7 +175,7 @@ export function DataTableRowActions<TData>({
))}
</RadioGroup>
<div>
- <span className="text-sm text-muted-foreground font-mono">
+ <span className="font-mono text-muted-foreground text-sm">
{SIZE[size].width}x{SIZE[size].height}
</span>
</div>
diff --git a/apps/web/src/components/forms/status-report-update/form.tsx b/apps/web/src/components/forms/status-report-update/form.tsx
index 98a1fb51c..5d72d95f8 100644
--- a/apps/web/src/components/forms/status-report-update/form.tsx
+++ b/apps/web/src/components/forms/status-report-update/form.tsx
@@ -50,9 +50,18 @@ export function StatusReportUpdateForm({
startTransition(async () => {
try {
if (defaultValues) {
- await api.statusReport.updateStatusReportUpdate.mutate({ ...props });
+ await api.statusReport.updateStatusReportUpdate.mutate({
+ ...props,
+ });
} else {
- await api.statusReport.createStatusReportUpdate.mutate({ ...props });
+ const statusReportUpdate =
+ await api.statusReport.createStatusReportUpdate.mutate({
+ ...props,
+ });
+ if (!statusReportUpdate) return;
+ await api.emailRouter.sendStatusReport.mutate({
+ id: statusReportUpdate.id,
+ });
}
toastAction("saved");
onSubmit?.();
diff --git a/apps/web/src/components/forms/status-report/form.tsx b/apps/web/src/components/forms/status-report/form.tsx
index 07f074d14..be7635675 100644
--- a/apps/web/src/components/forms/status-report/form.tsx
+++ b/apps/web/src/components/forms/status-report/form.tsx
@@ -82,12 +82,19 @@ export function StatusReportForm({
);
// include update on creation
if (statusReport?.id) {
- await api.statusReport.createStatusReportUpdate.mutate({
- message,
- date,
- status,
- statusReportId: statusReport.id,
- });
+ const statusReportUpdate =
+ await api.statusReport.createStatusReportUpdate.mutate({
+ message,
+ date,
+ status,
+ statusReportId: statusReport.id,
+ });
+
+ if (statusReportUpdate) {
+ await api.emailRouter.sendStatusReport.mutate({
+ id: statusReportUpdate.id,
+ });
+ }
}
}
if (nextUrl) {
diff --git a/apps/web/src/trpc/shared.ts b/apps/web/src/trpc/shared.ts
index b0e827330..9d9b3a03c 100644
--- a/apps/web/src/trpc/shared.ts
+++ b/apps/web/src/trpc/shared.ts
@@ -11,7 +11,7 @@ const getBaseUrl = () => {
return "http://localhost:3000";
};
-const lambdas = ["stripeRouter", "rumRouter"];
+const lambdas = ["stripeRouter", "emailRouter"];
export const endingLink = (opts?: {
headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
diff --git a/packages/api/src/lambda.ts b/packages/api/src/lambda.ts
index 7948ddf37..d384b4fb0 100644
--- a/packages/api/src/lambda.ts
+++ b/packages/api/src/lambda.ts
@@ -1,9 +1,10 @@
+import { emailRouter } from "./router/email";
import { stripeRouter } from "./router/stripe";
import { createTRPCRouter } from "./trpc";
-
// Deployed to /trpc/lambda/**
export const lambdaRouter = createTRPCRouter({
stripeRouter: stripeRouter,
+ emailRouter: emailRouter,
});
export { stripe } from "./router/stripe/shared";
diff --git a/packages/api/src/router/email/index.ts b/packages/api/src/router/email/index.ts
new file mode 100644
index 000000000..6598f059f
--- /dev/null
+++ b/packages/api/src/router/email/index.ts
@@ -0,0 +1,88 @@
+import { z } from "zod";
+
+import { and, eq, isNotNull } from "@openstatus/db";
+import {
+ invitation,
+ pageSubscriber,
+ statusReportUpdate,
+} from "@openstatus/db/src/schema";
+import { EmailClient } from "@openstatus/emails";
+import { env } from "../../env";
+import { createTRPCRouter, protectedProcedure } from "../../trpc";
+
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
+
+export const emailRouter = createTRPCRouter({
+ sendStatusReport: protectedProcedure
+ .input(z.object({ id: z.number() }))
+ .mutation(async (opts) => {
+ const limits = opts.ctx.workspace.limits;
+
+ if (limits["status-subscribers"]) {
+ const _statusReportUpdate =
+ await opts.ctx.db.query.statusReportUpdate.findFirst({
+ where: eq(statusReportUpdate.id, opts.input.id),
+ with: {
+ statusReport: {
+ with: {
+ page: {
+ with: {
+ pageSubscribers: {
+ where: isNotNull(pageSubscriber.acceptedAt),
+ },
+ monitorsToPages: {
+ with: {
+ monitor: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!_statusReportUpdate) return;
+ if (!_statusReportUpdate.statusReport.page) return;
+ if (!_statusReportUpdate.statusReport.page.pageSubscribers.length)
+ return;
+
+ await emailClient.sendStatusReportUpdate({
+ to: _statusReportUpdate.statusReport.page.pageSubscribers.map(
+ (subscriber) => subscriber.email,
+ ),
+ pageTitle: _statusReportUpdate.statusReport.page.title,
+ reportTitle: _statusReportUpdate.statusReport.title,
+ status: _statusReportUpdate.status,
+ message: _statusReportUpdate.message,
+ date: new Date(_statusReportUpdate.date).toISOString(),
+ monitors: _statusReportUpdate.statusReport.page.monitorsToPages.map(
+ (i) => i.monitor.name,
+ ),
+ });
+ }
+ }),
+ sendTeamInvitation: protectedProcedure
+ .input(z.object({ id: z.number() }))
+ .mutation(async (opts) => {
+ const limits = opts.ctx.workspace.limits;
+
+ if (limits.members === "Unlimited" || limits.members > 1) {
+ const _invitation = await opts.ctx.db.query.invitation.findFirst({
+ where: and(
+ eq(invitation.id, opts.input.id),
+ eq(invitation.workspaceId, opts.ctx.workspace.id),
+ ),
+ });
+
+ if (!_invitation) return;
+
+ await emailClient.sendTeamInvitation({
+ to: _invitation.email,
+ token: _invitation.token,
+ invitedBy: `${opts.ctx.user.email}`,
+ workspaceName: opts.ctx.workspace.name || "OpenStatus",
+ });
+ }
+ }),
+});
diff --git a/packages/api/src/router/invitation.ts b/packages/api/src/router/invitation.ts
index 4c8b091ef..5be7115d1 100644
--- a/packages/api/src/router/invitation.ts
+++ b/packages/api/src/router/invitation.ts
@@ -62,30 +62,6 @@ export const invitationRouter = createTRPCRouter({
console.log(
`>>>> Invitation token: http://localhost:3000/app/invite?token=${token} <<<< `,
);
- } else {
- await fetch("https://api.resend.com/emails", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
- },
- body: JSON.stringify({
- to: email,
- from: "OpenStatus <[email protected]>",
- subject: "You have been invited to join OpenStatus.dev",
- html: `<p>You have been invited by ${opts.ctx.user.email} ${
- opts.ctx.workspace.name
- ? `to join the workspace '${opts.ctx.workspace.name}'.`
- : "to join a workspace."
- }</p>
- <br>
- <p>Click here to access the workspace: <a href='https://openstatus.dev/app/invite?token=${
- _invitation.token
- }'>accept invitation</a>.</p>
- <p>If you don't have an account yet, it will require you to create one.</p>
- `,
- }),
- });
}
return _invitation;
diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.ts
index a624f7583..4af35e460 100644
--- a/packages/api/src/router/statusReport.ts
+++ b/packages/api/src/router/statusReport.ts
@@ -1,12 +1,11 @@
import { z } from "zod";
-import { and, eq, inArray, isNotNull, sql } from "@openstatus/db";
+import { and, eq, inArray, sql } from "@openstatus/db";
import {
insertStatusReportSchema,
insertStatusReportUpdateSchema,
monitorsToStatusReport,
page,
- pageSubscriber,
selectMonitorSchema,
selectPublicStatusReportSchemaWithRelation,
selectStatusReportSchema,
@@ -14,9 +13,7 @@ import {
statusReport,
statusReportStatusSchema,
statusReportUpdate,
- workspace,
} from "@openstatus/db/src/schema";
-import { sendBatchEmailHtml } from "@openstatus/emails/src/send";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
@@ -67,9 +64,9 @@ export const statusReportRouter = createTRPCRouter({
.returning()
.get();
- const { id, ...statusReportUpdateInput } = opts.input;
+ if (!_statusReport) return;
- // Send email
+ const { id, ...statusReportUpdateInput } = opts.input;
const updatedValue = await opts.ctx.db
.insert(statusReportUpdate)
@@ -77,44 +74,7 @@ export const statusReportRouter = createTRPCRouter({
.returning()
.get();
- const currentWorkspace = await opts.ctx.db
- .select()
- .from(workspace)
- .where(eq(workspace.id, opts.ctx.workspace.id))
- .get();
- if (currentWorkspace?.plan !== "pro" && _statusReport.pageId) {
- const subscribers = await opts.ctx.db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, _statusReport.pageId),
- isNotNull(pageSubscriber.acceptedAt),
- ),
- )
- .all();
- const pageInfo = await opts.ctx.db
- .select()
- .from(page)
- .where(eq(page.id, _statusReport.pageId))
- .get();
- if (pageInfo) {
- const emails = subscribers.map((subscriber) => {
- return {
- to: subscriber.email,
-
- subject: `New status update for ${pageInfo.title}`,
- html: `<p>Hi,</p><p>${pageInfo.title} just posted an update on their status page:</p><p>New Status : ${updatedValue.status}</p><p>${updatedValue.message}</p></p><p></p><p>Powered by OpenStatus</p><p></p><p></p><p></p><p></p><p></p>
- `,
- from: "Notification OpenStatus <[email protected]>",
- };
- });
- if (emails.length > 0) {
- await sendBatchEmailHtml(emails);
- }
- }
- }
- return updatedValue;
+ return selectStatusReportUpdateSchema.parse(updatedValue);
}),
updateStatusReport: protectedProcedure
@@ -195,7 +155,7 @@ export const statusReportRouter = createTRPCRouter({
.returning()
.get();
- return currentStatusReportUpdate;
+ return selectStatusReportUpdateSchema.parse(currentStatusReportUpdate);
}),
deleteStatusReport: protectedProcedure
diff --git a/packages/db/src/schema/pages/page.ts b/packages/db/src/schema/pages/page.ts
index c0e27c5bd..e537a0a40 100644
--- a/packages/db/src/schema/pages/page.ts
+++ b/packages/db/src/schema/pages/page.ts
@@ -3,6 +3,7 @@ import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { maintenance } from "../maintenances";
import { monitorsToPages } from "../monitors";
+import { pageSubscriber } from "../page_subscribers";
import { statusReport } from "../status_reports";
import { workspace } from "../workspaces";
@@ -49,4 +50,5 @@ export const pageRelations = relations(page, ({ many, one }) => ({
fields: [page.workspaceId],
references: [workspace.id],
}),
+ pageSubscribers: many(pageSubscriber),
}));
diff --git a/packages/db/src/schema/status_reports/status_reports.ts b/packages/db/src/schema/status_reports/status_reports.ts
index e0a5ae3f6..e216c1773 100644
--- a/packages/db/src/schema/status_reports/status_reports.ts
+++ b/packages/db/src/schema/status_reports/status_reports.ts
@@ -37,7 +37,7 @@ export const statusReport = sqliteTable("status_report", {
export const statusReportUpdate = sqliteTable("status_report_update", {
id: integer("id").primaryKey(),
- status: text("status", statusReportStatus).notNull(),
+ status: text("status", { enum: statusReportStatus }).notNull(),
date: integer("date", { mode: "timestamp" }).notNull(),
message: text("message").notNull(),
diff --git a/packages/emails/emails/monitor-alert.tsx b/packages/emails/emails/monitor-alert.tsx
index 228538780..90e204661 100644
--- a/packages/emails/emails/monitor-alert.tsx
+++ b/packages/emails/emails/monitor-alert.tsx
@@ -20,14 +20,15 @@ import { Layout } from "./_components/layout";
import { colors, styles } from "./_components/styles";
const MonitorAlertSchema = z.object({
- type: z.enum(["degraded", "up", "down"]),
+ type: z.enum(["degraded", "alert", "recovery"]),
name: z.string().optional(),
url: z.string().optional(),
method: z.string().optional(),
status: z.string().optional(),
latency: z.string().optional(),
- location: z.string().optional(),
+ region: z.string().optional(),
timestamp: z.string().optional(),
+ message: z.string().optional(),
});
export type MonitorAlertProps = z.infer<typeof MonitorAlertSchema>;
@@ -37,12 +38,12 @@ function getIcon(type: MonitorAlertProps["type"]): {
color: string;
} {
switch (type) {
- case "up":
+ case "recovery":
return {
src: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLWNoZWNrIj48cGF0aCBkPSJNMjAgNiA5IDE3bC01LTUiLz48L3N2Zz4=",
color: colors.success,
};
- case "down":
+ case "alert":
return {
src: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLXgiPjxwYXRoIGQ9Ik0xOCA2IDYgMTgiLz48cGF0aCBkPSJtNiA2IDEyIDEyIi8+PC9zdmc+",
color: colors.danger,
@@ -58,9 +59,7 @@ function getIcon(type: MonitorAlertProps["type"]): {
const MonitorAlertEmail = (props: MonitorAlertProps) => (
<Html>
<Head />
- <Preview>
- A fine-grained personal access token has been added to your account
- </Preview>
+ <Preview>Your monitor's status is: {props.type}</Preview>
<Body style={styles.main}>
<Layout>
<Container
@@ -108,28 +107,23 @@ const MonitorAlertEmail = (props: MonitorAlertProps) => (
</Text>
</Column>
</Row>
+ {/* REMINDER: no status code for TCP monitors */}
+ {props.status ? (
+ <Row style={styles.row}>
+ <Column>
+ <Text style={styles.bold}>Status</Text>
+ </Column>
+ <Column style={{ textAlign: "right" }}>
+ <Text>{props.status}</Text>
+ </Column>
+ </Row>
+ ) : null}
<Row style={styles.row}>
<Column>
- <Text style={styles.bold}>Status</Text>
+ <Text style={styles.bold}>Region</Text>
</Column>
<Column style={{ textAlign: "right" }}>
- <Text>{props.status}</Text>
- </Column>
- </Row>
- <Row style={styles.row}>
- <Column>
- <Text style={styles.bold}>Latency</Text>
- </Column>
- <Column style={{ textAlign: "right" }}>
- <Text>{props.latency}</Text>
- </Column>
- </Row>
- <Row style={styles.row}>
- <Column>
- <Text style={styles.bold}>Location</Text>
- </Column>
- <Column style={{ textAlign: "right" }}>
- <Text>{props.location}</Text>
+ <Text>{props.region}</Text>
</Column>
</Row>
<Row style={styles.row}>
@@ -140,6 +134,16 @@ const MonitorAlertEmail = (props: MonitorAlertProps) => (
<Text>{props.timestamp}</Text>
</Column>
</Row>
+ {props.message ? (
+ <Row style={styles.row}>
+ <Column>
+ <Text>
+ {props.message?.slice(0, 200)}
+ {props.message?.length > 200 ? "..." : ""}
+ </Text>
+ </Column>
+ </Row>
+ ) : null}
<Row style={styles.row}>
<Column>
<Text style={{ textAlign: "center" }}>
@@ -155,14 +159,16 @@ const MonitorAlertEmail = (props: MonitorAlertProps) => (
);
MonitorAlertEmail.PreviewProps = {
- type: "up",
+ type: "alert",
name: "Ping Pong",
url: "https://openstatus.dev/ping",
method: "GET",
status: "200",
latency: "300ms",
- location: "San Francisco",
+ region: "Amsterdam, Netherlands",
timestamp: "2021-10-13T17:29:00Z",
+ message:
+ "This is a very long test message that will be truncated. Just testing it for the preview. Veryy veryy long message.",
} satisfies MonitorAlertProps;
export default MonitorAlertEmail;
diff --git a/packages/emails/emails/status-report.tsx b/packages/emails/emails/status-report.tsx
index e05189e8b..d739303e8 100644
--- a/packages/emails/emails/status-report.tsx
+++ b/packages/emails/emails/status-report.tsx
@@ -16,6 +16,7 @@ import { colors, styles } from "./_components/styles";
export const StatusReportSchema = z.object({
pageTitle: z.string(),
+ // statusReportStatus from db
status: z.enum(["investigating", "identified", "monitoring", "resolved"]),
date: z.string(),
message: z.string(),
@@ -91,7 +92,7 @@ function StatusReportEmail({
</Column>
<Column style={{ textAlign: "right" }}>
<Text style={{ flexWrap: "wrap", wordWrap: "break-word" }}>
- {monitors.join(", ")}
+ {monitors.length > 0 ? monitors.join(", ") : "N/A"}
</Text>
</Column>
</Row>
@@ -112,7 +113,7 @@ StatusReportEmail.PreviewProps = {
pageTitle: "OpenStatus Status",
reportTitle: "API Unavaible",
status: "investigating",
- date: "2021-07-19",
+ date: new Date().toISOString(),
message:
"The API is down, including the webhook. We are actively investigating the issue and will provide updates as soon as possible.",
monitors: ["OpenStatus API", "OpenStatus Webhook"],
diff --git a/packages/emails/src/client.tsx b/packages/emails/src/client.tsx
index 35d87d897..07a0ae57c 100644
--- a/packages/emails/src/client.tsx
+++ b/packages/emails/src/client.tsx
@@ -42,17 +42,21 @@ export class EmailClient {
}
}
- public async sendStatusReportUpdate(req: StatusReportProps & { to: string }) {
+ public async sendStatusReportUpdate(
+ req: StatusReportProps & { to: string[] },
+ ) {
if (process.env.NODE_ENV === "development") return;
try {
const html = await render(<StatusReportEmail {...req} />);
- const result = await this.client.emails.send({
- from: `${req.pageTitle} <[email protected]>`,
- subject: req.reportTitle,
- to: req.to,
- html,
- });
+ const result = await this.client.batch.send(
+ req.to.map((subscriber) => ({
+ from: `${req.pageTitle} <[email protected]>`,
+ subject: req.reportTitle,
+ to: subscriber,
+ html,
+ })),
+ );
if (!result.error) {
console.log(`Sent status report update email to ${req.to}`);
@@ -62,7 +66,8 @@ export class EmailClient {
throw result.error;
} catch (err) {
console.error(
- `Error sending status report update email to ${req.to}: ${err}`,
+ `Error sending status report update email to ${req.to}`,
+ err,
);
}
}
@@ -86,7 +91,7 @@ export class EmailClient {
throw result.error;
} catch (err) {
- console.error(`Error sending team invitation email to ${req.to}: ${err}`);
+ console.error(`Error sending team invitation email to ${req.to}`, err);
}
}
@@ -109,7 +114,7 @@ export class EmailClient {
throw result.error;
} catch (err) {
- console.error(`Error sending monitor alert to ${req.to}: ${err}`);
+ console.error(`Error sending monitor alert to ${req.to}`, err);
}
}
@@ -134,7 +139,7 @@ export class EmailClient {
throw result.error;
} catch (err) {
- console.error(`Error sending page subscription to ${req.to}: ${err}`);
+ console.error(`Error sending page subscription to ${req.to}`, err);
}
}
}
diff --git a/packages/notifications/discord/src/index.ts b/packages/notifications/discord/src/index.ts
index 290a2f204..e6c1eb50e 100644
--- a/packages/notifications/discord/src/index.ts
+++ b/packages/notifications/discord/src/index.ts
@@ -1,6 +1,6 @@
import type { Monitor, Notification } from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { DataSchema } from "./schema";
-
const postToWebhook = async (content: string, webhookUrl: string) => {
await fetch(webhookUrl, {
method: "POST",
@@ -29,6 +29,8 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { discord: webhookUrl } = notificationData; // webhook url
@@ -61,6 +63,8 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { discord: webhookUrl } = notificationData; // webhook url
@@ -93,6 +97,8 @@ export const sendDegraded = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { discord: webhookUrl } = notificationData; // webhook url
diff --git a/packages/notifications/email/package.json b/packages/notifications/email/package.json
index 91976dc84..ca0258518 100644
--- a/packages/notifications/email/package.json
+++ b/packages/notifications/email/package.json
@@ -7,6 +7,7 @@
"@openstatus/db": "workspace:*",
"@openstatus/emails": "workspace:*",
"@openstatus/tinybird": "workspace:*",
+ "@openstatus/utils": "workspace:*",
"@react-email/components": "0.0.31",
"@react-email/render": "1.0.3",
"@t3-oss/env-core": "0.7.0",
diff --git a/packages/notifications/email/src/index.ts b/packages/notifications/email/src/index.ts
index bb31334af..81c4a412b 100644
--- a/packages/notifications/email/src/index.ts
+++ b/packages/notifications/email/src/index.ts
@@ -4,44 +4,12 @@ import {
emailDataSchema,
} from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
+import { EmailClient } from "@openstatus/emails/src/client";
+import { flyRegionsDict } from "@openstatus/utils";
import { env } from "../env";
-async function send({
- subject,
- html,
- email,
- id,
- type,
-}: {
- subject: string;
- html: string;
- email: string;
- id: number;
- type: "recovered" | "alert" | "degraded";
-}) {
- const res = await fetch("https://api.resend.com/emails", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${env.RESEND_API_KEY}`,
- },
- body: JSON.stringify({
- to: email,
- from: "Notifications <[email protected]>",
- subject,
- html,
- }),
- });
-
- if (res.ok) {
- const data = await res.json();
- console.log(data);
- // return NextResponse.json(data);
- }
- if (!res.ok) {
- console.log(`Error sending ${type} email ${id}`);
- }
-}
+const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
export const sendAlert = async ({
monitor,
@@ -49,6 +17,8 @@ export const sendAlert = async ({
statusCode,
message,
cronTimestamp,
+ latency,
+ region,
}: {
monitor: Monitor;
notification: Notification;
@@ -56,33 +26,33 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ region?: Region;
+ latency?: number;
}) => {
const config = emailDataSchema.safeParse(JSON.parse(notification.data));
if (!config.success) return;
- await send({
- id: monitor.id,
+ await emailClient.sendMonitorAlert({
+ name: monitor.name,
type: "alert",
- email: config.data.email,
- subject: `🚨 Alert ${monitor.name}`,
- html: `
- <p>Hi,</p>
- <p>Your monitor <strong>${monitor.name}</strong> is down.</p>
- <p>URL: ${monitor.url}</p>
- ${
- statusCode
- ? `<p>Status Code: ${statusCode}</p>`
- : `<p>Error message: ${message}</p>`
- }
- <p>Cron Timestamp: ${cronTimestamp} (${new Date(cronTimestamp).toISOString()})</p>
- <p>OpenStatus πŸ“</p>`,
+ to: config.data.email,
+ url: monitor.url,
+ status: statusCode?.toString(),
+ latency: latency ? `${latency}ms` : "N/A",
+ region: region ? flyRegionsDict[region].location : "N/A",
+ timestamp: new Date(cronTimestamp).toISOString(),
+ message,
});
};
export const sendRecovery = async ({
monitor,
notification,
+ statusCode,
+ cronTimestamp,
+ region,
+ latency,
}: {
monitor: Monitor;
notification: Notification;
@@ -90,49 +60,53 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ region?: Region;
+ latency?: number;
}) => {
const config = emailDataSchema.safeParse(JSON.parse(notification.data));
if (!config.success) return;
- send({
- id: monitor.id,
- type: "recovered",
- email: config.data.email,
- subject: `βœ… Recovered ${monitor.name}`,
- html: `
- <p>Hi,</p>
- <p>Your monitor <strong>${monitor.name}</strong> is up again.</p>
- <p>URL: ${monitor.url}</p>
- <p>OpenStatus πŸ“</p>
- `,
+ await emailClient.sendMonitorAlert({
+ name: monitor.name,
+ type: "recovery",
+ to: config.data.email,
+ url: monitor.url,
+ status: statusCode?.toString(),
+ latency: latency ? `${latency}ms` : "N/A",
+ region: region ?? "N/A",
+ timestamp: new Date(cronTimestamp).toISOString(),
});
};
export const sendDegraded = async ({
monitor,
notification,
+ statusCode,
+ cronTimestamp,
+ region,
+ latency,
}: {
monitor: Monitor;
notification: Notification;
statusCode?: number;
message?: string;
cronTimestamp: number;
+ region?: Region;
+ latency?: number;
}) => {
const config = emailDataSchema.safeParse(JSON.parse(notification.data));
if (!config.success) return;
- send({
- id: monitor.id,
+ await emailClient.sendMonitorAlert({
+ name: monitor.name,
type: "degraded",
- email: config.data.email,
- subject: `⚠️ Degraded ${monitor.name}`,
- html: `
- <p>Hi,</p>
- <p>Your monitor <strong>${monitor.name}</strong> is taking longer than expected to respond</p>
- <p>URL: ${monitor.url}</p>
- <p>OpenStatus πŸ“</p>
- `,
+ to: config.data.email,
+ url: monitor.url,
+ status: statusCode?.toString(),
+ latency: latency ? `${latency}ms` : "N/A",
+ region: region ?? "N/A",
+ timestamp: new Date(cronTimestamp).toISOString(),
});
};
diff --git a/packages/notifications/opsgenie/src/index.ts b/packages/notifications/opsgenie/src/index.ts
index 5ba3a694a..57fa5243d 100644
--- a/packages/notifications/opsgenie/src/index.ts
+++ b/packages/notifications/opsgenie/src/index.ts
@@ -1,4 +1,5 @@
import type { Monitor, Notification } from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { OpsGeniePayloadAlert, OpsGenieSchema } from "./schema";
export const sendAlert = async ({
@@ -15,6 +16,8 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const { opsgenie } = OpsGenieSchema.parse(JSON.parse(notification.data));
const { name } = monitor;
@@ -62,6 +65,8 @@ export const sendDegraded = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const { opsgenie } = OpsGenieSchema.parse(JSON.parse(notification.data));
const { name } = monitor;
@@ -113,6 +118,8 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const { opsgenie } = OpsGenieSchema.parse(JSON.parse(notification.data));
diff --git a/packages/notifications/pagerduty/src/index.ts b/packages/notifications/pagerduty/src/index.ts
index b1f689f4e..64eb583f2 100644
--- a/packages/notifications/pagerduty/src/index.ts
+++ b/packages/notifications/pagerduty/src/index.ts
@@ -1,5 +1,6 @@
import type { Monitor, Notification } from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import {
PagerDutySchema,
resolveEventPayloadSchema,
@@ -20,6 +21,8 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = PagerDutySchema.parse(JSON.parse(notification.data));
const { name } = monitor;
@@ -66,6 +69,8 @@ export const sendDegraded = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = PagerDutySchema.parse(JSON.parse(notification.data));
const { name } = monitor;
@@ -117,6 +122,8 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = PagerDutySchema.parse(JSON.parse(notification.data));
@@ -162,7 +169,7 @@ export const sendTest = async ({
},
});
- const res = await fetch("https://events.pagerduty.com/v2/enqueue", {
+ const _res = await fetch("https://events.pagerduty.com/v2/enqueue", {
method: "POST",
body: JSON.stringify(event),
});
diff --git a/packages/notifications/slack/src/index.ts b/packages/notifications/slack/src/index.ts
index 5205a3c92..e02a018c0 100644
--- a/packages/notifications/slack/src/index.ts
+++ b/packages/notifications/slack/src/index.ts
@@ -1,4 +1,5 @@
import type { Monitor, Notification } from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { DataSchema } from "./schema";
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
@@ -29,6 +30,8 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { slack: webhookUrl } = notificationData; // webhook url
@@ -88,6 +91,8 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ region?: Region;
+ latency?: number;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { slack: webhookUrl } = notificationData; // webhook url
@@ -139,6 +144,8 @@ export const sendDegraded = async ({
statusCode?: number;
message?: string;
cronTimestamp: number;
+ region?: Region;
+ latency?: number;
}) => {
const notificationData = DataSchema.parse(JSON.parse(notification.data));
const { slack: webhookUrl } = notificationData; // webhook url
diff --git a/packages/notifications/twillio-sms/src/index.ts b/packages/notifications/twillio-sms/src/index.ts
index 0b845a18c..e13d51ff6 100644
--- a/packages/notifications/twillio-sms/src/index.ts
+++ b/packages/notifications/twillio-sms/src/index.ts
@@ -1,5 +1,6 @@
import type { Monitor, Notification } from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { env } from "./env";
import { SmsConfigurationSchema } from "./schema/config";
@@ -17,6 +18,8 @@ export const sendAlert = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = SmsConfigurationSchema.parse(
JSON.parse(notification.data),
@@ -68,6 +71,8 @@ export const sendRecovery = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = SmsConfigurationSchema.parse(
JSON.parse(notification.data),
@@ -112,6 +117,8 @@ export const sendDegraded = async ({
message?: string;
incidentId?: string;
cronTimestamp: number;
+ latency?: number;
+ region?: Region;
}) => {
const notificationData = SmsConfigurationSchema.parse(
JSON.parse(notification.data),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fdffef1c6..e7d8e8f33 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -171,7 +171,7 @@ importers:
version: link:../../packages/utils
'@scalar/hono-api-reference':
specifier: 0.5.131
'@t3-oss/env-core':
specifier: 0.7.1
@@ -286,7 +286,7 @@ importers:
'@sentry/nextjs':
specifier: 8.46.0
'@stripe/stripe-js':
specifier: 2.1.6
version: 2.1.6
@@ -313,7 +313,7 @@ importers:
'@trpc/next':
specifier: 11.0.0-rc.666
'@trpc/react-query':
specifier: 11.0.0-rc.666
@@ -361,19 +361,19 @@ importers:
version: 5.0.7
next:
specifier: 15.1.7
next-auth:
specifier: 5.0.0-beta.25
next-plausible:
specifier: 3.12.4
next-themes:
specifier: 0.2.1
nuqs:
specifier: 2.2.3
random-word-slugs:
specifier: 0.1.7
version: 0.1.7
@@ -443,7 +443,7 @@ importers:
'@content-collections/next':
specifier: 0.2.4
'@openstatus/tsconfig':
specifier: workspace:*
version: link:../../packages/tsconfig
@@ -761,6 +761,9 @@ importers:
'@openstatus/tinybird':
specifier: workspace:*
version: link:../../tinybird
+ '@openstatus/utils':
+ specifier: workspace:*
+ version: link:../../utils
'@react-email/components':
specifier: 0.0.31
@@ -11470,11 +11473,11 @@ snapshots:
- acorn
- supports-color
dependencies:
'@content-collections/core': 0.7.3([email protected])
'@content-collections/integrations': 0.2.1(@content-collections/[email protected]([email protected]))
'@cspotcode/[email protected]':
dependencies:
@@ -12019,9 +12022,9 @@ snapshots:
protobufjs: 7.2.5
yargs: 17.7.2
dependencies:
dependencies:
@@ -13652,9 +13655,9 @@ snapshots:
'@rollup/[email protected]':
optional: true
dependencies:
- '@headlessui/tailwindcss': 0.2.0([email protected]([email protected](@types/[email protected])([email protected])))
+ '@headlessui/tailwindcss': 0.2.0([email protected]([email protected](@types/[email protected])([email protected])))
'@headlessui/vue': 1.7.22([email protected]([email protected]))
'@scalar/draggable': 0.1.4([email protected])
@@ -13690,11 +13693,11 @@ snapshots:
- typescript
- vitest
dependencies:
'@floating-ui/vue': 1.1.1([email protected]([email protected]))
'@headlessui/vue': 1.7.22([email protected]([email protected]))
'@scalar/oas-utils': 0.2.26([email protected])
'@scalar/openapi-parser': 0.7.2
@@ -13779,9 +13782,9 @@ snapshots:
transitivePeerDependencies:
- typescript
dependencies:
hono: 4.5.3
transitivePeerDependencies:
- '@jest/globals'
@@ -13999,7 +14002,7 @@ snapshots:
'@sentry/types': 8.9.2
'@sentry/utils': 8.9.2
dependencies:
'@opentelemetry/api': 1.9.0
'@opentelemetry/semantic-conventions': 1.28.0
@@ -14012,7 +14015,7 @@ snapshots:
'@sentry/vercel-edge': 8.46.0
'@sentry/webpack-plugin': 2.22.7([email protected])([email protected]([email protected]))
chalk: 3.0.0
resolve: 1.22.8
rollup: 3.29.5
stacktrace-parser: 0.1.10
@@ -14640,11 +14643,11 @@ snapshots:
'@trpc/server': 11.0.0-rc.666([email protected])
typescript: 5.6.2
dependencies:
'@trpc/client': 11.0.0-rc.666(@trpc/[email protected]([email protected]))([email protected])
'@trpc/server': 11.0.0-rc.666([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
typescript: 5.6.2
@@ -18648,27 +18651,15 @@ snapshots:
- dependencies:
- '@auth/core': 0.37.2
- react: 19.0.0
-
dependencies:
'@auth/core': 0.37.2
react: 19.0.0
dependencies:
- react: 19.0.0
- react-dom: 19.0.0([email protected])
-
- dependencies:
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -18704,32 +18695,6 @@ snapshots:
- '@babel/core'
- babel-plugin-macros
- dependencies:
- '@next/env': 15.1.7
- '@swc/counter': 0.1.3
- '@swc/helpers': 0.5.15
- busboy: 1.6.0
- caniuse-lite: 1.0.30001689
- postcss: 8.4.31
- react: 19.0.0
- react-dom: 19.0.0([email protected])
- styled-jsx: 5.1.6(@babel/[email protected])([email protected])
- optionalDependencies:
- '@next/swc-darwin-arm64': 15.1.7
- '@next/swc-darwin-x64': 15.1.7
- '@next/swc-linux-arm64-gnu': 15.1.7
- '@next/swc-linux-arm64-musl': 15.1.7
- '@next/swc-linux-x64-gnu': 15.1.7
- '@next/swc-linux-x64-musl': 15.1.7
- '@next/swc-win32-arm64-msvc': 15.1.7
- '@next/swc-win32-x64-msvc': 15.1.7
- '@opentelemetry/api': 1.9.0
- sharp: 0.33.5
- transitivePeerDependencies:
- - '@babel/core'
- - babel-plugin-macros
-
dependencies:
'@next/env': 15.1.7
@@ -18740,7 +18705,7 @@ snapshots:
postcss: 8.4.31
react: 19.0.0
react-dom: 19.0.0([email protected])
- styled-jsx: 5.1.6([email protected])
+ styled-jsx: 5.1.6(@babel/[email protected])([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 15.1.7
'@next/swc-darwin-x64': 15.1.7
@@ -18833,12 +18798,12 @@ snapshots:
dependencies:
boolbase: 1.0.0
dependencies:
mitt: 3.0.1
react: 19.0.0
optionalDependencies:
@@ -19187,21 +19152,21 @@ snapshots:
postcss: 8.4.38
ts-node: 10.9.2(@types/[email protected])([email protected])
dependencies:
lilconfig: 3.1.3
yaml: 2.6.1
optionalDependencies:
postcss: 8.5.2
- ts-node: 10.9.2(@types/[email protected])([email protected])
+ ts-node: 10.9.2(@types/[email protected])([email protected])
dependencies:
lilconfig: 3.1.3
yaml: 2.6.1
optionalDependencies:
postcss: 8.5.2
- ts-node: 10.9.2(@types/[email protected])([email protected])
+ ts-node: 10.9.2(@types/[email protected])([email protected])
dependencies:
@@ -20351,18 +20316,6 @@ snapshots:
optionalDependencies:
'@babel/core': 7.24.5
- dependencies:
- client-only: 0.0.1
- react: 19.0.0
- optionalDependencies:
- '@babel/core': 7.26.0
-
- dependencies:
- client-only: 0.0.1
- react: 19.0.0
-
dependencies:
'@jridgewell/gen-mapping': 0.3.5
@@ -20426,7 +20379,7 @@ snapshots:
dependencies:
dependencies:
'@alloc/quick-lru': 5.2.0
arg: 5.0.2
@@ -20445,7 +20398,7 @@ snapshots:
postcss: 8.5.2
postcss-import: 15.1.0([email protected])
postcss-js: 4.0.1([email protected])
postcss-nested: 6.2.0([email protected])
postcss-selector-parser: 6.1.2
resolve: 1.22.9
@@ -20453,7 +20406,7 @@ snapshots:
transitivePeerDependencies:
- ts-node
dependencies:
'@alloc/quick-lru': 5.2.0
arg: 5.0.2
@@ -20472,7 +20425,7 @@ snapshots:
postcss: 8.5.2
postcss-import: 15.1.0([email protected])
postcss-js: 4.0.1([email protected])
postcss-nested: 6.2.0([email protected])
postcss-selector-parser: 6.1.2
resolve: 1.22.9
@@ -20726,26 +20679,26 @@ snapshots:
v8-compile-cache-lib: 3.0.1
yn: 3.1.1
dependencies:
'@cspotcode/source-map-support': 0.8.1
'@tsconfig/node10': 1.0.11
'@tsconfig/node12': 1.0.11
'@tsconfig/node14': 1.0.3
'@tsconfig/node16': 1.0.4
- '@types/node': 22.10.2
+ '@types/node': 20.8.0
acorn: 8.11.3
acorn-walk: 8.3.2
arg: 4.1.3
create-require: 1.1.1
diff: 4.0.2
make-error: 1.3.6
- typescript: 5.6.2
+ typescript: 5.7.2
v8-compile-cache-lib: 3.0.1
yn: 3.1.1
optional: true
dependencies:
'@cspotcode/source-map-support': 0.8.1
'@tsconfig/node10': 1.0.11
@@ -20759,7 +20712,7 @@ snapshots:
create-require: 1.1.1
diff: 4.0.2
make-error: 1.3.6
- typescript: 5.7.2
+ typescript: 5.6.2
v8-compile-cache-lib: 3.0.1
yn: 3.1.1
optional: true