Skip to content

Commit

Permalink
method to use db from cache
Browse files Browse the repository at this point in the history
  • Loading branch information
tantaman committed Dec 1, 2023
1 parent 57f1a8f commit 5f8858f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
7 changes: 6 additions & 1 deletion packages/ws-server/src/DB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,14 +338,19 @@ export function getDbPath(dbName: string, config: Config) {
return path.join(config.dbFolder, dbName);
}

function getSchemaPath(schemaName: string, config: Config) {
export function getSchemaPath(schemaName: string, config: Config) {
if (hasPathParts(schemaName)) {
throw new Error(`${schemaName} must not include '..', '/', or '\\'`);
}

return path.join(config.schemaFolder, schemaName);
}

export function getResidentSchemaVersion(schemaName: string, config: Config) {
const content = fs.readFileSync(getSchemaPath(schemaName, config), "utf-8");
return cryb64(content);
}

function hasPathParts(s: string) {
return s.includes("..") || s.includes("/") || s.includes("\\");
}
12 changes: 11 additions & 1 deletion packages/ws-server/src/DBCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IDB } from "./DB.js";
import { IDB, getResidentSchemaVersion } from "./DB.js";
import { IDBFactory } from "./DBFactory.js";
import { Config } from "./config.js";
import FSNotify from "./fs/FSNotify.js";
Expand Down Expand Up @@ -34,6 +34,16 @@ export default class DBCache {
return ret[0];
}

async use(roomId: string, schemaName: string, cb: (db: IDB) => unknown) {
const version = getResidentSchemaVersion(schemaName, this.#config);
const db = await this.getAndRef(roomId, schemaName, version);
try {
await cb(db);
} finally {
this.unref(roomId);
}
}

async getAndRef(roomId: string, schemaName: string, schemaVersion: bigint) {
logger.info(`Get db from cache for room "${roomId}"`);
let entry = this.#dbs.get(roomId);
Expand Down

0 comments on commit 5f8858f

Please sign in to comment.