Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
do migrations directly in instrumentation file
Brendan Allan0a4342f0e2b4
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex fdc9ba4b8..634120f80 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -10,7 +10,7 @@ COPY . .RUN corepack enable pnpmRUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm i --frozen-lockfile-ARG DOCKER_BUILD=true+ARG NEXT_PUBLIC_DOCKER_BUILD=trueENV NEXT_PUBLIC_WEB_URL=http://localhost:3000ENV NEXT_PUBLIC_CAP_AWS_BUCKET=capsoENV NEXT_PUBLIC_CAP_AWS_REGION=us-east-1diff --git a/apps/web/instrumentation.node.ts b/apps/web/instrumentation.node.tsnew file mode 100644index 000000000..744e56d0f--- /dev/null+++ b/apps/web/instrumentation.node.ts@@ -0,0 +1,104 @@+// This file is used to run database migrations in the docker builds or other self hosting environments.+// It is not suitable (a.k.a DEADLY) for serverless environments where the server will be restarted on each request.+//+import { db } from "@cap/database";+import { migrate } from "drizzle-orm/mysql2/migrator";+import path from "path";+import { buildEnv, serverEnv } from "@cap/env";+import {+ BucketAlreadyOwnedByYou,+ CreateBucketCommand,+ PutBucketPolicyCommand,+ S3Client,+} from "@aws-sdk/client-s3";++export async function register() {+ console.log("Waiting 5 seconds to run migrations");++ // Function to trigger migrations with retry logic+ const triggerMigrations = async (retryCount = 0, maxRetries = 3) => {+ try {+ await runMigrations();+ } catch (error) {+ console.error(+ `π¨ Error triggering migrations (attempt ${retryCount + 1}):`,+ error+ );+ if (retryCount < maxRetries - 1) {+ console.log(+ `π Retrying in 5 seconds... (${retryCount + 1}/${maxRetries})`+ );+ setTimeout(() => triggerMigrations(retryCount + 1, maxRetries), 5000);+ } else {+ console.error(`π¨ All ${maxRetries} migration attempts failed.`);+ process.exit(1); // Exit with error code if all attempts fail+ }+ }+ };++ // Add a timeout to trigger migrations after 5 seconds on server start+ setTimeout(() => triggerMigrations(), 5000);++ setTimeout(() => createS3Bucket(), 5000);+}++async function createS3Bucket() {+ const s3Client = new S3Client({+ endpoint: serverEnv().CAP_AWS_ENDPOINT,+ region: serverEnv().CAP_AWS_REGION,+ credentials: {+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY ?? "",+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY ?? "",+ },+ forcePathStyle: serverEnv().S3_PATH_STYLE,+ });++ await s3Client+ .send(new CreateBucketCommand({ Bucket: serverEnv().CAP_AWS_BUCKET }))+ .then(() => {+ console.log("Created S3 bucket");+ return s3Client.send(+ new PutBucketPolicyCommand({+ Bucket: serverEnv().CAP_AWS_BUCKET,+ Policy: JSON.stringify({+ Version: "2012-10-17",+ Statement: [+ {+ Effect: "Allow",+ Principal: "*",+ Action: ["s3:GetObject"],+ Resource: [`arn:aws:s3:::${serverEnv().CAP_AWS_BUCKET}/*`],+ },+ ],+ }),+ })+ );+ })+ .then(() => {+ console.log("Configured S3 buckeet");+ })+ .catch((e) => {+ if (e instanceof BucketAlreadyOwnedByYou) {+ console.log("Found existing S3 bucket");+ return;+ }+ });+}++async function runMigrations() {+ const isDockerBuild = buildEnv.NEXT_PUBLIC_DOCKER_BUILD === "true";+ if (isDockerBuild) {+ try {+ console.log("π DB migrations triggered");+ console.log("πΏ Running DB migrations...");++ await migrate(db() as any, {+ migrationsFolder: path.join(process.cwd(), "/migrations"),+ });+ console.log("πΏ Migrations run successfully!");+ } catch (error) {+ console.error("π¨ MIGRATION_FAILED", { error });+ throw error;+ }+ }+}diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.tsindex 988fe3323..a8987d056 100644--- a/apps/web/instrumentation.ts+++ b/apps/web/instrumentation.ts@@ -1,104 +1,6 @@-// This file is used to run database migrations in the docker builds or other self hosting environments.-// It is not suitable (a.k.a DEADLY) for serverless environments where the server will be restarted on each request.--import { serverEnv } from "@cap/env";-import {- BucketAlreadyOwnedByYou,- CreateBucketCommand,- PutBucketPolicyCommand,- S3Client,-} from "@aws-sdk/client-s3";-export async function register() {if (process.env.NEXT_RUNTIME === "nodejs") {- console.log("Waiting 5 seconds to run migrations");-- // Function to trigger migrations with retry logic- const triggerMigrations = async (retryCount = 0, maxRetries = 3) => {- try {- const response = await fetch(- `${serverEnv().WEB_URL}/api/selfhosted/migrations`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- }- );-- // This will throw an error if the response status is not ok- response.ok ||- (await Promise.reject(new Error(`HTTP error ${response.status}`)));-- const responseData = await response.json();- console.log(- "β Migrations triggered successfully:",- responseData.message- );- } catch (error) {- console.error(- `π¨ Error triggering migrations (attempt ${retryCount + 1}):`,- error- );- if (retryCount < maxRetries - 1) {- console.log(- `π Retrying in 5 seconds... (${retryCount + 1}/${maxRetries})`- );- setTimeout(() => triggerMigrations(retryCount + 1, maxRetries), 5000);- } else {- console.error(`π¨ All ${maxRetries} migration attempts failed.`);- process.exit(1); // Exit with error code if all attempts fail- }- }- };-- // Add a timeout to trigger migrations after 5 seconds on server start- setTimeout(() => triggerMigrations(), 5000);-- setTimeout(() => createS3Bucket(), 5000);+ const { register } = await import("./instrumentation.node");+ await register();}- return;-}--async function createS3Bucket() {- const s3Client = new S3Client({- endpoint: serverEnv().CAP_AWS_ENDPOINT,- region: serverEnv().CAP_AWS_REGION,- credentials: {- accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY ?? "",- secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY ?? "",- },- forcePathStyle: serverEnv().S3_PATH_STYLE,- });-- await s3Client- .send(new CreateBucketCommand({ Bucket: serverEnv().CAP_AWS_BUCKET }))- .then(() => {- console.log("Created S3 bucket");- return s3Client.send(- new PutBucketPolicyCommand({- Bucket: serverEnv().CAP_AWS_BUCKET,- Policy: JSON.stringify({- Version: "2012-10-17",- Statement: [- {- Effect: "Allow",- Principal: "*",- Action: ["s3:GetObject"],- Resource: [`arn:aws:s3:::${serverEnv().CAP_AWS_BUCKET}/*`],- },- ],- }),- })- );- })- .then(() => {- console.log("Configured S3 buckeet");- })- .catch((e) => {- if (e instanceof BucketAlreadyOwnedByYou) {- console.log("Found existing S3 bucket");- return;- }- });}diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjsindex d1dd18f7c..9ed6995f6 100644--- a/apps/web/next.config.mjs+++ b/apps/web/next.config.mjs@@ -21,7 +21,7 @@ const nextConfig = {ignoreBuildErrors: true,},experimental: {- instrumentationHook: process.env.DOCKER_BUILD === "true",+ instrumentationHook: process.env.NEXT_PUBLIC_DOCKER_BUILD === "true",optimizePackageImports: ["@cap/ui", "@cap/utils", "@cap/web-api-contract"],serverComponentsExternalPackages: ["@react-email/components",@@ -102,7 +102,8 @@ const nextConfig = {appVersion: version,},// If the DOCKER_BUILD environment variable is set to true, we are output nextjs to standalone ready for docker deployment- output: process.env.DOCKER_BUILD === "true" ? "standalone" : undefined,+ output:+ process.env.NEXT_PUBLIC_DOCKER_BUILD === "true" ? "standalone" : undefined,};export default nextConfig;