Skip to content

Commit 93c754d

Browse files
committed
hub: centralize db singleton access
1 parent 97191b2 commit 93c754d

File tree

11 files changed

+31
-23
lines changed

11 files changed

+31
-23
lines changed

src/packages/hub/hub.ts

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import {
2020
pgdatabase,
2121
pghost,
2222
pguser,
23-
data,
2423
} from "@cocalc/backend/data";
2524
import { trimLogFileSize } from "@cocalc/backend/logger";
2625
import port from "@cocalc/backend/port";
@@ -50,15 +49,14 @@ import { stripe_sync } from "@cocalc/server/stripe/sync";
5049
import { callback2, retry_until_success } from "@cocalc/util/async-utils";
5150
import { set_agent_endpoint } from "./health-checks";
5251
import { getLogger } from "./logger";
53-
import initDatabase from "./servers/database";
52+
import initDatabase, { getDatabase } from "./servers/database";
5453
import initExpressApp from "./servers/express-app";
5554

5655
import initHttpRedirect from "./servers/http-redirect";
5756

5857
import { addErrorListeners } from "@cocalc/server/metrics/error-listener";
5958
import * as MetricsRecorder from "@cocalc/server/metrics/metrics-recorder";
6059
import { migrateBookmarksToConat } from "./migrate-bookmarks";
61-
import { PostgreSQL } from "@cocalc/database/postgres";
6260

6361
// Logger tagged with 'hub' for this file.
6462
const logger = getLogger("hub");
@@ -69,15 +67,6 @@ export { program };
6967

7068
const REGISTER_INTERVAL_S = 20;
7169

72-
let database: PostgreSQL | undefined = undefined;
73-
74-
function getDatabase(): PostgreSQL {
75-
if (database == null) {
76-
throw new Error("database not initialized yet");
77-
}
78-
return database;
79-
}
80-
8170
async function reset_password(email_address: string): Promise<void> {
8271
try {
8372
await callback2(getDatabase().reset_password, { email_address });
@@ -256,6 +245,8 @@ async function startServer(): Promise<void> {
256245
key: program.httpsKey,
257246
});
258247

248+
const database = getDatabase();
249+
259250
// The express app create via initExpressApp above **assumes** that init_passport is done
260251
// or complains a lot. This is obviously not really necessary, but we leave it for now.
261252
await callback2(init_passport, {
@@ -453,7 +444,7 @@ async function main(): Promise<void> {
453444
try {
454445
// Everything we do here requires the database to be initialized. Once
455446
// initDatabase returns, database is the initialized singleton.
456-
database = initDatabase();
447+
const database = initDatabase();
457448
database._concurrent_warn = program.dbConcurrentWarn;
458449

459450
if (program.passwd) {

src/packages/hub/proxy/check-for-access-to-project.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import LRU from "lru-cache";
22
import { callback2 } from "@cocalc/util/async-utils";
33
import getLogger from "../logger";
4-
import { database } from "../servers/database";
4+
import { getDatabase } from "../servers/database";
55
const {
66
user_has_write_access_to_project,
77
user_has_read_access_to_project,
@@ -128,6 +128,7 @@ async function checkForRememberMeAccess({
128128
type,
129129
dbg,
130130
}): Promise<{ access: boolean; error?: string }> {
131+
const database = getDatabase();
131132
dbg("get remember_me message");
132133
const x = remember_me.split("$");
133134
const hash = generateHash(x[0], x[1], parseInt(x[2]), x[3]);

src/packages/hub/proxy/target.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ to this target or the target project isn't running.
99
import LRU from "lru-cache";
1010

1111
import getLogger from "@cocalc/hub/logger";
12-
import { database } from "@cocalc/hub/servers/database";
12+
import { getDatabase } from "@cocalc/hub/servers/database";
1313
import { ProjectControlFunction } from "@cocalc/server/projects/control";
1414
import { reuseInFlight } from "@cocalc/util/reuse-in-flight";
1515
import { NamedServerName } from "@cocalc/util/types/servers";
@@ -91,6 +91,7 @@ export async function getTarget({
9191
throw Error(`user does not have write access to project`);
9292
}
9393

94+
const database = getDatabase();
9495
const project = projectControl(project_id);
9596
let state = await project.state();
9697
let host = state.ip;
@@ -184,6 +185,7 @@ async function _namedServerPort(
184185
if (p) {
185186
return p;
186187
}
188+
const database = getDatabase();
187189
const project = hub_projects.new_project(
188190
// NOT @cocalc/server/projects/control like above...
189191
project_id,

src/packages/hub/servers/app/blob-upload.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ allows for attaching files to github issue comments.
88

99
import { Router } from "express";
1010
import { callback2 } from "@cocalc/util/async-utils";
11-
import { database } from "../database";
11+
import { getDatabase } from "../database";
1212
const { save_blob } = require("@cocalc/hub/blobs");
1313
import { getLogger } from "@cocalc/hub/logger";
1414
import {
@@ -27,14 +27,15 @@ function dbg(...args): void {
2727
}
2828

2929
export default function init(router: Router) {
30+
const database = getDatabase();
3031
router.post("/blobs", async (req, res) => {
3132
const account_id = await getAccount(req);
3233
if (!account_id) {
3334
res.status(500).send("user must be signed in to upload files");
3435
return;
3536
}
3637
const { project_id, ttl } = req.query;
37-
if (typeof project_id == 'string' && project_id) {
38+
if (typeof project_id == "string" && project_id) {
3839
if (!(await isCollaborator({ account_id, project_id }))) {
3940
res.status(500).send("user must be collaborator on project");
4041
return;

src/packages/hub/servers/app/blobs.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import { Router } from "express";
2-
import { database } from "../database";
2+
import { getDatabase } from "../database";
33
import { is_valid_uuid_string } from "@cocalc/util/misc";
44
import { database_is_working } from "@cocalc/server/metrics/hub_register";
55
import { callback2 } from "@cocalc/util/async-utils";
66
import { getLogger } from "@cocalc/hub/logger";
77

88
const logger = getLogger("hub:servers:app:blobs");
99
export default function init(router: Router) {
10+
const database = getDatabase();
1011
// return uuid-indexed blobs (mainly used for graphics)
1112
router.get("/blobs/*", async (req, res) => {
1213
logger.debug(`${JSON.stringify(req.query)}, ${req.path}`);

src/packages/hub/servers/app/customize.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55

66
import { send as sendManifest } from "@cocalc/hub/manifest";
77
import { WebappConfiguration } from "@cocalc/hub/webapp-configuration";
8-
import { database } from "../database";
8+
import { getDatabase } from "../database";
99

1010
export default function init(router, isPersonal: boolean) {
11+
const database = getDatabase();
1112
const webappConfig = new WebappConfiguration({ db: database });
1213

1314
router.get("/customize", async (req, res) => {

src/packages/hub/servers/app/next.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import basePath from "@cocalc/backend/base-path";
1515
import { getLogger } from "@cocalc/hub/logger";
1616
import handleRaw from "@cocalc/next/lib/share/handle-raw";
1717
import { callback2 } from "@cocalc/util/async-utils";
18-
import { database } from "../database";
18+
import { getDatabase } from "../database";
1919
import createLandingRedirect from "./landing-redirect";
2020
import shareRedirect from "./share-redirect";
2121
import { separate_file_extension } from "@cocalc/util/misc";
@@ -123,6 +123,7 @@ function parseURL(req: Request, base): { id: string; path: string } {
123123
}
124124

125125
async function runShareServer(): Promise<boolean> {
126+
const database = getDatabase();
126127
const { rows } = await callback2(database._query, {
127128
query: "SELECT value FROM server_settings WHERE name='share_server'",
128129
});

src/packages/hub/servers/app/stats.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { Router } from "express";
22
import { callback2 } from "@cocalc/util/async-utils";
33
import { database_is_working } from "@cocalc/server/metrics/hub_register";
4-
import { database } from "../database";
4+
import { getDatabase } from "../database";
55

66
export default function init(router: Router) {
7+
const database = getDatabase();
78
// Return global status information about CoCalc
89
router.get("/stats", async (_req, res) => {
910
if (!database_is_working()) {

src/packages/hub/servers/database.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ import { enableDbAdminAlerts } from "@cocalc/server/messages/admin-alert";
88
// object gets used.
99
let database: PostgreSQL | undefined = undefined;
1010

11+
export function getDatabase(): PostgreSQL {
12+
if (database == null) {
13+
throw new Error("database not initialized yet");
14+
}
15+
return database;
16+
}
17+
1118
export default function init(): PostgreSQL {
1219
if (database != null) {
1320
throw Error("only call database init once");

src/packages/hub/servers/express-app.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import initCustomize from "./app/customize";
2525
import { initMetricsEndpoint, setupInstrumentation } from "./app/metrics";
2626
import initNext from "./app/next";
2727
import initStats from "./app/stats";
28-
import { database } from "./database";
28+
import { getDatabase } from "./database";
2929
import initHttpServer from "./http";
3030
import initRobots from "./robots";
3131
import basePath from "@cocalc/backend/base-path";
@@ -57,6 +57,7 @@ export default async function init(opts: Options): Promise<{
5757
}> {
5858
const winston = getLogger("express-app");
5959
winston.info("creating express app");
60+
const database = getDatabase();
6061

6162
// Create an express application
6263
const app = express();

0 commit comments

Comments
 (0)