Skip to content

Commit 0a6b037

Browse files
committed
refactor(language-database): 🔄 simplify async handling in from method
1 parent d390eb6 commit 0a6b037

16 files changed

Lines changed: 58 additions & 81 deletions

File tree

‎packages/api/src/content/server/localized-list-routes.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ const LANGUAGE_ROWS = [
2323

2424
const languageDatabase = {
2525
select: () => ({
26-
from: async (table: unknown) => {
26+
from: (table: unknown) => {
2727
if (table !== core_languages) {
2828
throw new Error("Only core_languages is read directly by this route.");
2929
}
3030

31-
return await Promise.resolve(LANGUAGE_ROWS);
31+
return LANGUAGE_ROWS;
3232
},
3333
}),
3434
};

‎packages/api/src/content/server/localized-public-routes.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,12 @@ const CORE = {
3030

3131
const languageDatabase = {
3232
select: () => ({
33-
from: async (table: unknown) => {
33+
from: (table: unknown) => {
3434
if (table !== core_languages) {
3535
throw new Error("Only core_languages is read directly by this route.");
3636
}
3737

38-
return await Promise.resolve(LANGUAGE_ROWS);
38+
return LANGUAGE_ROWS;
3939
},
4040
}),
4141
};

‎packages/api/src/content/server/public-routes.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { HTTPException } from "hono/http-exception";
55
import { describe, expect, it, vi } from "vitest";
66

77
import { core_content_containers } from "@/database/content-containers";
8+
import { siteOfflineGuard } from "@/middlewares/site-offline.middleware";
89
import {
910
testCategoryContentType,
1011
testPostContentType,
@@ -441,17 +442,16 @@ describe("generated surface", () => {
441442
});
442443

443444
it("installs no staff-permission guard", () => {
444-
// `buildRoute` always adds `pluginMiddleware`, adds the offline-site
445-
// guard unless the route sets `allowWhenOffline`, and adds one more only
446-
// when `adminStaffPermission` is set. At most two means none.
447445
const routes = buildContentPublicRoutes(posts, { pluginId: PLUGIN_ID });
448446

449447
for (const { route } of routes) {
450448
// `createRoute` types `middleware` per route config, so read it through
451449
// the shape `buildRoute` actually assembles.
452450
const { middleware } = route as unknown as { middleware: unknown[] };
453451

454-
expect(middleware.length).toBeLessThanOrEqual(2);
452+
expect(
453+
middleware.filter(handler => handler !== siteOfflineGuard),
454+
).toHaveLength(1);
455455
}
456456
});
457457
});

‎packages/api/src/content/server/public-routes.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -532,8 +532,6 @@ export const buildContentPublicRoutes = <
532532
* would hand a reviewer a different language from the one they were sent.
533533
*/
534534
const preview = buildRoute({
535-
// The signed token is the authorization, and reviewers preview while the
536-
// site is still offline.
537535
allowWhenOffline: true,
538536
pluginId,
539537
route: {

‎packages/api/src/lib/route.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ export const buildRoute = <
193193
const middleware: MiddlewareHandler[] = [pluginMiddleware(pluginId)];
194194

195195
if (!allowWhenOffline && !adminStaffPermission) {
196-
middleware.push(siteOfflineGuard());
196+
middleware.push(siteOfflineGuard);
197197
}
198198

199199
if (adminStaffPermission) {

‎packages/api/src/lib/site-status.server.ts‎

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,23 @@ import type { Context } from "hono";
33
import { eq } from "drizzle-orm";
44
import { z } from "zod";
55

6-
import { defineCacheEntry } from "@/builders";
7-
import { zodRichTextDocument } from "@/content/rich-text/document";
86
import { core_site_status } from "@/database/site";
7+
import { manifest } from "@/manifest";
98

109
import type { DomainCache } from "./cache";
1110
import type { SiteOfflineMessage, SiteStatusUpdate } from "./site-status";
1211

12+
import { defineCacheEntry } from "./cache-entry";
1313
import {
1414
checkStaffPermissionOfUser,
1515
getStaffFlags,
1616
} from "./check-staff-permission";
1717
import { coreStaffPermissions } from "./core-staff-permissions";
1818
import { invalidatePageCacheTags } from "./page-cache";
19-
import { SITE_STATUS_PAGE_CACHE_TAG } from "./site-status";
19+
import {
20+
SITE_STATUS_PAGE_CACHE_TAG,
21+
zodSiteOfflineMessage,
22+
} from "./site-status";
2023
import { staffPermissionArgs } from "./staff-permissions";
2124

2225
/** The stored row, as every request reads it. */
@@ -38,34 +41,22 @@ const ONLINE: StoredSiteStatus = {
3841
showCountdown: true,
3942
};
4043

41-
/**
42-
* Every request reads it, so it is cached. A save deletes the entry; the TTL
43-
* only bounds how long another instance without a shared store lags behind.
44-
*/
4544
const siteStatusCache = defineCacheEntry({
45+
pluginId: manifest.id,
4646
name: "site.status",
4747
version: 1,
4848
schema: z.object({
4949
changedAt: z.string().nullable(),
5050
changedById: z.number().int().nullable(),
51-
/** JSON of the message: rich-text attrs are not typed as JSON. */
52-
message: z.string(),
51+
messageJson: z.string(),
5352
offline: z.boolean(),
5453
opensAt: z.string().nullable(),
5554
showCountdown: z.boolean(),
5655
}),
5756
ttlSeconds: 300,
5857
});
5958

60-
const zodMessage = z.array(
61-
z.object({ languageCode: z.string(), value: zodRichTextDocument }),
62-
);
63-
64-
const parseMessage = (json: string): SiteOfflineMessage =>
65-
zodMessage.parse(JSON.parse(json));
66-
67-
/** Test apps built without the global middleware have no cache. */
68-
const cacheOf = (c: Context) => c.get("cache") as DomainCache | undefined;
59+
const cacheOf = (c: Context): DomainCache | undefined => c.get("cache");
6960

7061
const perRequest = new WeakMap<Context, Promise<StoredSiteStatus>>();
7162

@@ -101,11 +92,14 @@ export const loadSiteStatus = async (c: Context): Promise<StoredSiteStatus> => {
10192
? cache
10293
.entry(siteStatusCache)
10394
.remember(async () => {
104-
const row = await readRow(c);
95+
const { message, ...row } = await readRow(c);
10596

106-
return { ...row, message: JSON.stringify(row.message) };
97+
return { ...row, messageJson: JSON.stringify(message) };
10798
})
108-
.then(cached => ({ ...cached, message: parseMessage(cached.message) }))
99+
.then(({ messageJson, ...cached }) => ({
100+
...cached,
101+
message: zodSiteOfflineMessage.parse(JSON.parse(messageJson)),
102+
}))
109103
: readRow(c);
110104
perRequest.set(c, loading);
111105

@@ -136,8 +130,8 @@ export const canBypassSiteOffline = async (c: Context): Promise<boolean> => {
136130
};
137131

138132
/**
139-
* Writes the site status and returns the row before the write (`null` when
140-
* there was none). Run it inside the caller's transaction, then call
133+
* Writes the site status. Returns the row before the write (`null` when there
134+
* was none) and whether this save flipped `offline`. Run it inside the caller's transaction, then call
141135
* {@link afterSiteStatusSaved} once it has committed. Server-only.
142136
*/
143137
export const saveSiteStatus = async (

‎packages/api/src/lib/site-status.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ import {
1212
/** The reason the site is offline: one rich-text document per language. */
1313
export type SiteOfflineMessage = MultiLangValue<RichTextDocument>;
1414

15+
/** {@link SiteOfflineMessage} as stored and served. Browser-safe. */
16+
export const zodSiteOfflineMessage = z.array(
17+
z.object({ languageCode: z.string(), value: zodRichTextDocument }),
18+
);
19+
1520
/** Limits of the offline message. */
1621
export const SITE_STATUS_LIMITS = {
1722
/** Largest serialised document per language, in bytes. */
@@ -33,9 +38,7 @@ export const SITE_STATUS_PAGE_CACHE_TAG = "core:site-status";
3338
/** What `GET /api/core/site/status` answers. Browser-safe. */
3439
export const zodSiteStatus = z.object({
3540
offline: z.boolean(),
36-
message: z.array(
37-
z.object({ languageCode: z.string(), value: zodRichTextDocument }),
38-
),
41+
message: zodSiteOfflineMessage,
3942
opensAt: z.string().nullable(),
4043
showCountdown: z.boolean(),
4144
/** The server's clock when it answered, so a countdown can correct skew. */

‎packages/api/src/middlewares/site-offline.middleware.ts‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
11
import type { MiddlewareHandler } from "hono";
22

3+
import { isAdminApiPath } from "../lib/route-metadata";
34
import { retryAfterSeconds } from "../lib/site-status";
5+
import {
6+
canBypassSiteOffline,
7+
loadSiteStatus,
8+
} from "../lib/site-status.server";
49

510
/**
611
* Answers `503 { error: "site_offline" }` while the site is offline, unless
712
* the caller may use the offline site (see `canBypassSiteOffline`) or the
8-
* request is under `/admin/` (which requires an AdminCP session anyway). `buildRoute` adds it to every
9-
* route that does not set `allowWhenOffline`.
13+
* request is under `/admin/` (which requires an AdminCP session anyway). A
14+
* status that fails to load counts as online, so the lookup never takes every
15+
* route down with it. `buildRoute` adds it to every route that does not set
16+
* `allowWhenOffline`.
1017
*/
11-
export const siteOfflineGuard = (): MiddlewareHandler => async (c, next) => {
12-
if (c.req.path.includes("/admin/")) return await next();
18+
export const siteOfflineGuard: MiddlewareHandler = async (c, next) => {
19+
if (isAdminApiPath(c.req.path)) return await next();
1320

14-
// Loaded lazily: the status module reaches the route builders, which
15-
// import this guard.
16-
const { canBypassSiteOffline, loadSiteStatus } =
17-
await import("../lib/site-status.server");
18-
let status: Awaited<ReturnType<typeof loadSiteStatus>>;
19-
try {
20-
status = await loadSiteStatus(c);
21-
} catch {
22-
// An unreadable status counts as online: the lookup failing must not
23-
// take every route down with it.
24-
return await next();
25-
}
26-
if (!status.offline || (await canBypassSiteOffline(c))) return await next();
21+
const status = await loadSiteStatus(c).catch(() => null);
22+
if (!status?.offline || (await canBypassSiteOffline(c))) return await next();
2723

2824
const retryAfter = retryAfterSeconds(status.opensAt);
2925
if (retryAfter) c.header("Retry-After", String(retryAfter));

‎packages/api/src/modules/admin/site/routes/update.route.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,6 @@ export const updateSiteStatusAdminRoute = buildRoute({
5656
});
5757
}
5858
}
59-
// A countdown that already ran out may stay as it is; a new time must be
60-
// in the future.
6159
const current = await loadSiteStatus(c);
6260
const opensAtMs = body.opensAt ? Date.parse(body.opensAt) : null;
6361
const unchanged =

‎packages/api/src/modules/admin/site/site.schema.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import { z } from "zod";
22

3-
import { zodRichTextDocument } from "@/content/rich-text/document";
3+
import { zodSiteOfflineMessage } from "@/lib/site-status";
44

55
export const zodSiteStatusAdmin = z.object({
66
offline: z.boolean(),
7-
message: z.array(
8-
z.object({ languageCode: z.string(), value: zodRichTextDocument }),
9-
),
7+
message: zodSiteOfflineMessage,
108
opensAt: z.string().nullable(),
119
showCountdown: z.boolean(),
1210
/** When `offline` last flipped; `null` before the first save. */

0 commit comments

Comments
 (0)