Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨🏢 Add Sentry #603

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/admin.checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ jobs:
context: .
file: ./apps/admin/Dockerfile
tags: registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.head_ref }}-${{ github.sha }}
secrets: "SENTRY_AUTH_TOKEN=${{ secrets.SENTRY_AUTH_TOKEN }}"
build-args: APPLICATION_VERSION=${{ github.sha }}
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new

Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/admin.deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ jobs:
file: ./apps/admin/Dockerfile
push: true
tags: registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}
secrets: "SENTRY_AUTH_TOKEN=${{ secrets.SENTRY_AUTH_TOKEN }}"
build-args: APPLICATION_VERSION=${{ github.sha }}
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new

Expand Down
1 change: 1 addition & 0 deletions apps/admin/.env
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
ALGOLIA_ADMIN_KEY="mock-key"
ALGOLIA_ID="mock-id"
APPLICATION_TOKEN="admin-token"
APPLICATION_VERSION="local-version"
CLOUDINARY_API_KEY="mock-api-key"
CLOUDINARY_API_SECRET="mock-api-secret"
CLOUDINARY_CLOUD_NAME="mock-cloud-name"
Expand Down
6 changes: 5 additions & 1 deletion apps/admin/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
ARG APPLICATION_VERSION

# base node image
FROM node:22.11-bullseye-slim as base

Expand Down Expand Up @@ -60,14 +62,16 @@ ADD ./libs/search-params-io ./libs/search-params-io
ADD ./libs/tailwind-animation ./libs/tailwind-animation
ADD ./libs/zod-utils ./libs/zod-utils
ADD ./apps/admin ./apps/admin
RUN yarn --cwd ./apps/admin build
RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN,env=SENTRY_AUTH_TOKEN \
yarn --cwd ./apps/admin build

# Finally, build the production image with minimal footprint
FROM base
COPY --from=production-deps /workspace/node_modules ./node_modules
COPY --from=production-deps /workspace/apps/admin/node_modules ./apps/admin/node_modules
COPY --from=build /workspace/node_modules/.prisma ./node_modules/.prisma
COPY --from=build /workspace/apps/admin/build ./apps/admin/build
COPY --from=build /workspace/apps/admin/server.js ./apps/admin/
ADD ./prisma ./prisma
ADD ./apps/admin ./apps/admin

Expand Down
18 changes: 15 additions & 3 deletions apps/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
"dev:icons": "yarn generate:icons --watch",
"dev:remix": "node -r dotenv-flow/config ./node_modules/.bin/remix vite:dev --host",
"dev:theme": "tsx watch --clear-screen=false ./scripts/generate-theme.ts",
"build": "run-s build:icons build:theme build:remix",
"build": "run-s build:icons build:theme build:server build:remix",
"build:icons": "yarn generate:icons --minify",
"build:remix": "remix vite:build",
"build:server": "tsc -p ./tsconfig.server.json",
"build:theme": "yarn generate:theme",
"start": "remix-serve ./build/server/index.js"
"start": "node server.js ./build/server/index.js"
},
"dependencies": {
"@algolia/client-search": "^4.22.1",
Expand All @@ -44,18 +45,23 @@
"@radix-ui/react-popover": "^1.0.6",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-visually-hidden": "^1.0.3",
"@remix-run/express": "~2.9.2",
"@remix-run/node": "~2.9.2",
"@remix-run/react": "~2.9.2",
"@remix-run/serve": "~2.9.2",
"@sentry/remix": "^8.37.1",
"@sentry/vite-plugin": "^3.1.1",
"@tailwindcss/container-queries": "^0.1.1",
"algoliasearch": "^4.19.1",
"autosize": "^6.0.1",
"bowser": "^2.11.0",
"chokidar": "^3.5.3",
"cloudinary": "^2.2.0",
"compression": "^1.7.4",
"cookie-signature": "^1.2.1",
"croner": "^8.0.0",
"downshift": "^9.0.6",
"express": "^4.17.1",
"get-port": "^5.1.1",
"googleapis": "^144.0.0",
"history": "^5.3.0",
"isbot": "^5.1.8",
Expand All @@ -72,6 +78,7 @@
"metascraper-image": "^5.36.0",
"metascraper-publisher": "^5.36.0",
"metascraper-title": "^5.36.0",
"morgan": "^1.10.0",
"react": "^18.2.0",
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
Expand All @@ -81,6 +88,7 @@
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.0",
"remix-utils": "^7.5.0",
"source-map-support": "^0.5.21",
"tiny-invariant": "^1.3.1",
"uuid": "^9.0.0",
"zod": "^3.22.2",
Expand All @@ -92,17 +100,21 @@
"@remix-run/dev": "~2.9.2",
"@total-typescript/ts-reset": "^0.5.1",
"@types/autosize": "^4.0.1",
"@types/compression": "^1.7.0",
"@types/cookie-signature": "^1.1.0",
"@types/express": "^4.17.9",
"@types/lodash.chunk": "^4.2.7",
"@types/lodash.difference": "^4.5.7",
"@types/lodash.intersection": "^4.4.7",
"@types/lodash.isequal": "^4.5.6",
"@types/lodash.orderby": "^4.6.7",
"@types/lodash.zip": "^4.2.7",
"@types/luxon": "^3.3.1",
"@types/morgan": "^1.9.2",
"@types/node": "^22.8.7",
"@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7",
"@types/source-map-support": "^0.5.6",
"@types/uuid": "^9.0.2",
"autoprefixer": "^10.4.15",
"chokidar": "^3.5.3",
Expand Down
115 changes: 115 additions & 0 deletions apps/admin/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Copied from @remix-run/server.
*
* We can't use `installGlobals()` with @mjackson/form-data-parser which is
* automatically called by `@remix-run/server`.
*
* This is version is the same as we used, with only the following changes:
* - Calls to `installGlobals()` have be removed.
* - Code for `NODE_ENV="development"` have been removed. We use
* `remix vite:dev` in dev.
*
* @see https://github.com/mjackson/remix-the-web/issues/26
* @see https://github.com/remix-run/remix/blob/%40remix-run/serve%402.9.2/packages/remix-serve/cli.ts
*/

import { createRequestHandler } from "@remix-run/express";
import type { ServerBuild } from "@remix-run/node";
import compression from "compression";
import express from "express";
import getPort from "get-port";
import morgan from "morgan";
import { existsSync, readFileSync } from "node:fs";
import { networkInterfaces } from "node:os";
import { fileURLToPath } from "node:url";
import { install as installSourceMapSupport } from "source-map-support";

if (process.env.NODE_ENV !== "production") {
throw new Error("server.ts should only be run in NODE_ENV=production.");
}

installSourceMapSupport({
retrieveSourceMap: function (source) {
let match = source.startsWith("file://");
if (match) {
let filePath = fileURLToPath(source);
let sourceMapPath = `${filePath}.map`;
if (existsSync(sourceMapPath)) {
return {
url: source,
map: readFileSync(sourceMapPath, "utf8"),
};
}
}
return null;
},
});

run();

function parseNumber(raw?: string) {
if (raw === undefined) return undefined;
let maybe = Number(raw);
if (Number.isNaN(maybe)) return undefined;
return maybe;
}

async function run() {
let port = parseNumber(process.env.PORT) ?? (await getPort({ port: 3000 }));

let buildPathArg = process.argv[2];

if (!buildPathArg) {
console.error(`
Usage: remix-serve <server-build-path> - e.g. remix-serve build/index.js`);
process.exit(1);
}

let build = (await import(buildPathArg)) as ServerBuild;

let onListen = () => {
let address =
process.env.HOST ||
Object.values(networkInterfaces())
.flat()
.find((ip) => String(ip?.family).includes("4") && !ip?.internal)
?.address;

if (!address) {
console.log(`[remix-serve] http://localhost:${port}`);
} else {
console.log(
`[remix-serve] http://localhost:${port} (http://${address}:${port})`,
);
}
};

let app = express();
app.disable("x-powered-by");
app.use(compression());
app.use(
build.publicPath,
express.static(build.assetsBuildDirectory, {
immutable: true,
maxAge: "1y",
}),
);
app.use(express.static("public", { maxAge: "1h" }));
app.use(morgan("tiny"));

app.all(
"*",
createRequestHandler({
build,
mode: process.env.NODE_ENV,
}),
);

let server = process.env.HOST
? app.listen(port, process.env.HOST, onListen)
: app.listen(port, onListen);

["SIGTERM", "SIGINT"].forEach((signal) => {
process.once(signal, () => server?.close(console.error));
});
}
6 changes: 6 additions & 0 deletions apps/admin/src/core/data-display/error-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ import {
useLocation,
useRouteError,
} from "@remix-run/react";
import { captureRemixErrorBoundaryError } from "@sentry/remix";
import { useEffect } from "react";

export function ErrorPage() {
const error = useRouteError();
console.error("ErrorBoundary error", error);

useEffect(() => {
captureRemixErrorBoundaryError(error);
}, [error]);

const status = isRouteErrorResponse(error)
? asStatusCode(error.status)
: DEFAULT_STATUS_CODE;
Expand Down
17 changes: 17 additions & 0 deletions apps/admin/src/core/env.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export function checkEnv() {
*/
export function getClientEnv() {
return {
APPLICATION_VERSION: process.env.APPLICATION_VERSION,
RUNTIME_ENV: process.env.RUNTIME_ENV,
SENTRY_DSN: process.env.SENTRY_DSN,
SENTRY_ENABLE_LOCAL: process.env.SENTRY_ENABLE_LOCAL,
SENTRY_TRACES_SAMPLE_RATE: process.env.SENTRY_TRACES_SAMPLE_RATE,
SHOW_URL: process.env.SHOW_URL,
};
}
Expand All @@ -44,8 +49,20 @@ declare global {
}

const processEnvSchema = zu.object({
APPLICATION_VERSION: zu.string(),
GOOGLE_API_CLIENT_EMAIL: zu.string().optional(),
GOOGLE_API_PRIVATE_KEY: zu.string().optional(),
GOOGLE_DRIVE_ROOT_FOLDER_ID: zu.string(),
RUNTIME_ENV: zu.enum(["local", "production", "staging"]),
SENTRY_DSN: zu.string().optional(),
SENTRY_ENABLE_LOCAL: zu.enum(["false", "true"]).optional(),
SENTRY_TRACES_SAMPLE_RATE: zu.coerce
.number()
.min(0)
.max(1)
// Because we access the raw value and not the parsed one, we need to be
// sure the type remains string and not number.
.transform((value) => String(value))
.optional(),
SHOW_URL: zu.string(),
});
28 changes: 28 additions & 0 deletions apps/admin/src/core/monitoring.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useLocation, useMatches } from "@remix-run/react";
import {
browserTracingIntegration,
httpClientIntegration,
init,
} from "@sentry/remix";
import { useEffect } from "react";

export function initMonitoring() {
if (
CLIENT_ENV.SENTRY_DSN != null &&
(CLIENT_ENV.RUNTIME_ENV !== "local" ||
CLIENT_ENV.SENTRY_ENABLE_LOCAL === "true")
) {
init({
dsn: CLIENT_ENV.SENTRY_DSN,
environment: CLIENT_ENV.RUNTIME_ENV,
tracesSampleRate: Number(CLIENT_ENV.SENTRY_TRACES_SAMPLE_RATE ?? 0),
integrations: [
// https://docs.sentry.io/platforms/javascript/guides/remix/configuration/integrations/browsertracing
browserTracingIntegration({ useEffect, useLocation, useMatches }),

// https://docs.sentry.io/platforms/javascript/guides/remix/configuration/integrations/httpclient
httpClientIntegration(),
],
});
}
}
32 changes: 32 additions & 0 deletions apps/admin/src/core/monitoring.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { User } from "@prisma/client";
import { init, setUser } from "@sentry/remix";

export function initMonitoring() {
if (
process.env.SENTRY_DSN != null &&
(process.env.RUNTIME_ENV !== "local" ||
process.env.SENTRY_ENABLE_LOCAL === "true")
) {
init({
dsn: process.env.SENTRY_DSN,
environment: process.env.RUNTIME_ENV,
tracesSampleRate: Number(process.env.SENTRY_TRACES_SAMPLE_RATE ?? 0),
});
}
}

export function setCurrentUserForMonitoring(
currentUser: null | Pick<User, "displayName" | "email" | "groups" | "id">,
) {
if (currentUser == null) {
setUser(null);
return;
}

setUser({
id: currentUser.id,
username: currentUser.displayName,
email: currentUser.email,
groups: currentUser.groups,
});
}
19 changes: 19 additions & 0 deletions apps/admin/src/core/monitoring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { User } from "@prisma/client";
import { setUser } from "@sentry/remix";

export function useCurrentUserForMonitoring(
currentUser: null | Pick<User, "displayName" | "email" | "groups" | "id">,
) {
// Do this as early as possible for possible errors during rendering.
if (currentUser == null) {
setUser(null);
return;
}

setUser({
id: currentUser.id,
username: currentUser.displayName,
email: currentUser.email,
groups: currentUser.groups,
});
}
Loading
Loading