Write the adopted team Rule before the server listens so deploy cannot feature the old draft body.

This commit is contained in:
adilallo committed 2026-11-12 15:55:36 -07:00
1 parent 29a8d2b32b
commit 1ec1f48d35
8 files changed
+222 -76

No files matched your search

+5
View File
@@ -42,6 +42,10 @@ RUN ./node_modules/.bin/esbuild scripts/send-rule-follow-up.ts \
--bundle --platform=node --format=cjs \
--outfile=follow-up-mail.bundle.cjs \
--external:@prisma/client
RUN ./node_modules/.bin/esbuild scripts/seed-team-rule.ts \
--bundle --platform=node --format=cjs \
--outfile=team-rule.bundle.cjs \
--external:@prisma/client
FROM base AS runner
# openssl: Prisma engines. gosu: privilege drop in start.sh after chown.
@@ -58,6 +62,7 @@ COPY --from=builder --chown=node:node /app/.next/static ./.next/static
COPY --from=builder --chown=node:node /app/prisma ./prisma
COPY --from=builder --chown=node:node /app/prune-expired.bundle.cjs ./prune-expired.bundle.cjs
COPY --from=builder --chown=node:node /app/follow-up-mail.bundle.cjs ./follow-up-mail.bundle.cjs
COPY --from=builder --chown=node:node /app/team-rule.bundle.cjs ./team-rule.bundle.cjs
# Facet/template seed JSON — NOT under /app/data (localstorage mount overlays that).
COPY --from=builder --chown=node:node /app/data ./seed-data
ENV SEED_DATA_DIR=/app/seed-data
+4 -3
View File
@@ -321,8 +321,8 @@ the base image's `node` user (uid 1000), installs `gosu` for the
privilege drop, and symlinks `.next/cache → /tmp/next-cache` so
Next.js ISR works on Cloudron's read-only rootfs. `start.sh` runs as
root to chown `/app/data` (localstorage mount), then drops to
`node:node`, applies `prisma migrate deploy`, and execs the Next.js
standalone server.
`node:node`, applies `prisma migrate deploy`, writes the adopted team
Rule, and execs the Next.js standalone server.
### One-time setup (per operator)
@@ -438,7 +438,8 @@ production env vars, and verify the vertical slice before apex cutover
already installed.) Cloudron provisions **postgresql**, **sendmail**, and
**localstorage** addons from the manifest, pulls the image (no registry
credentials needed), and starts the container. `scripts/start.sh` chowns
`/app/data`, runs `prisma migrate deploy`, then execs the Next.js server.
`/app/data`, runs `prisma migrate deploy`, writes the adopted team Rule,
then execs the Next.js server.
4. **Set manual env vars** (Cloudron does not inject these):
```bash
cloudron env set --app staging.communityrule.info \
+5 -2
View File
@@ -94,7 +94,8 @@ credentials on the host), restarts the container, and runs
1. `chown`s `/app/data` (localstorage mount),
2. runs **`prisma migrate deploy`**,
3. execs the Next.js standalone server.
3. writes the adopted team Rule (document and visibility together),
4. execs the Next.js standalone server.
Watch the app **Logs** tab in the Cloudron dashboard for a clean migration and
`Listening on port 3000`.
@@ -121,7 +122,9 @@ deploying a new image. See [`backend-roadmap.md` §8](backend-roadmap.md#8-prism
### 3.4 Seed data (not every deploy)
Template + facet seed (`MethodFacet` rows for create-flow “Recommended” tags)
is **not** applied at boot. Run once per environment after first install, or
is **not** applied at boot. The adopted team Rule is the exception: container
start writes that one row so the public catalog does not keep the old draft
body. Run the template seed once per environment after first install, or
when recommendations return all-zero scores:
```bash
@@ -1,11 +0,0 @@
-- The team's adopted Rule replaces the September draft at GET /api/rules.
-- Document bodies land when `prisma db seed` / `node prisma/seed.bundle.cjs` runs.
UPDATE "PublishedRule"
SET
title = 'CommunityRule Creative Team',
summary = 'We build and maintain CommunityRule for the communities that use it. It is free for every community that wants to write down how it decides.',
visibility = 'public_and_featured'
WHERE title IN (
'The CommunityRule Project',
'CommunityRule Creative Team'
);
+59 -22
View File
@@ -1,3 +1,4 @@
import { isDeepStrictEqual } from "node:util";
import type { Prisma, PrismaClient } from "@prisma/client";
import { publishedRuleAnalyticsFromDocument } from "../../lib/create/publishedRuleAnalytics";
import {
@@ -8,7 +9,7 @@ import {
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
export type SeedTeamRuleResult = {
action: "created" | "updated";
action: "created" | "updated" | "unchanged";
id: string;
title: string;
};
@@ -16,6 +17,8 @@ export type SeedTeamRuleResult = {
/**
* Replaces the old "The CommunityRule Project" draft with the adopted Rule,
* or inserts it when the environment has neither row.
* Any other featured row with either title is taken out of the catalog so
* a second copy cannot stay public with a stale document.
*/
export async function seedTeamRule(
prisma: PrismaClient,
@@ -23,36 +26,35 @@ export async function seedTeamRule(
const adopted = buildAdoptedTeamRule();
const document = adopted.document as Prisma.InputJsonValue;
const analytics = publishedRuleAnalyticsFromDocument(adopted.document);
const draftRow = await prisma.publishedRule.findFirst({
where: { title: TEAM_RULE_DRAFT_TITLE },
orderBy: { createdAt: "asc" },
select: { id: true },
});
const adoptedRow = await prisma.publishedRule.findFirst({
where: { title: TEAM_RULE_TITLE },
orderBy: { createdAt: "asc" },
select: { id: true },
});
const existingId = draftRow?.id ?? adoptedRow?.id;
const data = {
title: adopted.title,
summary: adopted.summary,
document,
visibility: RULE_VISIBILITY.public_and_featured,
...analytics,
communityLocation: analytics.communityLocation,
orgType: analytics.orgType,
};
if (existingId) {
const row = await prisma.publishedRule.update({
where: { id: existingId },
data,
select: { id: true, title: true },
const rows = await prisma.publishedRule.findMany({
where: {
title: { in: [TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE] },
},
orderBy: { createdAt: "asc" },
select: {
id: true,
title: true,
summary: true,
document: true,
visibility: true,
communityLocation: true,
orgType: true,
},
});
return { action: "updated", id: row.id, title: row.title };
}
const canonical =
rows.find((row) => row.title === TEAM_RULE_DRAFT_TITLE) ?? rows[0];
if (!canonical) {
const row = await prisma.publishedRule.create({
data: {
userId: null,
@@ -62,3 +64,38 @@ export async function seedTeamRule(
});
return { action: "created", id: row.id, title: row.title };
}
const matches =
canonical.title === data.title &&
canonical.summary === data.summary &&
canonical.visibility === data.visibility &&
canonical.communityLocation === data.communityLocation &&
canonical.orgType === data.orgType &&
isDeepStrictEqual(canonical.document, data.document);
let action: SeedTeamRuleResult["action"] = "unchanged";
if (!matches) {
await prisma.publishedRule.update({
where: { id: canonical.id },
data,
});
action = "updated";
}
const extraIds = rows
.filter(
(row) =>
row.id !== canonical.id &&
row.visibility === RULE_VISIBILITY.public_and_featured,
)
.map((row) => row.id);
if (extraIds.length > 0) {
await prisma.publishedRule.updateMany({
where: { id: { in: extraIds } },
data: { visibility: RULE_VISIBILITY.private },
});
action = "updated";
}
return { action, id: canonical.id, title: data.title };
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Writes the adopted team Rule, including its document, before the server
* listens. Container start runs the esbuild bundle of this file.
*
* Local:
* node --env-file=.env --import tsx scripts/seed-team-rule.ts
*/
import { PrismaClient } from "@prisma/client";
import { seedTeamRule } from "../prisma/seed/teamRule";
const prisma = new PrismaClient();
async function main() {
const result = await seedTeamRule(prisma);
// eslint-disable-next-line no-console -- boot CLI feedback
console.log(
`Seeded team Rule: ${result.action} ${result.title} (${result.id})`,
);
}
main()
.catch((error) => {
console.error(error);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+3 -2
View File
@@ -18,7 +18,8 @@ chown -R node:node /app/data
mkdir -p /tmp/next-cache
chown -R node:node /tmp/next-cache
# Drop privileges, apply any pending migrations, then exec the server.
# Drop privileges, apply any pending migrations, write the adopted team Rule
# (document included) before anything listens, then exec the server.
# Inner `exec` ensures SIGTERM from Cloudron reaches node for clean shutdown.
exec gosu node:node sh -c \
'prisma migrate deploy && exec node server.js'
'prisma migrate deploy && node team-rule.bundle.cjs && exec node server.js'
+118 -36
View File
@@ -1,9 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { publishedRuleAnalyticsFromDocument } from "../../lib/create/publishedRuleAnalytics";
import {
TEAM_RULE_DRAFT_TITLE,
TEAM_RULE_TITLE,
buildAdoptedTeamRule,
} from "../../lib/create/teamRule";
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
import { TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE } from "../../lib/create/teamRule";
const findFirstMock = vi.fn();
const findManyMock = vi.fn();
const updateMock = vi.fn();
const updateManyMock = vi.fn();
const createMock = vi.fn();
import { seedTeamRule } from "../../prisma/seed/teamRule";
@@ -11,28 +17,45 @@ import { seedTeamRule } from "../../prisma/seed/teamRule";
function prismaStub() {
return {
publishedRule: {
findFirst: findFirstMock,
findMany: findManyMock,
update: updateMock,
updateMany: updateManyMock,
create: createMock,
},
};
}
function staleRow(
id: string,
title: string,
visibility: string = RULE_VISIBILITY.private,
) {
return {
id,
title,
summary: "September draft",
document: { stale: true },
visibility,
communityLocation: null,
orgType: null,
};
}
beforeEach(() => {
findFirstMock.mockReset();
findManyMock.mockReset();
updateMock.mockReset();
updateManyMock.mockReset();
createMock.mockReset();
updateMock.mockResolvedValue({});
updateManyMock.mockResolvedValue({ count: 1 });
});
describe("seedTeamRule", () => {
it("replaces the old draft row in place", async () => {
findFirstMock
.mockResolvedValueOnce({ id: "draft-1" })
.mockResolvedValueOnce(null);
updateMock.mockResolvedValueOnce({
id: "draft-1",
title: TEAM_RULE_TITLE,
});
it("replaces the old draft row in place, including the document", async () => {
const adopted = buildAdoptedTeamRule();
findManyMock.mockResolvedValueOnce([
staleRow("draft-1", TEAM_RULE_DRAFT_TITLE),
]);
const result = await seedTeamRule(prismaStub() as never);
@@ -41,31 +64,39 @@ describe("seedTeamRule", () => {
id: "draft-1",
title: TEAM_RULE_TITLE,
});
expect(findFirstMock).toHaveBeenNthCalledWith(1, {
where: { title: TEAM_RULE_DRAFT_TITLE },
expect(findManyMock).toHaveBeenCalledWith({
where: {
title: { in: [TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE] },
},
orderBy: { createdAt: "asc" },
select: { id: true },
select: {
id: true,
title: true,
summary: true,
document: true,
visibility: true,
communityLocation: true,
orgType: true,
},
});
expect(updateMock).toHaveBeenCalledWith(
expect.objectContaining({
expect(updateMock).toHaveBeenCalledWith({
where: { id: "draft-1" },
data: expect.objectContaining({
title: TEAM_RULE_TITLE,
data: {
title: adopted.title,
summary: adopted.summary,
document: adopted.document,
visibility: RULE_VISIBILITY.public_and_featured,
}),
}),
);
...publishedRuleAnalyticsFromDocument(adopted.document),
},
});
expect(updateManyMock).not.toHaveBeenCalled();
expect(createMock).not.toHaveBeenCalled();
});
it("updates an already-renamed adopted row", async () => {
findFirstMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "adopted-1" });
updateMock.mockResolvedValueOnce({
id: "adopted-1",
title: TEAM_RULE_TITLE,
});
findManyMock.mockResolvedValueOnce([
staleRow("adopted-1", TEAM_RULE_TITLE),
]);
const result = await seedTeamRule(prismaStub() as never);
@@ -76,7 +107,8 @@ describe("seedTeamRule", () => {
});
it("creates the adopted Rule when neither row exists", async () => {
findFirstMock.mockResolvedValueOnce(null).mockResolvedValueOnce(null);
const adopted = buildAdoptedTeamRule();
findManyMock.mockResolvedValueOnce([]);
createMock.mockResolvedValueOnce({
id: "new-1",
title: TEAM_RULE_TITLE,
@@ -89,14 +121,64 @@ describe("seedTeamRule", () => {
id: "new-1",
title: TEAM_RULE_TITLE,
});
expect(createMock).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
expect(createMock).toHaveBeenCalledWith({
data: {
userId: null,
title: TEAM_RULE_TITLE,
title: adopted.title,
summary: adopted.summary,
document: adopted.document,
visibility: RULE_VISIBILITY.public_and_featured,
}),
}),
...publishedRuleAnalyticsFromDocument(adopted.document),
},
select: { id: true, title: true },
});
});
it("unpublishes a second featured row instead of leaving its document public", async () => {
findManyMock.mockResolvedValueOnce([
staleRow(
"adopted-1",
TEAM_RULE_TITLE,
RULE_VISIBILITY.public_and_featured,
),
staleRow("draft-1", TEAM_RULE_DRAFT_TITLE),
]);
const result = await seedTeamRule(prismaStub() as never);
expect(result).toEqual({
action: "updated",
id: "draft-1",
title: TEAM_RULE_TITLE,
});
expect(updateMock).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "draft-1" } }),
);
expect(updateManyMock).toHaveBeenCalledWith({
where: { id: { in: ["adopted-1"] } },
data: { visibility: RULE_VISIBILITY.private },
});
});
it("does not rewrite a row that already matches the adopted Rule", async () => {
const adopted = buildAdoptedTeamRule();
const analytics = publishedRuleAnalyticsFromDocument(adopted.document);
findManyMock.mockResolvedValueOnce([
{
id: "adopted-1",
title: adopted.title,
summary: adopted.summary,
document: adopted.document,
visibility: RULE_VISIBILITY.public_and_featured,
communityLocation: analytics.communityLocation,
orgType: analytics.orgType,
},
]);
const result = await seedTeamRule(prismaStub() as never);
expect(result.action).toBe("unchanged");
expect(updateMock).not.toHaveBeenCalled();
expect(updateManyMock).not.toHaveBeenCalled();
});
});