Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/openstatusHQ/openstatus. ๐ซ Status page with uptime monitoring & API monitoring as code ๐ซ openstatus.dev
bun drizzle-orm monitoring monitoring-as-code nextjs observability on-call open-source shadcn-ui status-page statuspage synthetic-monitoring tinybird turso uptime uptime-checker uptime-monitor
Something went wrong. Try again.
9.5 kB ยท 338 lines
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339import { type EventProps, type IdentifyProps, parseInputToProps, setupAnalytics,} from "@openstatus/analytics";import { db } from "@openstatus/db";import type { User, Workspace } from "@openstatus/db/src/schema";import { TRPCError, initTRPC } from "@trpc/server";import { type NextRequest, after } from "next/server.js";import superjson from "superjson";import { ZodError, treeifyError } from "zod";
import { type ResolveActiveWorkspaceResult, resolveActiveWorkspace, resolveUserWorkspaces,} from "./auth/resolve-active-workspace";
// Generic session type that works with both User and Viewertype Session = { user?: { id?: string | null; email?: string | null; } | null;} | null;
/** * 1. CONTEXT * * This section defines the "contexts" that are available in the backend API * * These allow you to access things like the database, the session, etc, when * processing a request * */type CreateContextOptions = { session: Session | null; workspace?: Workspace | null; workspaces?: Workspace[] | null; user?: User | null; req?: NextRequest; metadata?: { userAgent?: string; location?: string; }; resolveWorkspace?: () => Promise<ResolveActiveWorkspaceResult>;};
type Meta = { track?: EventProps; trackProps?: string[];};
/** * This helper generates the "internals" for a tRPC context. If you need to use * it, you can export it from here * * Examples of things you may need it for: * - testing, so we dont have to mock Next.js' req/res * - trpc's `createSSGHelpers` where we don't have req/res * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts */export const createInnerTRPCContext = (opts: CreateContextOptions) => { return { ...opts, db, };};
/** * This is the actual context you'll use in your router. It will be used to * process every request that goes through your tRPC endpoint * @link https://trpc.io/docs/context */export const createTRPCContext = async (opts: { req: NextRequest; serverSideCall?: boolean; auth?: () => Promise<Session>;}) => { // Use provided auth function or return null session const session = opts.auth ? await opts.auth() : null; const workspace = null; const workspaces = null; const user = null;
// Context is per HTTP request while middleware runs per procedure โ a // batched request would otherwise re-run the same userรworkspaces query // once per procedure. Zero-arg by design: userId/slug are bound here so // the first call's promise is safe to share across the whole batch. let resolution: Promise<ResolveActiveWorkspaceResult> | undefined; const resolveWorkspace = () => (resolution ??= resolveActiveWorkspace({ userId: Number(session?.user?.id), workspaceSlug: opts.req.cookies.get("workspace-slug")?.value, }));
return createInnerTRPCContext({ session, workspace, workspaces, user, resolveWorkspace, req: opts.req, metadata: { userAgent: opts.req.headers.get("user-agent") ?? undefined, location: opts.req.headers.get("x-forwarded-for") ?? process.env.VERCEL_REGION ?? undefined, }, });};
export type Context = Awaited<ReturnType<typeof createTRPCContext>>;
/** * 2. INITIALIZATION * * This is where the trpc api is initialized, connecting the context and * transformer */export const t = initTRPC .context<Context>() .meta<Meta>() .create({ transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? treeifyError(error.cause) : null, }, }; }, });
/** * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) * * These are the pieces you use to build your tRPC API. You should import these * a lot in the /src/server/api/routers folder */
/** * This is how you create new routers and subrouters in your tRPC API * @see https://trpc.io/docs/router */export const createTRPCRouter = t.router;export const mergeRouters = t.mergeRouters;
const timingMiddleware = t.middleware(async (opts) => { const start = performance.now(); const result = await opts.next(); if (process.env.NODE_ENV !== "test") { const durationMs = Math.round(performance.now() - start); console.info( JSON.stringify({ msg: "trpc.timing", path: opts.path, type: opts.type, durationMs, ok: result.ok, region: process.env.VERCEL_REGION, }), ); } return result;});
/** * Public (unauthed) procedure * * This is the base piece you use to build new queries and mutations on your * tRPC API. It does not guarantee that a user querying is authorized, but you * can still access user session data if they are logged in */export const publicProcedure = t.procedure.use(timingMiddleware);
/** * Reusable middleware that enforces users are logged in before running the * procedure */const enforceUserIsAuthed = t.middleware(async (opts) => { const { ctx } = opts; if (!ctx.session?.user?.id) { throw new TRPCError({ code: "UNAUTHORIZED" }); }
// Test escape hatch: when NODE_ENV=test and the caller already // populated `workspace` + `user` on the inner context (via // `createInnerTRPCContext` in a test helper), trust it and skip the // DB round-trip. Without this, router-level limit tests that pass // an override `workspace.limits` object see it immediately replaced // by the seeded team-plan workspace below โ the override never // reaches the service and the test asserts against the wrong plan. if ( process.env.NODE_ENV === "test" && ctx.workspace != null && ctx.user != null ) { return opts.next({ ctx: { ...ctx, user: ctx.user, workspace: ctx.workspace, workspaces: ctx.workspaces ?? [ctx.workspace], }, }); }
/** * The active "workspace-slug" cookie is set in the dashboard middleware * for server requests and in `<WorkspaceClientCookie />` for client * requests; we read the same cookie either way. */ const workspaceSlug = ctx.req?.cookies.get("workspace-slug")?.value;
const resolved = await (ctx.resolveWorkspace ? ctx.resolveWorkspace() : resolveActiveWorkspace({ userId: Number(ctx.session.user.id), workspaceSlug, }));
if (!resolved.ok) { throw new TRPCError({ code: "UNAUTHORIZED", message: resolved.error.kind === "user_not_found" ? "User Not Found" : "Workspace Not Found", }); }
const { user, workspace, workspaces } = resolved.value;
if (workspace.slug !== workspaceSlug) { // properly set the workspace slug cookie ctx.req?.cookies.set("workspace-slug", workspace.slug); }
const result = await opts.next({ ctx: { ...ctx, user, workspace, workspaces }, });
if (process.env.NODE_ENV === "test") { return result; }
// REMINDER: We only track the event if the request was successful if (!result.ok) { return result; }
// REMINDER: We only track the event if the request was successful // REMINDER: We are not blocking the request after(async () => { const { ctx, meta, getRawInput } = opts;
if (meta?.track) { let identify: IdentifyProps = { userAgent: ctx.metadata?.userAgent, location: ctx.metadata?.location, };
if (user && workspace) { identify = { ...identify, userId: `usr_${user.id}`, email: user.email || undefined, workspaceId: String(workspace.id), plan: workspace.plan, }; }
const analytics = await setupAnalytics(identify); const rawInput = await getRawInput(); const additionalProps = parseInputToProps(rawInput, meta.trackProps);
await analytics.track({ ...meta.track, ...additionalProps }); } });
return result;});
/** * Middleware to parse form data and put it in the rawInput */export const formdataMiddleware = t.middleware(async (opts) => { const formData = await opts.ctx.req?.formData?.(); if (!formData) throw new TRPCError({ code: "BAD_REQUEST" });
return opts.next({ input: formData, });});
/** * Signed-in user without an active workspace. `ctx.workspaces` may be empty; * `ctx.workspace` stays null. Only for surfaces that must render for a user * who belongs to no workspace โ everything else uses `protectedProcedure`. */const enforceUserIsSignedIn = t.middleware(async (opts) => { const { ctx } = opts; if (!ctx.session?.user?.id) { throw new TRPCError({ code: "UNAUTHORIZED" }); } const resolved = await resolveUserWorkspaces({ userId: Number(ctx.session.user.id), }); if (!resolved) { throw new TRPCError({ code: "UNAUTHORIZED", message: "User Not Found" }); } return opts.next({ ctx: { ...ctx, user: resolved.user, workspaces: resolved.workspaces }, });});
export const userProcedure = t.procedure .use(timingMiddleware) .use(enforceUserIsSignedIn);
/** * Protected (authed) procedure * * If you want a query or mutation to ONLY be accessible to logged in users, use * this. It verifies the session is valid and guarantees ctx.session.user is not * null * * @see https://trpc.io/docs/procedures */export const protectedProcedure = t.procedure .use(timingMiddleware) .use(enforceUserIsAuthed);