Compare commits

...

4 commits

Author SHA1 Message Date
Nicolas Meienberger
1efc4c3328 refactor: remove proxy pattern for db and auth
Some checks failed
Release Workflow / determine-release-type (push) Has been cancelled
Release Workflow / checks (push) Has been cancelled
Release Workflow / e2e-tests (push) Has been cancelled
Release Workflow / build-images (push) Has been cancelled
Release Workflow / publish-release (push) Has been cancelled
Since we migrated away from rr this is not needed anymore as the bundler
correctly split chunks
2026-02-13 21:09:52 +01:00
Nicolas Meienberger
48b3c9a87f refactor: extract common setup in initModule function
Some checks failed
Release Workflow / determine-release-type (push) Has been cancelled
Release Workflow / checks (push) Has been cancelled
Release Workflow / e2e-tests (push) Has been cancelled
Release Workflow / build-images (push) Has been cancelled
Release Workflow / publish-release (push) Has been cancelled
2026-02-13 20:53:15 +01:00
Nicolas Meienberger
ca2a2cb74f refactor(bootstrap): avoid duplicate event firing
Some checks failed
Release Workflow / determine-release-type (push) Has been cancelled
Release Workflow / checks (push) Has been cancelled
Release Workflow / e2e-tests (push) Has been cancelled
Release Workflow / build-images (push) Has been cancelled
Release Workflow / publish-release (push) Has been cancelled
2026-02-13 20:37:12 +01:00
Nicolas Meienberger
436a63a4b4 refactor: add nitro bootstrap plugin to ensure app is started before first call
Some checks failed
Release Workflow / determine-release-type (push) Has been cancelled
Release Workflow / checks (push) Has been cancelled
Release Workflow / e2e-tests (push) Has been cancelled
Release Workflow / build-images (push) Has been cancelled
Release Workflow / publish-release (push) Has been cancelled
2026-02-13 20:20:16 +01:00
10 changed files with 208 additions and 229 deletions

View file

@ -100,7 +100,6 @@ ENV PORT=4096
WORKDIR /app WORKDIR /app
COPY --from=builder /app/package.json ./ COPY --from=builder /app/package.json ./
RUN bun install --production --frozen-lockfile && rm -rf $HOME/.bun/install/cache
COPY --from=deps /deps/restic /usr/local/bin/restic COPY --from=deps /deps/restic /usr/local/bin/restic
COPY --from=deps /deps/rclone /usr/local/bin/rclone COPY --from=deps /deps/rclone /usr/local/bin/rclone

View file

@ -1,25 +1,18 @@
import * as schema from "./server/db/schema";
import { setSchema, runDbMigrations } from "./server/db/db";
import { startup } from "./server/modules/lifecycle/startup";
import { logger } from "./server/utils/logger"; import { logger } from "./server/utils/logger";
import { shutdown } from "./server/modules/lifecycle/shutdown"; import { shutdown } from "./server/modules/lifecycle/shutdown";
import { runCLI } from "./server/cli"; import { runCLI } from "./server/cli";
import { runMigrations } from "./server/modules/lifecycle/migrations"; import {
import { createStartHandler, defaultStreamHandler, defineHandlerCallback } from "@tanstack/react-start/server"; createStartHandler,
defaultStreamHandler,
defineHandlerCallback,
} from "@tanstack/react-start/server";
import { createServerEntry } from "@tanstack/react-start/server-entry"; import { createServerEntry } from "@tanstack/react-start/server-entry";
setSchema(schema);
const cliRun = await runCLI(Bun.argv); const cliRun = await runCLI(Bun.argv);
if (cliRun) { if (cliRun) {
process.exit(0); process.exit(0);
} }
runDbMigrations();
await runMigrations();
await startup();
const customHandler = defineHandlerCallback((ctx) => { const customHandler = defineHandlerCallback((ctx) => {
return defaultStreamHandler(ctx); return defaultStreamHandler(ctx);
}); });

View file

@ -6,53 +6,22 @@ import { migrate } from "drizzle-orm/bun-sqlite/migrator";
import { DATABASE_URL } from "../core/constants"; import { DATABASE_URL } from "../core/constants";
import fs from "node:fs"; import fs from "node:fs";
import { config } from "../core/config"; import { config } from "../core/config";
import type * as schemaTypes from "./schema"; import * as schema from "./schema";
/** fs.mkdirSync(path.dirname(DATABASE_URL), { recursive: true });
* TODO: try to remove this if moving away from react-router.
* The rr vite plugin doesn't let us customize the chunk names
* to isolate the db initialization code from the rest of the server code.
*/
let _sqlite: Database | undefined;
let _db: ReturnType<typeof initDb> | undefined;
let _schema: typeof schemaTypes | undefined;
/** if (
* Sets the database schema. This must be called before any database operations. fs.existsSync(path.join(path.dirname(DATABASE_URL), "ironmount.db")) &&
*/ !fs.existsSync(DATABASE_URL)
export const setSchema = (schema: typeof schemaTypes) => { ) {
_schema = schema; fs.renameSync(
}; path.join(path.dirname(DATABASE_URL), "ironmount.db"),
DATABASE_URL,
);
}
const initDb = () => { const sqlite = new Database(DATABASE_URL);
if (!_schema) { export const db = drizzle({ client: sqlite, relations, schema });
throw new Error("Database schema not set. Call setSchema() before accessing the database.");
}
fs.mkdirSync(path.dirname(DATABASE_URL), { recursive: true });
if (fs.existsSync(path.join(path.dirname(DATABASE_URL), "ironmount.db")) && !fs.existsSync(DATABASE_URL)) {
fs.renameSync(path.join(path.dirname(DATABASE_URL), "ironmount.db"), DATABASE_URL);
}
_sqlite = new Database(DATABASE_URL);
return drizzle({ client: _sqlite, relations, schema: _schema });
};
/**
* Database instance (Proxy for lazy initialization)
*/
export const db = new Proxy(
{},
{
get(_, prop, receiver) {
if (!_db) {
_db = initDb();
}
return Reflect.get(_db, prop, receiver);
},
},
) as ReturnType<typeof initDb>;
export const runDbMigrations = () => { export const runDbMigrations = () => {
let migrationsFolder: string; let migrationsFolder: string;
@ -67,9 +36,5 @@ export const runDbMigrations = () => {
migrate(db, { migrationsFolder }); migrate(db, { migrationsFolder });
if (!_sqlite) { sqlite.run("PRAGMA foreign_keys = ON;");
throw new Error("Database not initialized");
}
_sqlite.run("PRAGMA foreign_keys = ON;");
}; };

View file

@ -6,23 +6,35 @@ import {
type MiddlewareOptions, type MiddlewareOptions,
} from "better-auth"; } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, createAuthMiddleware, twoFactor, username, organization } from "better-auth/plugins"; import {
admin,
createAuthMiddleware,
twoFactor,
username,
organization,
} from "better-auth/plugins";
import { UnauthorizedError } from "http-errors-enhanced"; import { UnauthorizedError } from "http-errors-enhanced";
import { convertLegacyUserOnFirstLogin } from "./auth-middlewares/convert-legacy-user"; import { convertLegacyUserOnFirstLogin } from "./auth-middlewares/convert-legacy-user";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { config } from "../core/config"; import { config } from "../core/config";
import { db } from "../db/db"; import { db } from "../db/db";
import { cryptoUtils } from "../utils/crypto"; import { cryptoUtils } from "../utils/crypto";
import { organization as organizationTable, member, usersTable } from "../db/schema"; import {
organization as organizationTable,
member,
usersTable,
} from "../db/schema";
import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user"; import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user";
import { authService } from "../modules/auth/auth.service"; import { authService } from "../modules/auth/auth.service";
import { tanstackStartCookies } from "better-auth/tanstack-start"; import { tanstackStartCookies } from "better-auth/tanstack-start";
export type AuthMiddlewareContext = MiddlewareContext<MiddlewareOptions, AuthContext<BetterAuthOptions>>; export type AuthMiddlewareContext = MiddlewareContext<
MiddlewareOptions,
AuthContext<BetterAuthOptions>
>;
const createBetterAuth = (secret: string) => { export const auth = betterAuth({
return betterAuth({ secret: await cryptoUtils.deriveSecret("better-auth"),
secret,
baseURL: config.baseUrl, baseURL: config.baseUrl,
trustedOrigins: config.trustedOrigins, trustedOrigins: config.trustedOrigins,
advanced: { advanced: {
@ -60,11 +72,15 @@ const createBetterAuth = (secret: string) => {
return { data: user }; return { data: user };
}, },
after: async (user) => { after: async (user) => {
const slug = user.email.split("@")[0] + "-" + Math.random().toString(36).slice(-4); const slug =
user.email.split("@")[0] +
"-" +
Math.random().toString(36).slice(-4);
const resticPassword = cryptoUtils.generateResticPassword(); const resticPassword = cryptoUtils.generateResticPassword();
const metadata = { const metadata = {
resticPassword: await cryptoUtils.sealSecret(resticPassword), resticPassword:
await cryptoUtils.sealSecret(resticPassword),
}; };
try { try {
@ -88,9 +104,13 @@ const createBetterAuth = (secret: string) => {
}); });
}); });
} catch { } catch {
await db.delete(usersTable).where(eq(usersTable.id, user.id)); await db
.delete(usersTable)
.where(eq(usersTable.id, user.id));
throw new Error(`Failed to create organization for user ${user.id}`); throw new Error(
`Failed to create organization for user ${user.id}`,
);
} }
}, },
}, },
@ -103,7 +123,9 @@ const createBetterAuth = (secret: string) => {
}); });
if (!orgMembership) { if (!orgMembership) {
throw new UnauthorizedError("User does not belong to any organization"); throw new UnauthorizedError(
"User does not belong to any organization",
);
} }
return { return {
@ -152,31 +174,4 @@ const createBetterAuth = (secret: string) => {
}), }),
tanstackStartCookies(), tanstackStartCookies(),
], ],
}); });
};
type Auth = ReturnType<typeof createBetterAuth>;
let _auth: Auth | null = null;
const createAuth = async (): Promise<Auth> => {
if (_auth) return _auth;
_auth = createBetterAuth(await cryptoUtils.deriveSecret("better-auth"));
return _auth;
};
export const auth = new Proxy(
{},
{
get(_, prop, receiver) {
if (!_auth) {
throw new Error("Auth not initialized. Call initAuth() first.");
}
return Reflect.get(_auth, prop, receiver);
},
},
) as Auth;
export const initAuth = createAuth;

View file

@ -0,0 +1,24 @@
import { runDbMigrations } from "../../db/db";
import { runMigrations } from "./migrations";
import { startup } from "./startup";
let bootstrapPromise: Promise<void> | undefined;
const runBootstrap = async () => {
runDbMigrations();
await runMigrations();
await startup();
};
export const bootstrapApplication = async () => {
if (!bootstrapPromise) {
bootstrapPromise = runBootstrap();
}
try {
await bootstrapPromise;
} catch (err) {
bootstrapPromise = undefined;
throw err;
}
};

View file

@ -12,8 +12,6 @@ import { repositoriesService } from "../repositories/repositories.service";
import { notificationsService } from "../notifications/notifications.service"; import { notificationsService } from "../notifications/notifications.service";
import { VolumeAutoRemountJob } from "~/server/jobs/auto-remount"; import { VolumeAutoRemountJob } from "~/server/jobs/auto-remount";
import { cache } from "~/server/utils/cache"; import { cache } from "~/server/utils/cache";
import { initAuth } from "~/server/lib/auth";
import { toMessage } from "~/server/utils/errors";
import { withContext } from "~/server/core/request-context"; import { withContext } from "~/server/core/request-context";
const ensureLatestConfigurationSchema = async () => { const ensureLatestConfigurationSchema = async () => {
@ -54,11 +52,6 @@ export const startup = async () => {
await Scheduler.start(); await Scheduler.start();
await Scheduler.clear(); await Scheduler.clear();
await initAuth().catch((err) => {
logger.error(`Error initializing auth: ${toMessage(err)}`);
throw err;
});
await ensureLatestConfigurationSchema(); await ensureLatestConfigurationSchema();
const volumes = await db.query.volumesTable.findMany({ const volumes = await db.query.volumesTable.findMany({

View file

@ -0,0 +1,11 @@
import { definePlugin } from "nitro";
import { bootstrapApplication } from "../modules/lifecycle/bootstrap";
import { logger } from "../utils/logger";
import { toMessage } from "../utils/errors";
export default definePlugin(() => {
void bootstrapApplication().catch((err) => {
logger.error(`Bootstrap failed: ${toMessage(err)}`);
process.exit(1);
});
});

View file

@ -2,11 +2,7 @@ import { beforeAll, mock } from "bun:test";
import { migrate } from "drizzle-orm/bun-sqlite/migrator"; import { migrate } from "drizzle-orm/bun-sqlite/migrator";
import path from "node:path"; import path from "node:path";
import { cwd } from "node:process"; import { cwd } from "node:process";
import * as schema from "~/server/db/schema"; import { db } from "~/server/db/db";
import { db, setSchema } from "~/server/db/db";
import { initAuth } from "~/server/lib/auth";
setSchema(schema);
void mock.module("~/server/utils/logger", () => ({ void mock.module("~/server/utils/logger", () => ({
logger: { logger: {
@ -29,5 +25,4 @@ void mock.module("~/server/utils/crypto", () => ({
beforeAll(async () => { beforeAll(async () => {
const migrationsFolder = path.join(cwd(), "app", "drizzle"); const migrationsFolder = path.join(cwd(), "app", "drizzle");
migrate(db, { migrationsFolder }); migrate(db, { migrationsFolder });
await initAuth();
}); });

View file

@ -43,6 +43,7 @@ services:
- APP_SECRET=94bad4678ce84a60b9789bd2114a6bf780aeb38df426f7352c941c66e25d5c2b - APP_SECRET=94bad4678ce84a60b9789bd2114a6bf780aeb38df426f7352c941c66e25d5c2b
- BASE_URL=http://localhost:4096 - BASE_URL=http://localhost:4096
- PORT=4096 - PORT=4096
- LOG_LEVEL=debug
volumes: volumes:
- /etc/localtime:/etc/localtime:ro - /etc/localtime:/etc/localtime:ro
- /var/lib/zerobyte:/var/lib/zerobyte - /var/lib/zerobyte:/var/lib/zerobyte

View file

@ -14,7 +14,10 @@ export default defineConfig({
routesDirectory: "routes", routesDirectory: "routes",
}, },
}), }),
nitro({ preset: "bun" }), nitro({
preset: "bun",
plugins: ["./app/server/plugins/bootstrap.ts"],
}),
viteReact({ viteReact({
babel: { babel: {
plugins: ["babel-plugin-react-compiler"], plugins: ["babel-plugin-react-compiler"],