Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38ebce24ab | ||
|
|
e8853cf0c8 | ||
|
|
c442fe0d42 | ||
|
|
f174285711 |
@@ -4,6 +4,11 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Contracts
|
||||
|
||||
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
|
||||
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
|
||||
|
||||
### Docs
|
||||
|
||||
- The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from
|
||||
|
||||
@@ -7,6 +7,20 @@ and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **AI use is shown in tokens, not rand** (for 2.3.0; needs Hub 2.0.1 for the token figures). Site
|
||||
settings → AI shows the percentage used, the input and output tokens used this month and an
|
||||
estimated allowance in tokens; the per-person, per-helper and per-day tables show tokens instead
|
||||
of cost. The 80% email names tokens instead of rand. The rand amounts the Hub sends are dropped
|
||||
on arrival, so they never reach a browser. With a Hub before 2.0.1 only the percentage shows.
|
||||
- **API (v2):** `GET /api/v2/ai/status` (and the `status` in every AI reply and in `/ai/usage`) no
|
||||
longer has `capCents` / `usedCents`; it has `usedInputTokens`, `usedOutputTokens`,
|
||||
`capInputTokens`, `capOutputTokens` (null from an older Hub). `/ai/usage` rows have
|
||||
`inputTokens` / `outputTokens` instead of `chargedCents`.
|
||||
- `AiCall` keeps each call's tokens (migration `20261117120000_ai_tokens`). Calls from before it
|
||||
show 0 tokens.
|
||||
|
||||
## [2.1.1] - 2026-11-03
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- 2.3.0: tokens per AI call, which is what the site shows (the rand amount is the Hub's business).
|
||||
ALTER TABLE "AiCall" ADD COLUMN "inputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE "AiCall" ADD COLUMN "outputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -2341,8 +2341,12 @@ model AiCall {
|
||||
helper String
|
||||
// ok, refused, incomplete, failed, cap_reached, unavailable
|
||||
outcome String
|
||||
// What the church was charged, in cents (fractions of a cent).
|
||||
// What the church was charged, in cents (fractions of a cent). Kept for the record; the site
|
||||
// shows tokens (2.3.0), and only the Hub shows rand.
|
||||
chargedCents Float @default(0)
|
||||
// Tokens the call used (2.3.0): input counts cached prompt tokens. 0 when the call failed.
|
||||
inputTokens Int @default(0)
|
||||
outputTokens Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through
|
||||
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap in rand,
|
||||
* calls Claude and meters the call. This module:
|
||||
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap, calls
|
||||
* Claude and meters the call. The site shows that use as tokens and a percentage (2.3.0); the cap's
|
||||
* rand amount stays on the Hub. This module:
|
||||
* - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the
|
||||
* allowance renews — from the licence token first, then the Hub (cached for a minute);
|
||||
* - runs one helper call (`runHelper`), with this site's own switches per helper and an optional
|
||||
@@ -32,8 +33,16 @@ const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(en
|
||||
export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const;
|
||||
export type HelperName = (typeof HELPERS)[number];
|
||||
|
||||
/** What the Hub says (§3b). Cents are charged rand, with fractions. */
|
||||
export type HubAiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string | null };
|
||||
/**
|
||||
* What the Hub says (§3b), as the site keeps it. The Hub also sends the allowance in rand
|
||||
* (`capCents`, `usedCents`); the site drops those (2.3.0): people see tokens and a percentage,
|
||||
* and only the Hub shows rand. The token fields are null from a Hub before 2.0.1.
|
||||
*/
|
||||
export type HubAiStatus = {
|
||||
enabled: boolean; capReached: boolean; usedPercent: number; renewsOn: string | null;
|
||||
usedInputTokens: number | null; usedOutputTokens: number | null;
|
||||
capInputTokens: number | null; capOutputTokens: number | null;
|
||||
};
|
||||
/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
||||
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
||||
|
||||
@@ -44,7 +53,28 @@ const STATUS_TTL_MS = 60 * 1000;
|
||||
const CALL_TIMEOUT_MS = 90 * 1000;
|
||||
const KEEP_CALLS_DAYS = 400;
|
||||
|
||||
const OFF: HubAiStatus = { enabled: false, capReached: false, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null };
|
||||
const OFF: HubAiStatus = { enabled: false, capReached: false, usedPercent: 0, renewsOn: null, usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null };
|
||||
|
||||
const tokens = (n: unknown): number | null => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.round(n) : null);
|
||||
|
||||
/** The Hub's status without its rand amounts. */
|
||||
function fromHub(v: Record<string, unknown>): HubAiStatus {
|
||||
return {
|
||||
enabled: v.enabled === true,
|
||||
capReached: v.capReached === true,
|
||||
usedPercent: typeof v.usedPercent === 'number' ? v.usedPercent : 0,
|
||||
renewsOn: typeof v.renewsOn === 'string' ? v.renewsOn : null,
|
||||
usedInputTokens: tokens(v.usedInputTokens), usedOutputTokens: tokens(v.usedOutputTokens),
|
||||
capInputTokens: tokens(v.capInputTokens), capOutputTokens: tokens(v.capOutputTokens),
|
||||
};
|
||||
}
|
||||
|
||||
/** "1.2M", "450K", "800": tokens for people. */
|
||||
export function tokenText(n: number): string {
|
||||
if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, '')}M`;
|
||||
if (n >= 1e3) return `${Math.round(n / 1e3)}K`;
|
||||
return String(n);
|
||||
}
|
||||
|
||||
// ─── This site's settings ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -78,8 +108,8 @@ let cached: { at: number; value: HubAiStatus; available: boolean } | null = null
|
||||
|
||||
/** Keep what the Hub just said (every AI reply and error carries it). */
|
||||
function remember(value: unknown, available = true): void {
|
||||
const v = value as Partial<HubAiStatus> | null;
|
||||
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, available };
|
||||
const v = value as Record<string, unknown> | null;
|
||||
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: fromHub(v), available };
|
||||
}
|
||||
|
||||
export function clearAiStatusCache(): void {
|
||||
@@ -185,7 +215,10 @@ async function warnAt80(status: HubAiStatus): Promise<void> {
|
||||
if (!email.isSmtpConfigured()) return;
|
||||
const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } });
|
||||
const when = renewsText(status.renewsOn);
|
||||
const text = `This site has used ${status.usedPercent}% of this month's AI allowance (R${(status.usedCents / 100).toFixed(2)} of R${(status.capCents / 100).toFixed(2)}). The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
||||
const used = status.usedInputTokens != null && status.usedOutputTokens != null
|
||||
? ` (${tokenText(status.usedInputTokens)} input and ${tokenText(status.usedOutputTokens)} output tokens)`
|
||||
: '';
|
||||
const text = `This site has used ${status.usedPercent}% of this month's AI allowance${used}. The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
||||
for (const a of admins) {
|
||||
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
||||
.catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message));
|
||||
@@ -210,9 +243,13 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
||||
|
||||
let outcome = 'ok';
|
||||
let chargedCents = 0;
|
||||
let inputTokens = 0;
|
||||
let outputTokens = 0;
|
||||
try {
|
||||
const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS });
|
||||
chargedCents = Number(reply.chargedCents) || 0;
|
||||
inputTokens = tokens(reply.usage?.inputTokens) ?? 0;
|
||||
outputTokens = tokens(reply.usage?.outputTokens) ?? 0;
|
||||
remember(reply.status);
|
||||
await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message));
|
||||
return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } };
|
||||
@@ -223,7 +260,7 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
||||
if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false);
|
||||
throw mapped.error;
|
||||
} finally {
|
||||
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
||||
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents, inputTokens, outputTokens } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
||||
await pruneOldCalls();
|
||||
}
|
||||
}
|
||||
@@ -234,27 +271,30 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
||||
export async function usageThisMonth(now = new Date()) {
|
||||
const sast = new Date(now.getTime() + 2 * 3600 * 1000);
|
||||
const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000);
|
||||
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, chargedCents: true, createdAt: true } });
|
||||
const add = (m: Map<string, { uses: number; chargedCents: number }>, key: string, cents: number) => {
|
||||
const v = m.get(key) || { uses: 0, chargedCents: 0 };
|
||||
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, inputTokens: true, outputTokens: true, createdAt: true } });
|
||||
type Use = { uses: number; inputTokens: number; outputTokens: number };
|
||||
const add = (m: Map<string, Use>, key: string, c: { inputTokens: number; outputTokens: number }) => {
|
||||
const v = m.get(key) || { uses: 0, inputTokens: 0, outputTokens: 0 };
|
||||
v.uses++;
|
||||
v.chargedCents += cents;
|
||||
v.inputTokens += c.inputTokens;
|
||||
v.outputTokens += c.outputTokens;
|
||||
m.set(key, v);
|
||||
};
|
||||
const byPerson = new Map<string, { uses: number; chargedCents: number }>();
|
||||
const byHelper = new Map<string, { uses: number; chargedCents: number }>();
|
||||
const byDay = new Map<string, { uses: number; chargedCents: number }>();
|
||||
const byPerson = new Map<string, Use>();
|
||||
const byHelper = new Map<string, Use>();
|
||||
const byDay = new Map<string, Use>();
|
||||
for (const c of calls) {
|
||||
if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue;
|
||||
add(byPerson, c.userId || '', c.chargedCents);
|
||||
add(byHelper, c.helper, c.chargedCents);
|
||||
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c.chargedCents);
|
||||
add(byPerson, c.userId || '', c);
|
||||
add(byHelper, c.helper, c);
|
||||
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c);
|
||||
}
|
||||
const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } });
|
||||
const names = new Map(people.map(p => [p.id, p.name]));
|
||||
const most = (a: Use, b: Use) => (b.inputTokens + b.outputTokens) - (a.inputTokens + a.outputTokens) || b.uses - a.uses;
|
||||
return {
|
||||
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
||||
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
||||
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort(most),
|
||||
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort(most),
|
||||
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,9 +21,11 @@ const status = z.object({
|
||||
enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'),
|
||||
capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'),
|
||||
available: z.boolean().describe('false: the Hub couldn\'t be reached just now'),
|
||||
capCents: z.number().describe('The monthly allowance, in cents'),
|
||||
usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'),
|
||||
usedPercent: z.number(),
|
||||
usedPercent: z.number().describe('How much of this month\'s allowance is used (0–100)'),
|
||||
usedInputTokens: z.number().int().nullable().describe('Input tokens used this month by all the church\'s products (null from a Hub before 2.0.1)'),
|
||||
usedOutputTokens: z.number().int().nullable().describe('Output tokens used this month'),
|
||||
capInputTokens: z.number().int().nullable().describe('About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)'),
|
||||
capOutputTokens: z.number().int().nullable().describe('About how many output tokens the allowance holds, if half of it went on output'),
|
||||
renewsOn: z.string().nullable().describe('YYYY-MM-DD'),
|
||||
helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'),
|
||||
});
|
||||
@@ -33,7 +35,7 @@ const settings = z.object({
|
||||
dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'),
|
||||
});
|
||||
|
||||
const use = z.object({ uses: z.number().int(), chargedCents: z.number() });
|
||||
const use = z.object({ uses: z.number().int(), inputTokens: z.number().int(), outputTokens: z.number().int() });
|
||||
|
||||
export const getAiStatus = defineRoute({
|
||||
method: 'get',
|
||||
|
||||
@@ -28,9 +28,12 @@ const mockMail = jest.fn(async (_m: unknown) => undefined);
|
||||
jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true }));
|
||||
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) }));
|
||||
|
||||
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai';
|
||||
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, tokenText, _internal } from '../src/ai';
|
||||
|
||||
const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over });
|
||||
const hubStatus = (over = {}) => ({
|
||||
enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01',
|
||||
usedInputTokens: 40000, usedOutputTokens: 9000, capInputTokens: 1785000, capOutputTokens: 357000, ...over,
|
||||
});
|
||||
const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 };
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -55,7 +58,7 @@ describe('status', () => {
|
||||
|
||||
test('asks the Hub and caches its answer for a minute', async () => {
|
||||
mockPost.mockResolvedValue(hubStatus());
|
||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } });
|
||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedInputTokens: 40000, capOutputTokens: 357000, helpers: { draft_event: true } });
|
||||
await aiStatus();
|
||||
expect(mockPost).toHaveBeenCalledTimes(1);
|
||||
expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 });
|
||||
@@ -68,16 +71,32 @@ describe('status', () => {
|
||||
mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502));
|
||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
||||
});
|
||||
|
||||
test('the Hub\'s rand amounts never leave the site (2.3.0); a Hub before 2.0.1 sends no tokens', async () => {
|
||||
mockPost.mockResolvedValueOnce(hubStatus());
|
||||
const s = await aiStatus() as unknown as Record<string, unknown>;
|
||||
expect(s).not.toHaveProperty('capCents');
|
||||
expect(s).not.toHaveProperty('usedCents');
|
||||
clearAiStatusCache();
|
||||
mockPost.mockResolvedValueOnce({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01' });
|
||||
expect(await aiStatus()).toMatchObject({ usedPercent: 2, usedInputTokens: null, capInputTokens: null });
|
||||
});
|
||||
|
||||
test('tokens for people', () => {
|
||||
expect(['800', '45K', '1.2M', '2M', '12M']).toEqual([800, 45000, 1200000, 2000000, 12300000].map(tokenText));
|
||||
});
|
||||
});
|
||||
|
||||
describe('running a helper', () => {
|
||||
test('sends the request to the Hub, logs the call, returns the answer', async () => {
|
||||
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) });
|
||||
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({
|
||||
output: 'Hi all!', usage: { inputTokens: 1840, outputTokens: 420 }, chargedCents: 0.31, status: hubStatus({ usedInputTokens: 41840, usedOutputTokens: 9420 }),
|
||||
});
|
||||
const r = await runHelper('draft_message', 'u1', req);
|
||||
expect(r.output).toBe('Hi all!');
|
||||
expect(r.status.usedCents).toBe(100.31);
|
||||
expect(r.status).toMatchObject({ usedInputTokens: 41840, usedOutputTokens: 9420 });
|
||||
expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 });
|
||||
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]);
|
||||
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31, inputTokens: 1840, outputTokens: 420 }]);
|
||||
});
|
||||
|
||||
test('a helper switched off, or the cap reached, never reaches the Hub', async () => {
|
||||
@@ -102,7 +121,7 @@ describe('running a helper', () => {
|
||||
.mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) }));
|
||||
await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') });
|
||||
expect((await aiStatus()).capReached).toBe(true);
|
||||
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 });
|
||||
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0, inputTokens: 0, outputTokens: 0 });
|
||||
});
|
||||
|
||||
test('admins are emailed once a month at 80%', async () => {
|
||||
@@ -112,6 +131,9 @@ describe('running a helper', () => {
|
||||
await runHelper('draft_message', 'u1', req);
|
||||
expect(mockMail).toHaveBeenCalledTimes(1);
|
||||
expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]);
|
||||
const text = (mockMail.mock.calls[0] as unknown as [{ text: string }])[0].text;
|
||||
expect(text).toContain('40K input and 9K output tokens');
|
||||
expect(text).not.toMatch(/R\d/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
||||
} from '../src/ai/helpers';
|
||||
|
||||
const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} };
|
||||
const status = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: {} };
|
||||
const now = new Date('2026-10-30T08:00:00Z');
|
||||
|
||||
beforeEach(() => mockRun.mockReset());
|
||||
|
||||
@@ -683,7 +683,7 @@ describe('money (v1 handlers behind v2 routes)', () => {
|
||||
});
|
||||
|
||||
describe('AI helpers (2.0)', () => {
|
||||
const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
||||
const st = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
||||
|
||||
test('supervisors only', async () => {
|
||||
signedIn = { id: 's1', role: 'staff' };
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { useEffect, useState } from "react";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { loadAiStatus, renewsText } from "@/lib/ai";
|
||||
import { loadAiStatus, renewsText, tokenText } from "@/lib/ai";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Usage = V2Result<"/ai/usage", "get">["data"];
|
||||
@@ -18,8 +18,8 @@ const HELPERS: { key: Helper; label: string; where: string }[] = [
|
||||
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
||||
];
|
||||
|
||||
// Fractions of a cent add up: show R0.0123 below a rand.
|
||||
const money = (cents: number) => (cents > 0 && cents < 100 ? `R${(cents / 100).toFixed(4)}` : `R${(cents / 100).toFixed(2)}`);
|
||||
/** "12K in · 3K out" for a row of use. */
|
||||
const inOut = (u: { inputTokens: number; outputTokens: number }) => `${tokenText(u.inputTokens)} in · ${tokenText(u.outputTokens)} out`;
|
||||
|
||||
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
||||
export function AiTab({ active }: { active: boolean }) {
|
||||
@@ -53,7 +53,10 @@ export function AiTab({ active }: { active: boolean }) {
|
||||
|
||||
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||
const s = usage.status;
|
||||
const maxDay = Math.max(0.0001, ...usage.days.map(d => d.chargedCents));
|
||||
const dayTokens = (d: { inputTokens: number; outputTokens: number }) => d.inputTokens + d.outputTokens;
|
||||
const maxDay = Math.max(1, ...usage.days.map(dayTokens));
|
||||
const hasTokens = s.usedInputTokens != null && s.usedOutputTokens != null;
|
||||
const hasCap = s.capInputTokens != null && s.capOutputTokens != null && s.capInputTokens > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -72,14 +75,23 @@ export function AiTab({ active }: { active: boolean }) {
|
||||
<div className="rounded-lg border p-4">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<span className="text-sm font-medium">This month</span>
|
||||
<span className="text-sm text-gray-600">{money(s.usedCents)} of {money(s.capCents)} · renews on {renewsText(s.renewsOn)}</span>
|
||||
<span className="text-sm text-gray-600">{s.usedPercent}% used · renews on {renewsText(s.renewsOn)}</span>
|
||||
</div>
|
||||
{hasTokens && (
|
||||
<p className="mt-1 text-sm text-gray-700">
|
||||
{tokenText(s.usedInputTokens!)} input and {tokenText(s.usedOutputTokens!)} output tokens used
|
||||
{hasCap && <> of about {tokenText(s.capInputTokens!)} input and {tokenText(s.capOutputTokens!)} output</>}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
||||
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
||||
</div>
|
||||
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
||||
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
||||
<p className="mt-2 text-xs text-gray-500">Admins get an email when 80% is used.</p>
|
||||
<p className="mt-2 text-xs text-gray-500">
|
||||
Admins get an email when 80% is used.
|
||||
{hasCap && " The allowance in tokens is an estimate: it's what you'd get if half went on input (what's sent) and half on output (the answers). Repeated instructions are cached and cost less, so most sites get more input than this."}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -114,8 +126,8 @@ export function AiTab({ active }: { active: boolean }) {
|
||||
<h3 className="mb-2 font-medium">By person this month</h3>
|
||||
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
||||
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{money(p.chargedCents)}</td></tr>)}</tbody>
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{inOut(p)}</td></tr>)}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
@@ -123,16 +135,16 @@ export function AiTab({ active }: { active: boolean }) {
|
||||
<h3 className="mb-2 font-medium">By helper this month</h3>
|
||||
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
||||
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{money(h.chargedCents)}</td></tr>)}</tbody>
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{inOut(h)}</td></tr>)}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
{usage.days.length > 0 && (
|
||||
<div className="md:col-span-2">
|
||||
<h3 className="mb-2 font-medium">Per day</h3>
|
||||
<div className="flex h-20 items-end gap-1" aria-label="AI cost per day this month">
|
||||
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${money(d.chargedCents)}`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (d.chargedCents / maxDay) * 100)}%` }} />)}
|
||||
<div className="flex h-20 items-end gap-1" aria-label="AI tokens per day this month">
|
||||
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${inOut(d)} tokens`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (dayTokens(d) / maxDay) * 100)}%` }} />)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { V2Result } from "@/lib/apiV2";
|
||||
|
||||
/**
|
||||
* AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly
|
||||
* allowance in rand per licence. One status per page load is shared by every AI button
|
||||
* allowance per licence, shown here as tokens and a percentage (2.3.0). One status per page load is shared by every AI button
|
||||
* (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the
|
||||
* call that used up the allowance.
|
||||
*/
|
||||
@@ -12,7 +12,8 @@ export type AiStatus = V2Result<"/ai/status", "get">["data"];
|
||||
export type AiHelper = keyof AiStatus["helpers"];
|
||||
|
||||
const OFF: AiStatus = {
|
||||
enabled: false, capReached: false, available: true, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null,
|
||||
enabled: false, capReached: false, available: true, usedPercent: 0, renewsOn: null,
|
||||
usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null,
|
||||
helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false },
|
||||
};
|
||||
|
||||
@@ -46,6 +47,13 @@ export function currentAiStatus(): AiStatus | null {
|
||||
return current;
|
||||
}
|
||||
|
||||
/** "800", "45K", "1.2M": token counts for people (the allowance is shown in tokens, never rand). */
|
||||
export function tokenText(n: number): string {
|
||||
if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, "")}M`;
|
||||
if (n >= 1e3) return `${Math.round(n / 1e3)}K`;
|
||||
return String(n);
|
||||
}
|
||||
|
||||
/** "1 December" from "2026-12-01". */
|
||||
export function renewsText(renewsOn: string | null): string {
|
||||
if (!renewsOn) return "next month";
|
||||
|
||||
@@ -67449,16 +67449,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -67501,9 +67546,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -67581,16 +67628,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -67633,9 +67725,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -67695,8 +67789,15 @@
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"chargedCents": {
|
||||
"type": "number"
|
||||
"inputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"outputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"userId": {
|
||||
"type": [
|
||||
@@ -67710,7 +67811,8 @@
|
||||
},
|
||||
"required": [
|
||||
"uses",
|
||||
"chargedCents",
|
||||
"inputTokens",
|
||||
"outputTokens",
|
||||
"userId",
|
||||
"name"
|
||||
],
|
||||
@@ -67727,8 +67829,15 @@
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"chargedCents": {
|
||||
"type": "number"
|
||||
"inputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"outputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"helper": {
|
||||
"type": "string"
|
||||
@@ -67736,7 +67845,8 @@
|
||||
},
|
||||
"required": [
|
||||
"uses",
|
||||
"chargedCents",
|
||||
"inputTokens",
|
||||
"outputTokens",
|
||||
"helper"
|
||||
],
|
||||
"additionalProperties": false
|
||||
@@ -67752,8 +67862,15 @@
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"chargedCents": {
|
||||
"type": "number"
|
||||
"inputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"outputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"day": {
|
||||
"type": "string"
|
||||
@@ -67761,7 +67878,8 @@
|
||||
},
|
||||
"required": [
|
||||
"uses",
|
||||
"chargedCents",
|
||||
"inputTokens",
|
||||
"outputTokens",
|
||||
"day"
|
||||
],
|
||||
"additionalProperties": false
|
||||
@@ -68184,16 +68302,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -68236,9 +68399,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -68479,16 +68644,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -68531,9 +68741,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -68677,16 +68889,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -68729,9 +68986,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -68916,16 +69175,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -68968,9 +69272,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
@@ -69122,16 +69428,61 @@
|
||||
"type": "boolean",
|
||||
"description": "false: the Hub couldn't be reached just now"
|
||||
},
|
||||
"capCents": {
|
||||
"type": "number",
|
||||
"description": "The monthly allowance, in cents"
|
||||
},
|
||||
"usedCents": {
|
||||
"type": "number",
|
||||
"description": "Used this month, in cents (fractions of a cent)"
|
||||
},
|
||||
"usedPercent": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"description": "How much of this month's allowance is used (0–100)"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Output tokens used this month"
|
||||
},
|
||||
"capInputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||
},
|
||||
"renewsOn": {
|
||||
"description": "YYYY-MM-DD",
|
||||
@@ -69174,9 +69525,11 @@
|
||||
"enabled",
|
||||
"capReached",
|
||||
"available",
|
||||
"capCents",
|
||||
"usedCents",
|
||||
"usedPercent",
|
||||
"usedInputTokens",
|
||||
"usedOutputTokens",
|
||||
"capInputTokens",
|
||||
"capOutputTokens",
|
||||
"renewsOn",
|
||||
"helpers"
|
||||
],
|
||||
|
||||
+69
-31
@@ -37676,11 +37676,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -37739,11 +37744,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -37768,18 +37778,21 @@ export interface operations {
|
||||
};
|
||||
people: {
|
||||
uses: number;
|
||||
chargedCents: number;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
userId: string | null;
|
||||
name: string;
|
||||
}[];
|
||||
helpers: {
|
||||
uses: number;
|
||||
chargedCents: number;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
helper: string;
|
||||
}[];
|
||||
days: {
|
||||
uses: number;
|
||||
chargedCents: number;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
day: string;
|
||||
}[];
|
||||
};
|
||||
@@ -37945,11 +37958,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -38041,11 +38059,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -38127,11 +38150,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -38220,11 +38248,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
@@ -38313,11 +38346,16 @@ export interface operations {
|
||||
capReached: boolean;
|
||||
/** @description false: the Hub couldn't be reached just now */
|
||||
available: boolean;
|
||||
/** @description The monthly allowance, in cents */
|
||||
capCents: number;
|
||||
/** @description Used this month, in cents (fractions of a cent) */
|
||||
usedCents: number;
|
||||
/** @description How much of this month's allowance is used (0–100) */
|
||||
usedPercent: number;
|
||||
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||
usedInputTokens: number | null;
|
||||
/** @description Output tokens used this month */
|
||||
usedOutputTokens: number | null;
|
||||
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||
capInputTokens: number | null;
|
||||
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||
capOutputTokens: number | null;
|
||||
/** @description YYYY-MM-DD */
|
||||
renewsOn: string | null;
|
||||
/** @description Each helper switched on or off in Site settings → AI */
|
||||
|
||||
@@ -181,6 +181,32 @@ Secrets stay in each product's own `.env`, never in `church.env`.
|
||||
| `adopt <church> --undo` | Yes (decision 26): goes back to the old folder and the 2.1.x it ran, within the days the old folder is kept |
|
||||
| `add <church> <product>` | **Later** (phase 3), when there's a second product to add |
|
||||
|
||||
**Built 2026-11-12** (branch `feat/crosscode-script`), as above, with these details settled while
|
||||
writing it:
|
||||
|
||||
- **Run as root.** `church.env` is root-only (mode 600), so every command needs root; each app's
|
||||
commands (git, npm, Prisma, PM2) run as its app user through `sudo -u`.
|
||||
- `church.env` is read as data, never sourced: only `CHURCH`, `PRODUCTS`, `ADDRESS` and
|
||||
`<PRODUCT>_*` keys are taken.
|
||||
- `--allow-local-changes` replaces `ALLOW_LOCAL_CHANGES=1` (the variable still works). `--check`
|
||||
never passes with changes.
|
||||
- "Latest" only counts plain `events@x.y.z` tags, so test tags such as `events@2.2.0-test` are
|
||||
only ever deployed with `--version`.
|
||||
- `--every-church` stops at the first church that fails (its products roll back as usual), and
|
||||
names the churches it didn't reach.
|
||||
- `install`: the app user defaults to `cc-<church>`, PM2 names to `<church>-events-backend` /
|
||||
`-frontend`, the database to `<church>_events`, and ports to the first free ones from 5000
|
||||
(API) and 3000 (web), counting every church's `church.env` and anything listening.
|
||||
- `adopt` writes `church.env` only once the switch has worked, and refuses to start if nginx
|
||||
refers to the old folder by path (it gets renamed). It also records `EVENTS_OLD_DIR`,
|
||||
`EVENTS_OLD_REF` and `EVENTS_ADOPTED_AT` for `--undo` and `status`.
|
||||
- `adopt --undo` refuses if the new checkout has migrations the old release doesn't have, and
|
||||
moves `/var/www/sites/<church>` aside to `.undone-<church>-<time>` (not deleted), so `adopt`
|
||||
can be run again.
|
||||
- Tests: `npm run lint:scripts` (shellcheck) and `npm run test:scripts` (bats: 47 tests,
|
||||
including deploys against a local git origin with stub hooks for the checks, requirements,
|
||||
order, rollback and `--every-church`). Both are part of `npm run check`.
|
||||
|
||||
**Requirement check** (decision 24): before anything is touched, read the target version's
|
||||
heading in `apps/<product>/WHATS-NEW.md`. Refuse the deploy if a `— requires <product> <version>`
|
||||
isn't met by the installed sibling or by this same run. Nothing in 2.2.0 requires anything, but
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|
||||
|-------|------|-------|
|
||||
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04 (`contracts@1.0.0`, `contracts@1.1.0`). Not published to a registry (decision 22): the Hub gets a packed release committed to its repo |
|
||||
| 1 | Hub 2.0.0 | **Released** 2026-11-05 (`events-hub` `v2.0.0`; `docs/HUB-2.0-PLAN.md` there). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). crosscode-site's address prices are merged, **not deployed yet** |
|
||||
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **Still to do:** the `crosscode` script and `adopt` (§4–5), VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
|
||||
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **The `crosscode` script and `adopt` (§4–5) are written** (branch `feat/crosscode-script`, 2026-11-12; shellcheck and 47 bats tests pass, not yet run on a server). **Still to do:** VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
|
||||
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | Not started (`TwoFactorMethod` enum in Events' `prisma/schema.prisma`) |
|
||||
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.2.0): server agent, installs / scheduled updates / uninstalls from the Hub, server stats | **Planned** 2026-11-12 in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) (ROADMAP decisions 27–37). Starts after 1b; can run alongside 1c |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
|
||||
|
||||
+12
-3
@@ -205,15 +205,24 @@ POST /api/installs/ai/status
|
||||
X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
|
||||
{ "protocolVersion": 1 }
|
||||
→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4,
|
||||
"usedPercent": 16, "renewsOn": "2026-12-01" }
|
||||
"usedPercent": 16, "renewsOn": "2026-12-01",
|
||||
"usedInputTokens": 412000, "usedOutputTokens": 61000, // Hub 2.0.1+
|
||||
"capInputTokens": 3571000, "capOutputTokens": 714000 } // Hub 2.0.1+
|
||||
```
|
||||
|
||||
- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't
|
||||
active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up.
|
||||
- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it
|
||||
renews on 1 December"). Reached means there isn't room left for even a small call.
|
||||
- Amounts are cents (rand) as **charged** to the church, with fractions (a call costs a fraction of a
|
||||
cent). The month is South African time; `renewsOn` is the 1st of the next month.
|
||||
- **Churches see tokens, never rand** (Hub 2.0.1, Cross Events 2.3.0). `usedInputTokens` /
|
||||
`usedOutputTokens` are this month's tokens over all the church's installs (input counts cached
|
||||
prompt tokens). `capInputTokens` / `capOutputTokens` are an **estimate** of the allowance: what half
|
||||
the cap buys as input and half as output, at the current model price, exchange rate and markup,
|
||||
rounded down to a thousand. `usedPercent` is exact (it's worked out in rand). Installs show the
|
||||
tokens and the percentage, and don't pass the cents on.
|
||||
- `capCents` / `usedCents` are cents (rand) as **charged** to the church, with fractions (a call costs
|
||||
a fraction of a cent), for the Hub and for installs before Cross Events 2.3.0. The month is South
|
||||
African time; `renewsOn` is the 1st of the next month.
|
||||
|
||||
### A helper call
|
||||
|
||||
|
||||
Generated
+1056
-5
File diff suppressed because it is too large
Load Diff
+5
-1
@@ -13,9 +13,11 @@
|
||||
"scripts": {
|
||||
"build": "npm run build --workspaces --if-present",
|
||||
"test": "npm test --workspaces --if-present",
|
||||
"test:scripts": "bats scripts/tests",
|
||||
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||
"lint": "eslint .",
|
||||
"check": "npm run lint && npm run typecheck && npm test && npm run build"
|
||||
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh",
|
||||
"check": "npm run lint && npm run lint:scripts && npm run typecheck && npm test && npm run test:scripts && npm run build"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
@@ -26,9 +28,11 @@
|
||||
"@playwright/test": "^1.64.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^20.19.43",
|
||||
"bats": "^1.13.0",
|
||||
"concurrently": "^9.2.1",
|
||||
"eslint": "^10.13.0",
|
||||
"jest": "^30.5.2",
|
||||
"shellcheck": "^4.1.0",
|
||||
"ts-jest": "^29.4.15",
|
||||
"tsup": "^9.0.0",
|
||||
"typescript": "^5.9.3",
|
||||
|
||||
@@ -65,6 +65,26 @@
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"capInputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -25,6 +25,26 @@
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"usedInputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"usedOutputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"capInputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"capOutputTokens": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -269,6 +269,12 @@ export const aiStatusSchema = z.object({
|
||||
usedCents: z.number().nonnegative(),
|
||||
usedPercent: z.number().nonnegative(),
|
||||
renewsOn: dateSchema,
|
||||
// Hub 2.0.1: tokens, which is what churches see (the cents are for the Hub and older installs).
|
||||
// The allowance is approximate: half the cap priced as input, half as output.
|
||||
usedInputTokens: count.optional(),
|
||||
usedOutputTokens: count.optional(),
|
||||
capInputTokens: count.optional(),
|
||||
capOutputTokens: count.optional(),
|
||||
});
|
||||
export type AiStatus = z.infer<typeof aiStatusSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# shellcheck settings for the crosscode script (npm run lint:scripts).
|
||||
source-path=SCRIPTDIR
|
||||
external-sources=true
|
||||
Executable
+77
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env bash
|
||||
# crosscode: installs, updates and moves church installs on this server (ROADMAP-v3 §8,
|
||||
# docs/EVENTS-2.2-PLAN.md §4). `crosscode help` lists the commands.
|
||||
#
|
||||
# On a server this is a checkout of crosscode-platform's main in /opt/crosscode/tools, linked as
|
||||
# /usr/local/bin/crosscode. Every run first updates that checkout (git pull --ff-only), then runs
|
||||
# from a copy, so a checkout never changes the script while it runs.
|
||||
#
|
||||
# Environment: CROSSCODE_SITES (default /var/www/sites), CROSSCODE_REPO (the monorepo's git URL),
|
||||
# CROSSCODE_TOOLS_DIR (default /opt/crosscode/tools), CROSSCODE_NO_UPDATE=1 (skip the update).
|
||||
set -Eeuo pipefail
|
||||
|
||||
CROSSCODE_TOOLS_DIR="${CROSSCODE_TOOLS_DIR:-/opt/crosscode/tools}"
|
||||
|
||||
if [ -z "${CROSSCODE_HOME:-}" ]; then
|
||||
src="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
|
||||
root="$(cd "$src/.." && pwd)"
|
||||
if [ "${CROSSCODE_NO_UPDATE:-}" != 1 ] && [ "$root" = "$CROSSCODE_TOOLS_DIR" ] && [ -d "$root/.git" ]; then
|
||||
git -C "$root" pull --ff-only --quiet ||
|
||||
printf '!!> Couldn'"'"'t update %s; running the version that is there.\n' "$root" >&2
|
||||
fi
|
||||
copy="$(mktemp -d /tmp/crosscode.XXXXXX)"
|
||||
cp -R "$src/." "$copy/"
|
||||
CROSSCODE_HOME="$copy" CROSSCODE_FROM="$root" exec bash "$copy/crosscode" "$@"
|
||||
fi
|
||||
|
||||
# Running from the copy: remove it afterwards (only ever a mktemp folder, never a checkout).
|
||||
if [[ "$CROSSCODE_HOME" == /tmp/crosscode.* ]]; then
|
||||
trap 'rm -rf "$CROSSCODE_HOME"' EXIT
|
||||
fi
|
||||
|
||||
# shellcheck source=lib/common.sh
|
||||
source "$CROSSCODE_HOME/lib/common.sh"
|
||||
# shellcheck source=lib/deploy.sh
|
||||
source "$CROSSCODE_HOME/lib/deploy.sh"
|
||||
# shellcheck source=lib/status.sh
|
||||
source "$CROSSCODE_HOME/lib/status.sh"
|
||||
# shellcheck source=lib/install.sh
|
||||
source "$CROSSCODE_HOME/lib/install.sh"
|
||||
# shellcheck source=lib/adopt.sh
|
||||
source "$CROSSCODE_HOME/lib/adopt.sh"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" rev-parse --short HEAD 2>/dev/null || echo 'unknown version'))
|
||||
|
||||
crosscode deploy <church> [events] [website] [app] update Accounts and the products named
|
||||
crosscode deploy --every-church [events] … the same, for every church here
|
||||
crosscode deploy <church> … --check only the checks; changes nothing
|
||||
crosscode status [<church>] versions, latest releases, health
|
||||
crosscode install <church> --products events --domain <address> a new church
|
||||
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
|
||||
crosscode adopt <church> --undo go back to the old folder (within 14 days)
|
||||
crosscode help [<command>] this, or a command's options
|
||||
|
||||
Churches live in $CROSSCODE_SITES/<church>/ (church.env, one checkout per product).
|
||||
EOF
|
||||
}
|
||||
|
||||
command="${1:-help}"
|
||||
[ $# -gt 0 ] && shift
|
||||
case "$command" in
|
||||
deploy) cmd_deploy "$@" ;;
|
||||
status) cmd_status "$@" ;;
|
||||
install) cmd_install "$@" ;;
|
||||
adopt) cmd_adopt "$@" ;;
|
||||
add) die "\`crosscode add\` comes with the second product (phase 3)." ;;
|
||||
help|-h|--help)
|
||||
case "${1:-}" in
|
||||
deploy) deploy_usage ;;
|
||||
status) status_usage ;;
|
||||
install) install_usage ;;
|
||||
adopt) adopt_usage ;;
|
||||
*) usage ;;
|
||||
esac ;;
|
||||
*) usage; die "Unknown command \"$command\"." ;;
|
||||
esac
|
||||
@@ -0,0 +1,289 @@
|
||||
# shellcheck shell=bash
|
||||
# crosscode adopt: moves an existing Cross Events install (a hope-events checkout at v2.1.x) onto
|
||||
# the monorepo, into /var/www/sites/<church>/events (EVENTS-2.2-PLAN §5, decisions 25 and 26).
|
||||
# The new checkout is built next to the running install, then PM2 switches over (seconds of
|
||||
# downtime). The old folder isn't changed, so a failed switch just starts it again.
|
||||
|
||||
ADOPT_KEEP_DAYS=14
|
||||
ADOPT_SUFFIX=".pre-2.2.0"
|
||||
|
||||
adopt_usage() {
|
||||
cat <<'EOF'
|
||||
crosscode adopt <church> --events-dir /var/www/<old folder> [options]
|
||||
crosscode adopt <church> --undo
|
||||
|
||||
Moves an existing Cross Events install (hope-events at v2.1.x) to the monorepo, in
|
||||
/var/www/sites/<church>/events. The old install keeps serving while the new one builds. The old
|
||||
folder is kept as <old>.pre-2.2.0 for 14 days, for --undo.
|
||||
|
||||
--events-dir <dir> the existing install (required)
|
||||
--version events@x.y.z the release to move to (default: the latest events@2.2.x)
|
||||
--address <domain> the church's address, e.g. hopefamily.co.za (default: the Events
|
||||
domain without "events.")
|
||||
--undo go back to the old folder and the 2.1.x it ran
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_adopt() {
|
||||
local church="" old="" version="" address="" undo=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--events-dir) [ $# -ge 2 ] || die "--events-dir needs a folder."; old="${2%/}"; shift 2 ;;
|
||||
--version) [ $# -ge 2 ] || die "--version needs events@x.y.z."; version="$2"; shift 2 ;;
|
||||
--address) [ $# -ge 2 ] || die "--address needs a domain."; address="$2"; shift 2 ;;
|
||||
--undo) undo=1; shift ;;
|
||||
-h|--help) adopt_usage; return 0 ;;
|
||||
-*) die "Unknown option $1 (crosscode adopt --help)." ;;
|
||||
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$church" ] || { adopt_usage; die "Name the church."; }
|
||||
valid_slug "$church" || die "\"$church\" isn't a church name (a-z, 0-9 and -, starting with a letter)."
|
||||
[ "$undo" = 1 ] || [ -n "$old" ] || { adopt_usage; die "--events-dir is required."; }
|
||||
[ -z "$version" ] || [[ "$version" =~ ^events@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version: expected events@x.y.z."
|
||||
require_root
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/events.sh"
|
||||
if [ "$undo" = 1 ]; then
|
||||
adopt_undo "$church"
|
||||
else
|
||||
adopt_run "$church" "$old" "$version" "$address"
|
||||
fi
|
||||
}
|
||||
|
||||
# rewrite_ecosystem <old dir> <new app dir>, PM2 config on stdin → stdout: absolute paths into
|
||||
# the old install (e.g. cwd: '/var/www/hope-events/backend') point into the new one instead.
|
||||
# __dirname-based paths need nothing. Only whole paths match (/var/www/hope-events2 doesn't).
|
||||
rewrite_ecosystem() {
|
||||
local old new
|
||||
old="$(printf '%s' "${1%/}" | sed 's/[][\.*^$#/]/\\&/g')"
|
||||
new="$(printf '%s' "${2%/}" | sed 's/[\&#]/\\&/g')"
|
||||
sed -E "s#([\"'\`])${old}(/|[\"'\`])#\\1${new}\\2#g"
|
||||
}
|
||||
|
||||
# Ignored files in a checkout's folder (the install's own data, not in git), one per line.
|
||||
ignored_files_in() { git_in "$1" ls-files --others --ignored --exclude-standard -- "$2"; }
|
||||
|
||||
adopt_run() {
|
||||
local church="$1" old="$2" version="$3" address="$4"
|
||||
local sites new app user oldref changes backend frontend api web dburl db domain major
|
||||
sites="$(church_dir "$church")"
|
||||
new="$sites/events"
|
||||
app="$new/apps/events"
|
||||
|
||||
# ── 1. Checks ──────────────────────────────────────────────────────────────────────────────
|
||||
step "Checks"
|
||||
[ -d "$old/.git" ] && [ -d "$old/backend" ] || die "$old isn't a Cross Events install (no .git or backend/)."
|
||||
oldref="$(git_in "$old" describe --tags --exact-match 2>/dev/null || true)"
|
||||
[[ "$oldref" =~ ^v2\.1\.[0-9]+$ ]] ||
|
||||
die "$old is on ${oldref:-an untagged commit}, not a v2.1.x release. Update it with its scripts/deploy.sh to v2.1.1 first."
|
||||
changes="$(local_changes "$old" | awk 'substr($0, 4) != "ecosystem.config.js"')"
|
||||
if [ -n "$changes" ]; then
|
||||
warn "Files in $old were changed or added by hand:"
|
||||
printf '%s\n' "$changes" | sed 's/^/ /' >&2
|
||||
die "Sort them out first (as scripts/deploy.sh --check explains). Nothing was changed."
|
||||
fi
|
||||
if [ -f "$(church_env_path "$church")" ]; then
|
||||
church_env_read "$(church_env_path "$church")"
|
||||
[ -n "$(pvar events ADOPTED_AT)" ] && { info "$church is already adopted ($(pvar events DIR)). Nothing to do."; return 0; }
|
||||
die "$(church_env_path "$church") already exists: $church is already set up on this server."
|
||||
fi
|
||||
[ ! -e "$new" ] || die "$new exists from an adopt that didn't finish. The old install is still the one running: remove $new and run adopt again."
|
||||
[ ! -e "$old$ADOPT_SUFFIX" ] || die "$old$ADOPT_SUFFIX already exists. Move it away first."
|
||||
if grep -rlsF -- "$old" /etc/nginx/ >/dev/null 2>&1; then
|
||||
warn "nginx refers to $old directly:"
|
||||
grep -rlsF -- "$old" /etc/nginx/ | sed 's/^/ /' >&2
|
||||
die "Change those to proxy to the app (or to the new folder, $app) first: the old folder gets renamed."
|
||||
fi
|
||||
[ -f "$old/ecosystem.config.js" ] || die "$old has no ecosystem.config.js, so its PM2 names aren't known."
|
||||
major="$(node_major)"
|
||||
[ "$major" -ge "$CROSSCODE_NODE_MIN" ] || die "This server runs Node $(node -v 2>/dev/null || echo '(none)'); 2.2.0 needs $CROSSCODE_NODE_MIN or later."
|
||||
|
||||
# ── 2. What the install already has ───────────────────────────────────────────────────────
|
||||
user="$(stat -c %U "$old")"
|
||||
id "$user" >/dev/null 2>&1 && [ "$user" != root ] || die "$old is owned by $user; expected the app user."
|
||||
# shellcheck disable=SC2016
|
||||
read -r backend frontend web < <(run_as "$user" "$old" node -e '
|
||||
const apps = require(process.argv[1]).apps || [];
|
||||
const b = apps.find(a => /backend/.test(a.name)) || apps[0] || {};
|
||||
const f = apps.find(a => /frontend/.test(a.name)) || apps[1] || {};
|
||||
const m = /-p\s+(\d+)/.exec([].concat(f.args || []).join(" "));
|
||||
console.log(b.name || "", f.name || "", m ? m[1] : "3000");' "$old/ecosystem.config.js") ||
|
||||
die "Couldn't read the PM2 names from $old/ecosystem.config.js."
|
||||
[ -n "$backend" ] && [ -n "$frontend" ] || die "Couldn't find the backend and frontend apps in $old/ecosystem.config.js."
|
||||
api="$(env_value "$old/backend/.env" PORT)"
|
||||
api="${api:-5000}"
|
||||
dburl="$(env_value "$old/backend/.env" DATABASE_URL)"
|
||||
db="$(db_name_from_url "$dburl")"
|
||||
[ -n "$db" ] || die "No DATABASE_URL in $old/backend/.env."
|
||||
domain="$(host_from_url "$(env_value "$old/backend/.env" FRONTEND_URL)")"
|
||||
if [ -z "$address" ]; then
|
||||
[[ "$domain" == events.* ]] || die "The Events domain is \"$domain\"; give the church's address with --address."
|
||||
address="${domain#events.}"
|
||||
fi
|
||||
info "App user $user, PM2 $backend + $frontend, ports api $api web $web, database $db, domain $domain"
|
||||
|
||||
# church.env is written at the end; until then the values live in CENV only.
|
||||
CENV=()
|
||||
church_env_set CHURCH "$church"
|
||||
church_env_set PRODUCTS events
|
||||
church_env_set ADDRESS "$address"
|
||||
church_env_set EVENTS_DIR "$new"
|
||||
church_env_set EVENTS_DOMAIN "$domain"
|
||||
church_env_set EVENTS_PM2 "$backend $frontend"
|
||||
church_env_set EVENTS_PORTS "$api $web"
|
||||
church_env_set EVENTS_DB "$db"
|
||||
church_env_set EVENTS_USER "$user"
|
||||
|
||||
# ── 3. The new checkout ────────────────────────────────────────────────────────────────────
|
||||
step "New checkout in $new"
|
||||
mkdir -p "$sites"
|
||||
chmod 755 "$CROSSCODE_SITES" "$sites"
|
||||
mkdir "$new"
|
||||
chown "$user:$user" "$new"
|
||||
run_as "$user" "$new" git clone --quiet "$CROSSCODE_REPO" .
|
||||
if [ -z "$version" ]; then
|
||||
version="$(git_in "$new" tag -l 'events@2.2.*' | latest_tag_from events)"
|
||||
[ -n "$version" ] || die "No events@2.2.x release tag yet. Remove $new; nothing else changed."
|
||||
fi
|
||||
git_in "$new" rev-parse -q --verify "refs/tags/$version" >/dev/null || die "There's no tag $version. Remove $new; nothing else changed."
|
||||
run_as "$user" "$new" git checkout -q --detach "$version"
|
||||
info "At $version"
|
||||
|
||||
# ── 4. The install's own files ────────────────────────────────────────────────────────────
|
||||
step "Copying the install's own files"
|
||||
local f
|
||||
cp -p "$old/backend/.env" "$app/backend/.env"
|
||||
for f in "$old"/frontend/.env*; do
|
||||
[ -f "$f" ] && [ "$(basename "$f")" != .env.example ] && cp -p "$f" "$app/frontend/"
|
||||
done
|
||||
rewrite_ecosystem "$old" "$app" < "$old/ecosystem.config.js" > "$app/ecosystem.config.js"
|
||||
chown "$user:$user" "$app/ecosystem.config.js"
|
||||
adopt_sync_data "$old" "$app" ""
|
||||
info "Uploads (this can take a while; the site is still running)"
|
||||
mkdir -p "$app/backend/public/uploads"
|
||||
rsync -a "$old/backend/public/uploads/" "$app/backend/public/uploads/"
|
||||
[ -z "$(local_changes "$new")" ] || die "The copied files show up as changes in $new (git status). Remove $new; nothing else changed."
|
||||
|
||||
# ── 5. Build, next to the running install ─────────────────────────────────────────────────
|
||||
step "Installing and building $version (the old install keeps serving)"
|
||||
events_install_deps "$new" "$user"
|
||||
events_build "$new" "$user"
|
||||
local expected
|
||||
expected="$(events_expected_version "$new")"
|
||||
if events_pending_migrations "$new" "$user"; then
|
||||
die "$version has database migrations that aren't applied (or the database can't be read). adopt only moves the install; run it at a 2.2.x without migrations. Remove $new; nothing else changed."
|
||||
fi
|
||||
|
||||
# ── 6. Switch over: the only downtime ─────────────────────────────────────────────────────
|
||||
step "Switching over"
|
||||
info "Database backup"
|
||||
events_backup "$new" "$user"
|
||||
info "Last copy of uploads and data"
|
||||
adopt_sync_data "$old" "$app" --delete
|
||||
rsync -a --delete "$old/backend/public/uploads/" "$app/backend/public/uploads/"
|
||||
set +e
|
||||
(
|
||||
set -e
|
||||
run_as "$user" "$new" pm2 delete "$backend" "$frontend"
|
||||
run_as "$user" "$app" pm2 start ecosystem.config.js
|
||||
run_as "$user" "$app" pm2 save
|
||||
wait_for_version "$(events_health_url)" "$expected" 60
|
||||
)
|
||||
local rc=$?
|
||||
set -e
|
||||
if [ "$rc" != 0 ]; then
|
||||
warn "The new install didn't come up. Starting the old one again."
|
||||
run_as "$user" "$old" pm2 delete "$backend" "$frontend" >/dev/null 2>&1 || true
|
||||
run_as "$user" "$old" pm2 start ecosystem.config.js
|
||||
run_as "$user" "$old" pm2 save
|
||||
if wait_for_version "$(events_health_url)" "${oldref#v}" 60; then
|
||||
die "Back on $oldref from $old, as before. $new is left for a look (pm2 logs); remove it before trying again."
|
||||
fi
|
||||
die "The old install didn't come back either: check now (pm2 status, pm2 logs)."
|
||||
fi
|
||||
|
||||
# ── 7. Keep the old folder for --undo, and record the church ──────────────────────────────
|
||||
mv "$old" "$old$ADOPT_SUFFIX"
|
||||
church_env_set EVENTS_OLD_DIR "$old$ADOPT_SUFFIX"
|
||||
church_env_set EVENTS_OLD_REF "$oldref"
|
||||
church_env_set EVENTS_ADOPTED_AT "$(date +%F)"
|
||||
church_env_write "$(church_env_path "$church")"
|
||||
step "Adopted: $church runs $version from $new"
|
||||
info "The old folder is $old$ADOPT_SUFFIX, kept $ADOPT_KEEP_DAYS days for \`crosscode adopt $church --undo\`."
|
||||
info "Updates from now on: crosscode deploy $church events"
|
||||
}
|
||||
|
||||
# adopt_sync_data <from install> <to app dir> [--delete]: the backend's data/*.json that aren't
|
||||
# in git, and its backups.
|
||||
adopt_sync_data() {
|
||||
local from="$1" to="$2" del="$3" f
|
||||
while IFS= read -r f; do
|
||||
[ -n "$f" ] || continue
|
||||
mkdir -p "$(dirname "$to/$f")"
|
||||
cp -p "$from/$f" "$to/$f"
|
||||
done < <(ignored_files_in "$from" backend/data)
|
||||
if [ -d "$from/backend/backups" ]; then
|
||||
mkdir -p "$to/backend/backups"
|
||||
# shellcheck disable=SC2086
|
||||
rsync -a $del "$from/backend/backups/" "$to/backend/backups/"
|
||||
fi
|
||||
}
|
||||
|
||||
# adopt --undo: back to the old folder and the 2.1.x it ran, while it's kept.
|
||||
adopt_undo() {
|
||||
local church="$1" new app user oldkept orig oldref backend frontend extra
|
||||
load_church "$church"
|
||||
new="$(pvar events DIR)"
|
||||
app="$new/apps/events"
|
||||
user="$(pvar events USER)"
|
||||
oldkept="$(pvar events OLD_DIR)"
|
||||
oldref="$(pvar events OLD_REF)"
|
||||
read -r backend frontend <<< "$(pvar events PM2)"
|
||||
[ -n "$oldkept" ] || die "$church wasn't moved with adopt, so there's nothing to go back to."
|
||||
[ -d "$oldkept" ] || die "The old folder $oldkept is gone, so adopt --undo can't go back any more."
|
||||
orig="${oldkept%"$ADOPT_SUFFIX"}"
|
||||
[ ! -e "$orig" ] || die "$orig exists again; move it away first."
|
||||
|
||||
step "Checks"
|
||||
# The database must still suit 2.1.x: no migrations the old release doesn't have.
|
||||
extra="$(comm -13 \
|
||||
<(find "$oldkept/backend/prisma/migrations" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort) \
|
||||
<(find "$app/backend/prisma/migrations" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort))"
|
||||
[ -z "$extra" ] || die "$(checkout_ref "$new" events) has database migrations $oldref doesn't know ($(echo "$extra" | tr '\n' ' ')). Going back would break it; restore a backup instead."
|
||||
|
||||
step "Database backup"
|
||||
events_backup "$new" "$user"
|
||||
|
||||
step "Going back to $oldref in $orig"
|
||||
mv "$oldkept" "$orig"
|
||||
info "Copying back uploads and data added since"
|
||||
adopt_sync_data "$app" "$orig" ""
|
||||
rsync -a "$app/backend/public/uploads/" "$orig/backend/public/uploads/"
|
||||
set +e
|
||||
(
|
||||
set -e
|
||||
run_as "$user" "$orig" pm2 delete "$backend" "$frontend"
|
||||
run_as "$user" "$orig" pm2 start ecosystem.config.js
|
||||
run_as "$user" "$orig" pm2 save
|
||||
wait_for_version "$(events_health_url)" "${oldref#v}" 60
|
||||
)
|
||||
local rc=$?
|
||||
set -e
|
||||
if [ "$rc" != 0 ]; then
|
||||
warn "$oldref didn't come up. Starting $(checkout_ref "$new" events) from $new again."
|
||||
run_as "$user" "$app" pm2 delete "$backend" "$frontend" >/dev/null 2>&1 || true
|
||||
mv "$orig" "$oldkept"
|
||||
run_as "$user" "$app" pm2 start ecosystem.config.js
|
||||
run_as "$user" "$app" pm2 save
|
||||
die "Undo failed; $church runs from $new as before."
|
||||
fi
|
||||
|
||||
# The church's folder goes aside (not deleted), so it's no longer a church here and adopt can
|
||||
# be run again.
|
||||
local aside
|
||||
aside="$CROSSCODE_SITES/.undone-$church-$(date +%Y%m%d%H%M%S)"
|
||||
mv "$(church_dir "$church")" "$aside"
|
||||
step "Undone: $church runs $oldref from $orig again"
|
||||
info "The monorepo checkout is in $aside; remove it when you no longer need it."
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared helpers for the crosscode script: logging, users, church.env, tags, versions, health.
|
||||
# Only functions and defaults: sourcing this file changes nothing (the bats tests rely on that).
|
||||
|
||||
CROSSCODE_SITES="${CROSSCODE_SITES:-/var/www/sites}"
|
||||
CROSSCODE_REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode-platform.git}"
|
||||
# Every deploy runs the products in this order (ROADMAP §8): Accounts first, since others sign in
|
||||
# through it.
|
||||
PRODUCT_ORDER=(accounts events website app)
|
||||
# Products this version of the script can deploy (a products/<name>.sh exists for each).
|
||||
SUPPORTED_PRODUCTS=(events)
|
||||
# Releases older than this get a warning; older than CROSSCODE_NODE_MIN the deploy is refused.
|
||||
CROSSCODE_NODE_MIN=20
|
||||
CROSSCODE_NODE_WARN=22
|
||||
|
||||
# ── Logging ──────────────────────────────────────────────────────────────────────────────────
|
||||
step() { printf '==> %s\n' "$*"; }
|
||||
info() { printf ' %s\n' "$*"; }
|
||||
warn() { printf '!!> %s\n' "$*" >&2; }
|
||||
die() { printf '!!> %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
# ── Small checks ─────────────────────────────────────────────────────────────────────────────
|
||||
require_root() {
|
||||
# The bats tests run deploys against stub products as an ordinary user.
|
||||
[ "${CROSSCODE_TEST:-}" = 1 ] && return 0
|
||||
[ "$(id -u)" = 0 ] || die "Run this as root (sudo crosscode …): it reads church.env (root only) and runs each app as its own user."
|
||||
}
|
||||
|
||||
# A church's short name: lower case letters, digits and -, starting with a letter.
|
||||
valid_slug() { [[ "$1" =~ ^[a-z][a-z0-9-]{0,39}$ ]]; }
|
||||
|
||||
is_known_product() {
|
||||
local p
|
||||
for p in "${PRODUCT_ORDER[@]}"; do [ "$p" = "$1" ] && return 0; done
|
||||
return 1
|
||||
}
|
||||
|
||||
is_supported_product() {
|
||||
local p
|
||||
for p in "${SUPPORTED_PRODUCTS[@]}"; do [ "$p" = "$1" ] && return 0; done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A product's place in the deploy order (0 for accounts).
|
||||
product_index() {
|
||||
local i
|
||||
for i in "${!PRODUCT_ORDER[@]}"; do [ "${PRODUCT_ORDER[$i]}" = "$1" ] && { echo "$i"; return 0; }; done
|
||||
echo 99
|
||||
}
|
||||
|
||||
# The products given (any order, repeats allowed), printed in deploy order, one per line.
|
||||
in_product_order() {
|
||||
local p q
|
||||
for p in "${PRODUCT_ORDER[@]}"; do
|
||||
for q in "$@"; do
|
||||
if [ "$p" = "$q" ]; then echo "$p"; break; fi
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
# Upper case for church.env keys: events → EVENTS.
|
||||
upper() { printf '%s' "$1" | tr '[:lower:]-' '[:upper:]_'; }
|
||||
|
||||
# ── Running things as the app user ───────────────────────────────────────────────────────────
|
||||
# run_as <user> <dir> <command…>: runs the command in <dir> as <user> (directly when we already
|
||||
# are that user), with that user's HOME so PM2 and npm use their own folders.
|
||||
run_as() {
|
||||
local user="$1" dir="$2"
|
||||
shift 2
|
||||
if [ "$(id -un)" = "$user" ]; then
|
||||
(cd -- "$dir" && "$@")
|
||||
else
|
||||
sudo -u "$user" -H -- bash -c 'cd -- "$1" && shift && exec "$@"' crosscode-run "$dir" "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# ── church.env ───────────────────────────────────────────────────────────────────────────────
|
||||
# /var/www/sites/<church>/church.env holds names, folders, domains and ports (never secrets). It is
|
||||
# read as data, never sourced: only KEY=VALUE lines with known keys are taken, into CENV.
|
||||
declare -gA CENV=()
|
||||
|
||||
church_dir() { printf '%s/%s' "$CROSSCODE_SITES" "$1"; }
|
||||
church_env_path() { printf '%s/%s/church.env' "$CROSSCODE_SITES" "$1"; }
|
||||
|
||||
church_env_key_ok() {
|
||||
[[ "$1" =~ ^(CHURCH|PRODUCTS|ADDRESS)$ ]] || [[ "$1" =~ ^(ACCOUNTS|EVENTS|WEBSITE|APP)_[A-Z0-9_]+$ ]]
|
||||
}
|
||||
|
||||
# church_env_read <file>: fills CENV. Values may be bare or in double or single quotes; a
|
||||
# "# comment" after the value is ignored. Unknown keys and other lines are skipped.
|
||||
church_env_read() {
|
||||
local file="$1" line key value
|
||||
CENV=()
|
||||
[ -f "$file" ] || return 1
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
line="${line%$'\r'}"
|
||||
[[ "$line" =~ ^[[:space:]]*([A-Z][A-Z0-9_]*)=(.*)$ ]] || continue
|
||||
key="${BASH_REMATCH[1]}"
|
||||
value="${BASH_REMATCH[2]}"
|
||||
church_env_key_ok "$key" || continue
|
||||
if [[ "$value" =~ ^\"([^\"]*)\" ]] || [[ "$value" =~ ^\'([^\']*)\' ]]; then
|
||||
value="${BASH_REMATCH[1]}"
|
||||
else
|
||||
value="${value%%#*}"
|
||||
value="${value%"${value##*[![:space:]]}"}"
|
||||
fi
|
||||
CENV[$key]="$value"
|
||||
done < "$file"
|
||||
}
|
||||
|
||||
# cenv <KEY> [default]: a value from CENV.
|
||||
cenv() { printf '%s' "${CENV[$1]:-${2:-}}"; }
|
||||
# pvar <product> <NAME> [default]: a product's value, e.g. pvar events DIR → CENV[EVENTS_DIR].
|
||||
pvar() { cenv "$(upper "$1")_$2" "${3:-}"; }
|
||||
|
||||
church_env_set() {
|
||||
church_env_key_ok "$1" || die "church.env: unknown key $1"
|
||||
[[ "$2" != *[\"\'\$\`\\]* && "$2" != *$'\n'* ]] || die "church.env: $1 can't contain quotes, \$, \` , \\ or newlines"
|
||||
CENV[$1]="$2"
|
||||
}
|
||||
|
||||
church_env_unset() { unset 'CENV[$1]'; }
|
||||
|
||||
# church_env_write <file>: writes CENV in a fixed order (CHURCH, PRODUCTS, ADDRESS, then each
|
||||
# product's keys in deploy order), atomically, mode 600.
|
||||
church_env_write() {
|
||||
local file="$1" tmp key p prefix
|
||||
local -a keys=()
|
||||
for key in CHURCH PRODUCTS ADDRESS; do [ -n "${CENV[$key]+x}" ] && keys+=("$key"); done
|
||||
for p in "${PRODUCT_ORDER[@]}"; do
|
||||
prefix="$(upper "$p")_"
|
||||
while IFS= read -r key; do [ -n "$key" ] && keys+=("$key"); done < <(
|
||||
for key in "${!CENV[@]}"; do [[ "$key" == "$prefix"* ]] && echo "$key"; done | LC_ALL=C sort
|
||||
)
|
||||
done
|
||||
tmp="$(mktemp "$(dirname "$file")/.church.env.XXXXXX")"
|
||||
{
|
||||
echo "# Written by crosscode. Names, folders, domains and ports only: secrets stay in each product's .env."
|
||||
for key in "${keys[@]}"; do
|
||||
if [[ "${CENV[$key]}" =~ [[:space:]#] || -z "${CENV[$key]}" ]]; then
|
||||
printf '%s="%s"\n' "$key" "${CENV[$key]}"
|
||||
else
|
||||
printf '%s=%s\n' "$key" "${CENV[$key]}"
|
||||
fi
|
||||
done
|
||||
} > "$tmp"
|
||||
chmod 600 "$tmp"
|
||||
mv -f "$tmp" "$file"
|
||||
}
|
||||
|
||||
# Church names on this server: every folder in $CROSSCODE_SITES with a church.env.
|
||||
list_churches() {
|
||||
local f
|
||||
for f in "$CROSSCODE_SITES"/*/church.env; do
|
||||
[ -f "$f" ] && basename "$(dirname "$f")"
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# Loads a church's church.env into CENV, or stops.
|
||||
load_church() {
|
||||
valid_slug "$1" || die "\"$1\" isn't a church name (a-z, 0-9 and -)."
|
||||
church_env_read "$(church_env_path "$1")" || die "No church \"$1\" on this server ($(church_env_path "$1") is missing)."
|
||||
}
|
||||
|
||||
church_has_product() {
|
||||
local p
|
||||
for p in $(cenv PRODUCTS); do [ "$p" = "$1" ] && return 0; done
|
||||
return 1
|
||||
}
|
||||
|
||||
# ── Versions and tags ────────────────────────────────────────────────────────────────────────
|
||||
# version_ge <a> <b>: a >= b, for x.y.z with an optional -prerelease (1.2.0-rc1 < 1.2.0).
|
||||
version_ge() {
|
||||
local a="$1" b="$2" an bn ap bp i x y
|
||||
an="${a%%-*}"; bn="${b%%-*}"
|
||||
ap=""; bp=""
|
||||
[[ "$a" == *-* ]] && ap="${a#*-}"
|
||||
[[ "$b" == *-* ]] && bp="${b#*-}"
|
||||
local -a A B
|
||||
IFS=. read -r -a A <<< "$an"
|
||||
IFS=. read -r -a B <<< "$bn"
|
||||
for i in 0 1 2; do
|
||||
x="${A[$i]:-0}"; y="${B[$i]:-0}"
|
||||
[[ "$x" =~ ^[0-9]+$ && "$y" =~ ^[0-9]+$ ]] || return 2
|
||||
if ((10#$x > 10#$y)); then return 0; fi
|
||||
if ((10#$x < 10#$y)); then return 1; fi
|
||||
done
|
||||
# Same x.y.z: a release beats its prereleases; prereleases compare as text.
|
||||
if [ -z "$ap" ]; then return 0; fi
|
||||
if [ -z "$bp" ]; then return 1; fi
|
||||
[[ "$ap" > "$bp" || "$ap" == "$bp" ]]
|
||||
}
|
||||
|
||||
# tag_version <product@x.y.z> → x.y.z
|
||||
tag_version() { printf '%s' "${1#*@}"; }
|
||||
|
||||
# latest_tag <product>, reading tag names on stdin: the newest released product@x.y.z
|
||||
# (prerelease and test tags such as events@2.2.0-test are never "latest").
|
||||
latest_tag_from() {
|
||||
local p="$1" t best=""
|
||||
while IFS= read -r t; do
|
||||
[[ "$t" =~ ^${p}@[0-9]+\.[0-9]+\.[0-9]+$ ]] || continue
|
||||
if [ -z "$best" ] || version_ge "$(tag_version "$t")" "$(tag_version "$best")"; then best="$t"; fi
|
||||
done
|
||||
printf '%s' "$best"
|
||||
}
|
||||
|
||||
# git_in <checkout> <args…>: git for reading a checkout owned by the app user (as root, git would
|
||||
# otherwise refuse it as "dubious ownership"). Anything that writes runs as the app user instead.
|
||||
git_in() {
|
||||
local dir="$1"
|
||||
shift
|
||||
git -c safe.directory="$dir" -C "$dir" "$@"
|
||||
}
|
||||
|
||||
# latest_tag <checkout> <product>: from the checkout's tags (fetch first).
|
||||
latest_tag() { git_in "$1" tag -l "$2@*" | latest_tag_from "$2"; }
|
||||
|
||||
# checkout_ref <checkout> <product>: the product tag the checkout is on, or the short commit.
|
||||
checkout_ref() {
|
||||
git_in "$1" describe --tags --exact-match --match "$2@*" 2>/dev/null || git_in "$1" rev-parse --short HEAD
|
||||
}
|
||||
|
||||
# whatsnew_requires <version>, reading a WHATS-NEW.md on stdin: the requirements in that
|
||||
# version's heading, one "product x.y.z" per line. Same grammar as the Hub's release sync
|
||||
# (events-hub releaseSync.js): "## 3.0.0 — requires accounts 1.2.0, website 1.1.0 — urgent".
|
||||
# HTML comments are skipped (the file's own instructions contain example headings).
|
||||
whatsnew_requires() {
|
||||
local version="$1"
|
||||
awk -v want="$version" '
|
||||
BEGIN { products = "accounts|events|website|app" }
|
||||
{
|
||||
line = $0
|
||||
sub(/\r$/, "", line)
|
||||
# Drop <!-- … --> comments, which can span lines.
|
||||
out = ""
|
||||
while (line != "") {
|
||||
if (incomment) {
|
||||
e = index(line, "-->")
|
||||
if (e == 0) { line = ""; break }
|
||||
line = substr(line, e + 3); incomment = 0
|
||||
} else {
|
||||
s = index(line, "<!--")
|
||||
if (s == 0) { out = out line; line = ""; break }
|
||||
out = out substr(line, 1, s - 1); line = substr(line, s + 4); incomment = 1
|
||||
}
|
||||
}
|
||||
if (out !~ /^##[ \t]+/) next
|
||||
h = out; sub(/^##[ \t]+/, "", h)
|
||||
if (!match(h, /v?[0-9]+\.[0-9]+\.[0-9]+/)) next
|
||||
v = substr(h, RSTART, RLENGTH); sub(/^v/, "", v)
|
||||
if (v != want) next
|
||||
rest = tolower(substr(h, RSTART + RLENGTH))
|
||||
if (!match(rest, /(^|[^a-z])requires?([^a-z]|$)/)) exit
|
||||
rest = substr(rest, RSTART)
|
||||
while (match(rest, "(" products ")[ \t]+v?[0-9]+\\.[0-9]+\\.[0-9]+")) {
|
||||
m = substr(rest, RSTART, RLENGTH)
|
||||
before = RSTART > 1 ? substr(rest, RSTART - 1, 1) : " "
|
||||
rest = substr(rest, RSTART + RLENGTH)
|
||||
if (before ~ /[a-z0-9]/) continue
|
||||
split(m, parts, /[ \t]+/)
|
||||
p = parts[1]; ver = parts[2]; sub(/^v/, "", ver)
|
||||
if (!(p in seen)) { seen[p] = 1; print p " " ver }
|
||||
}
|
||||
exit
|
||||
}
|
||||
'
|
||||
}
|
||||
|
||||
# ── .env files and URLs ──────────────────────────────────────────────────────────────────────
|
||||
# env_value <file> <KEY>: a value from a .env file (quotes removed), "" when absent.
|
||||
env_value() {
|
||||
local line
|
||||
line="$(grep -E "^[[:space:]]*(export[[:space:]]+)?$2=" "$1" 2>/dev/null | tail -n 1)" || true
|
||||
line="${line#*=}"
|
||||
line="${line%$'\r'}"
|
||||
if [[ "$line" =~ ^\"(.*)\"$ ]] || [[ "$line" =~ ^\'(.*)\'$ ]]; then line="${BASH_REMATCH[1]}"; fi
|
||||
printf '%s' "$line"
|
||||
}
|
||||
|
||||
# db_name_from_url <postgresql://user:pass@host:5432/name?x=y> → name
|
||||
db_name_from_url() {
|
||||
local u="${1%%\?*}"
|
||||
printf '%s' "${u##*/}"
|
||||
}
|
||||
|
||||
# host_from_url <https://events.church.org/x> → events.church.org (the first, if a list)
|
||||
host_from_url() {
|
||||
local u="${1%%,*}"
|
||||
u="${u#*://}"
|
||||
u="${u%%/*}"
|
||||
printf '%s' "${u%%:*}"
|
||||
}
|
||||
|
||||
# ── Health ───────────────────────────────────────────────────────────────────────────────────
|
||||
# json_get <path>, reading JSON on stdin: a value ("a.b"), objects as compact JSON, "" if absent.
|
||||
json_get() {
|
||||
node -e '
|
||||
let s = "";
|
||||
process.stdin.on("data", d => (s += d)).on("end", () => {
|
||||
try {
|
||||
const v = process.argv[1].split(".").reduce((o, k) => (o == null ? o : o[k]), JSON.parse(s));
|
||||
process.stdout.write(v == null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v));
|
||||
} catch { process.exit(1); }
|
||||
});' "$1"
|
||||
}
|
||||
|
||||
health_json() { curl -fsS --max-time 5 "$1" 2>/dev/null; }
|
||||
|
||||
# wait_for_version <health url> <version> [seconds]: until /health answers with that version.
|
||||
wait_for_version() {
|
||||
local url="$1" want="$2" limit="${3:-60}" waited=0 got=""
|
||||
while [ "$waited" -lt "$limit" ]; do
|
||||
got="$(health_json "$url" | json_get version 2>/dev/null || true)"
|
||||
[ "$got" = "$want" ] && return 0
|
||||
sleep 2
|
||||
waited=$((waited + 2))
|
||||
done
|
||||
warn "/health ($url) didn't report $want within ${limit}s (last answer: ${got:-none})."
|
||||
return 1
|
||||
}
|
||||
|
||||
node_major() { node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0; }
|
||||
|
||||
# Files changed or added by hand in a checkout (ignored files such as .env, uploads, backups and
|
||||
# the install's ecosystem.config.js never count).
|
||||
local_changes() { git_in "$1" status --porcelain --untracked-files=all; }
|
||||
@@ -0,0 +1,293 @@
|
||||
# shellcheck shell=bash
|
||||
# crosscode deploy: checks first for every product named, then each product in a fixed order
|
||||
# (Accounts, Events, Website, App), each rolled back on its own if it fails (ROADMAP §8).
|
||||
|
||||
deploy_usage() {
|
||||
cat <<'EOF'
|
||||
crosscode deploy <church> [events] [website] [app] [options]
|
||||
crosscode deploy --every-church [events] [website] [app] [options]
|
||||
|
||||
Updates Accounts (always, once the church has it) and the products named, to their latest
|
||||
released tags. Products not named aren't touched.
|
||||
|
||||
--version <product>@<x.y.z> that release instead of the latest (repeatable, one per product)
|
||||
--main the latest main instead of a tag (staging churches only)
|
||||
--check only the checks; changes nothing
|
||||
--allow-local-changes deploy even if files in a checkout were changed by hand
|
||||
EOF
|
||||
}
|
||||
|
||||
# Set by cmd_deploy, read by deploy_church.
|
||||
declare -gA DEPLOY_VERSION=()
|
||||
DEPLOY_MAIN=0
|
||||
DEPLOY_CHECK=0
|
||||
DEPLOY_EVERY=0
|
||||
|
||||
cmd_deploy() {
|
||||
local church="" arg p
|
||||
local -a named=()
|
||||
while [ $# -gt 0 ]; do
|
||||
arg="$1"
|
||||
case "$arg" in
|
||||
--version)
|
||||
[ $# -ge 2 ] || die "--version needs <product>@<x.y.z>."
|
||||
[[ "$2" =~ ^([a-z]+)@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version $2: expected <product>@<x.y.z>, e.g. events@2.2.0."
|
||||
p="${BASH_REMATCH[1]}"
|
||||
is_known_product "$p" || die "--version $2: unknown product \"$p\"."
|
||||
DEPLOY_VERSION[$p]="$2"
|
||||
shift 2 ;;
|
||||
--main) DEPLOY_MAIN=1; shift ;;
|
||||
--check) DEPLOY_CHECK=1; shift ;;
|
||||
--allow-local-changes) ALLOW_LOCAL_CHANGES=1; shift ;;
|
||||
--every-church) DEPLOY_EVERY=1; shift ;;
|
||||
-h|--help) deploy_usage; return 0 ;;
|
||||
-*) die "Unknown option $arg (crosscode deploy --help)." ;;
|
||||
*)
|
||||
if [ "$DEPLOY_EVERY" = 0 ] && [ -z "$church" ]; then
|
||||
church="$arg"
|
||||
else
|
||||
is_known_product "$arg" || die "Unknown product \"$arg\" (accounts, events, website, app)."
|
||||
named+=("$arg")
|
||||
fi
|
||||
shift ;;
|
||||
esac
|
||||
done
|
||||
[ "$DEPLOY_MAIN" = 0 ] || [ "${#DEPLOY_VERSION[@]}" = 0 ] || die "Use --main or --version, not both."
|
||||
# The church name was taken as the first word; with --every-church after it, it's a product.
|
||||
if [ "$DEPLOY_EVERY" = 1 ] && [ -n "$church" ]; then
|
||||
is_known_product "$church" || die "--every-church doesn't take a church name."
|
||||
named=("$church" "${named[@]}")
|
||||
church=""
|
||||
fi
|
||||
for p in "${!DEPLOY_VERSION[@]}"; do
|
||||
[ "$p" = accounts ] || printf '%s\n' "${named[@]}" | grep -qx "$p" ||
|
||||
die "--version ${DEPLOY_VERSION[$p]}: name $p as well (crosscode deploy <church> $p --version …)."
|
||||
done
|
||||
require_root
|
||||
|
||||
if [ "$DEPLOY_EVERY" = 1 ]; then
|
||||
local -a churches
|
||||
mapfile -t churches < <(list_churches)
|
||||
[ "${#churches[@]}" -gt 0 ] || die "No churches on this server ($CROSSCODE_SITES/*/church.env)."
|
||||
local i rc
|
||||
for i in "${!churches[@]}"; do
|
||||
echo
|
||||
step "Church ${churches[$i]} ($((i + 1)) of ${#churches[@]})"
|
||||
set +e
|
||||
(deploy_church "${churches[$i]}" "${named[@]}")
|
||||
rc=$?
|
||||
set -e
|
||||
if [ "$rc" != 0 ]; then
|
||||
warn "Stopped at ${churches[$i]}. Not reached: ${churches[*]:$((i + 1))}"
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
fi
|
||||
|
||||
[ -n "$church" ] || { deploy_usage; die "Name a church, or use --every-church."; }
|
||||
deploy_church "$church" "${named[@]}"
|
||||
}
|
||||
|
||||
# deploy_church <church> [products…]: the checks, then the deploy. Must be called as a plain
|
||||
# command (not in `if` or after `||`), so `set -e` keeps working inside it.
|
||||
deploy_church() {
|
||||
local church="$1"
|
||||
shift
|
||||
load_church "$church"
|
||||
local p rp rv
|
||||
local -a wanted=() products=()
|
||||
church_has_product accounts && wanted+=(accounts)
|
||||
for p in "$@"; do
|
||||
if church_has_product "$p"; then
|
||||
wanted+=("$p")
|
||||
elif [ "$DEPLOY_EVERY" = 1 ]; then
|
||||
info "$church has no $p: skipped."
|
||||
else
|
||||
die "$church has no $p (its products: $(cenv PRODUCTS))."
|
||||
fi
|
||||
done
|
||||
mapfile -t products < <(in_product_order "${wanted[@]}")
|
||||
if [ "${#products[@]}" = 0 ]; then
|
||||
info "Nothing to deploy for $church. Name the products to update (its products: $(cenv PRODUCTS))."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# ── 1. Checks, for every product, before anything is touched ──────────────────────────────
|
||||
step "Checks for $church: ${products[*]}"
|
||||
local -A DIR=() USR=() PREV=() TARGET=() TVER=()
|
||||
local failed=0 dir user changes major t v
|
||||
major="$(node_major)"
|
||||
if [ "$major" -lt "$CROSSCODE_NODE_MIN" ]; then
|
||||
warn "This server runs Node $(node -v 2>/dev/null || echo '(none)'). Releases need Node $CROSSCODE_NODE_MIN or later (24 LTS recommended)."
|
||||
failed=1
|
||||
elif [ "$major" -lt "$CROSSCODE_NODE_WARN" ]; then
|
||||
warn "This server runs Node $(node -v), which no longer gets security fixes. Move to Node 24 LTS."
|
||||
fi
|
||||
for p in "${products[@]}"; do
|
||||
is_supported_product "$p" || die "This version of crosscode can't deploy $p yet."
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/$p.sh"
|
||||
dir="$(pvar "$p" DIR)"
|
||||
user="$(pvar "$p" USER)"
|
||||
if [ -z "$dir" ] || [ ! -d "$dir/.git" ]; then warn "$p: $dir isn't a checkout (church.env $(upper "$p")_DIR)."; failed=1; continue; fi
|
||||
if [ -z "$user" ] || ! id "$user" >/dev/null 2>&1; then warn "$p: no app user \"$user\" (church.env $(upper "$p")_USER)."; failed=1; continue; fi
|
||||
DIR[$p]="$dir"; USR[$p]="$user"
|
||||
if ! run_as "$user" "$dir" git fetch --tags --quiet origin; then
|
||||
warn "$p: couldn't fetch from origin."; failed=1; continue
|
||||
fi
|
||||
PREV[$p]="$(checkout_ref "$dir" "$p")"
|
||||
if [ -n "${DEPLOY_VERSION[$p]:-}" ]; then
|
||||
t="${DEPLOY_VERSION[$p]}"
|
||||
git_in "$dir" rev-parse -q --verify "refs/tags/$t" >/dev/null || { warn "$p: there's no tag $t."; failed=1; continue; }
|
||||
elif [ "$DEPLOY_MAIN" = 1 ]; then
|
||||
t="origin/main"
|
||||
else
|
||||
t="$(latest_tag "$dir" "$p")"
|
||||
[ -n "$t" ] || { warn "$p: no $p@x.y.z release tags found."; failed=1; continue; }
|
||||
fi
|
||||
TARGET[$p]="$t"
|
||||
if [ "$t" = origin/main ]; then TVER[$p]=""; else TVER[$p]="$(tag_version "$t")"; fi
|
||||
|
||||
changes="$(local_changes "$dir")"
|
||||
if [ -n "$changes" ]; then
|
||||
warn "$p: files in $dir were changed or added by hand:"
|
||||
printf '%s\n' "$changes" | sed 's/^/ /' >&2
|
||||
info "A release would build them in (or refuse to replace them). Move added files (??) out of"
|
||||
info "the folder and put changed ones ( M) back with \"git checkout -- <file>\", after checking"
|
||||
info "nothing in them is needed."
|
||||
if [ "${ALLOW_LOCAL_CHANGES:-}" = 1 ] && [ "$DEPLOY_CHECK" = 0 ]; then
|
||||
info "--allow-local-changes: deploying anyway."
|
||||
else
|
||||
failed=1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
[ "$failed" = 0 ] || die "Checks failed for $church. Nothing was changed."
|
||||
|
||||
# Requirements between products (decision 24): from the target release's WHATS-NEW.md heading.
|
||||
local req_ok
|
||||
for p in "${products[@]}"; do
|
||||
[ -n "${TVER[$p]}" ] || { info "$p: deploying main, so no release requirements to check."; continue; }
|
||||
while read -r rp rv; do
|
||||
[ -n "$rp" ] && [ "$rp" != "$p" ] || continue
|
||||
req_ok=0
|
||||
if [ -n "${TARGET[$rp]:-}" ] && [ "$(product_index "$rp")" -lt "$(product_index "$p")" ]; then
|
||||
# Updated earlier in this same run.
|
||||
if [ -z "${TVER[$rp]}" ] || version_ge "${TVER[$rp]}" "$rv"; then req_ok=1; fi
|
||||
v="${TVER[$rp]:-main}"
|
||||
elif church_has_product "$rp"; then
|
||||
v="$(checkout_ref "$(pvar "$rp" DIR)" "$rp" 2>/dev/null || true)"
|
||||
v="$(tag_version "$v")"
|
||||
version_ge "$v" "$rv" 2>/dev/null && req_ok=1
|
||||
else
|
||||
v="not installed"
|
||||
fi
|
||||
if [ "$req_ok" = 1 ]; then
|
||||
info "$p ${TVER[$p]} requires $rp $rv: met ($rp ${v})."
|
||||
else
|
||||
warn "$p ${TVER[$p]} requires $rp $rv, and $church has $rp ${v:-unknown}. Update $rp first (or in the same run)."
|
||||
failed=1
|
||||
fi
|
||||
done < <(git_in "${DIR[$p]}" show "${TARGET[$p]}:apps/$p/WHATS-NEW.md" 2>/dev/null | whatsnew_requires "${TVER[$p]}")
|
||||
done
|
||||
[ "$failed" = 0 ] || die "Requirements not met for $church. Nothing was changed."
|
||||
|
||||
for p in "${products[@]}"; do
|
||||
if [ "${PREV[$p]}" = "${TARGET[$p]}" ]; then
|
||||
info "$p: already on ${PREV[$p]}."
|
||||
else
|
||||
info "$p: ${PREV[$p]} → ${TARGET[$p]}"
|
||||
fi
|
||||
done
|
||||
if [ "$DEPLOY_CHECK" = 1 ]; then
|
||||
step "Checks passed for $church: ready to deploy."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# ── 2. Each product in order; a failure rolls that product back and stops the run ─────────
|
||||
local -A RESULT=()
|
||||
local stopped=0
|
||||
for p in "${products[@]}"; do
|
||||
if [ "$stopped" = 1 ]; then RESULT[$p]="not reached"; continue; fi
|
||||
if [ "${PREV[$p]}" = "${TARGET[$p]}" ]; then RESULT[$p]="already on ${PREV[$p]}"; continue; fi
|
||||
deploy_product "$p" "${DIR[$p]}" "${USR[$p]}" "${PREV[$p]}" "${TARGET[$p]}"
|
||||
RESULT[$p]="$DEPLOY_RESULT"
|
||||
[ "$DEPLOY_OK" = 1 ] || stopped=1
|
||||
done
|
||||
|
||||
echo
|
||||
step "Summary for $church"
|
||||
for p in "${products[@]}"; do info "$(printf '%-9s %s' "$p" "${RESULT[$p]}")"; done
|
||||
[ "$stopped" = 0 ] || return 1
|
||||
}
|
||||
|
||||
# deploy_product <product> <checkout> <user> <previous ref> <target ref>: sets DEPLOY_OK and
|
||||
# DEPLOY_RESULT. Always returns 0, so `set -e` inside the steps works (see deploy_church).
|
||||
deploy_product() {
|
||||
local p="$1" dir="$2" user="$3" prev="$4" target="$5" stage_file rc stage
|
||||
stage_file="$(mktemp)"
|
||||
echo
|
||||
step "$p: $prev → $target"
|
||||
set +e
|
||||
(
|
||||
set -e
|
||||
echo backup > "$stage_file"
|
||||
step "$p: backing up the database"
|
||||
"${p}_backup" "$dir" "$user"
|
||||
echo checkout > "$stage_file"
|
||||
step "$p: checking out $target"
|
||||
run_as "$user" "$dir" git checkout -q --detach "$target"
|
||||
step "$p: installing"
|
||||
"${p}_install_deps" "$dir" "$user"
|
||||
step "$p: migrations"
|
||||
"${p}_migrate" "$dir" "$user"
|
||||
step "$p: building"
|
||||
"${p}_build" "$dir" "$user"
|
||||
expected="$("${p}_expected_version" "$dir")"
|
||||
echo reload > "$stage_file"
|
||||
step "$p: reloading PM2"
|
||||
"${p}_reload" "$dir" "$user"
|
||||
step "$p: waiting for /health to report $expected"
|
||||
wait_for_version "$("${p}_health_url")" "$expected" 60
|
||||
)
|
||||
rc=$?
|
||||
set -e
|
||||
stage="$(cat "$stage_file")"
|
||||
rm -f "$stage_file"
|
||||
if [ "$rc" = 0 ]; then
|
||||
DEPLOY_OK=1
|
||||
DEPLOY_RESULT="updated $prev → $(checkout_ref "$dir" "$p")"
|
||||
return 0
|
||||
fi
|
||||
|
||||
DEPLOY_OK=0
|
||||
if [ "$stage" = backup ]; then
|
||||
warn "$p: the backup failed, so nothing was changed."
|
||||
DEPLOY_RESULT="failed at the backup; still on $prev, nothing changed"
|
||||
return 0
|
||||
fi
|
||||
warn "$p: deploy failed. Going back to $prev (database migrations aren't undone; the backup has the database as it was)."
|
||||
set +e
|
||||
(
|
||||
set -e
|
||||
run_as "$user" "$dir" git checkout -q --detach "$prev"
|
||||
"${p}_rollback_build" "$dir" "$user"
|
||||
if [ "$stage" = reload ]; then
|
||||
"${p}_reload" "$dir" "$user"
|
||||
wait_for_version "$("${p}_health_url")" "$("${p}_expected_version" "$dir")" 60
|
||||
fi
|
||||
)
|
||||
rc=$?
|
||||
set -e
|
||||
if [ "$rc" = 0 ]; then
|
||||
if [ "$stage" = reload ]; then
|
||||
DEPLOY_RESULT="FAILED, rolled back to $prev and running again"
|
||||
else
|
||||
DEPLOY_RESULT="FAILED, rolled back to $prev (the running version was never stopped)"
|
||||
fi
|
||||
else
|
||||
DEPLOY_RESULT="FAILED, and going back to $prev failed too: check it now (crosscode status, pm2 logs)"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
# shellcheck shell=bash
|
||||
# crosscode install: a new church on this server (from hope-events' scripts/install.sh 2.1.x).
|
||||
# Events only in 2.2.0; Accounts, Website and App follow as their products/*.sh are added.
|
||||
|
||||
install_usage() {
|
||||
cat <<'EOF'
|
||||
crosscode install <church> --products events --domain <address> [options]
|
||||
|
||||
A new church: system packages (Node 24, PostgreSQL, PM2, nginx, certbot) if missing, then per
|
||||
product an app user, database, checkout, .env, PM2 processes, nginx site and certificate.
|
||||
Writes /var/www/sites/<church>/church.env. DNS must already point here (it prints the records).
|
||||
|
||||
--products events the products to install (only events in this version)
|
||||
--domain <address> the church's address: hopefamily.co.za or hopefamily.crosscode.co.za;
|
||||
Events is served on events.<address>
|
||||
--events-domain <domain> serve Events somewhere else instead
|
||||
--email <email> for Let's Encrypt notices (required unless --no-ssl)
|
||||
--version events@x.y.z that release (default: the latest)
|
||||
--main the latest main (staging churches only)
|
||||
--user <name> the Linux user the apps run as (default: cc-<church>)
|
||||
--api-port <n> Events backend port (default: the first free one from 5000)
|
||||
--web-port <n> Events frontend port (default: the first free one from 3000)
|
||||
--no-ssl no certificate (behind another proxy that does HTTPS)
|
||||
EOF
|
||||
}
|
||||
|
||||
# Ports in use: every church's *_PORTS on this server, and anything listening now.
|
||||
used_ports() {
|
||||
local f
|
||||
for f in "$CROSSCODE_SITES"/*/church.env; do
|
||||
[ -f "$f" ] && sed -nE 's/^[A-Z]+_PORTS="?([0-9 ]+)"?.*/\1/p' "$f" | tr ' ' '\n'
|
||||
done
|
||||
ss -ltnH 2>/dev/null | awk '{ n = split($4, a, ":"); print a[n] }'
|
||||
return 0
|
||||
}
|
||||
|
||||
# free_port <from> <taken…>: the first port from <from> not in the list.
|
||||
free_port() {
|
||||
local p="$1"
|
||||
shift
|
||||
while printf '%s\n' "$@" | grep -qx "$p"; do p=$((p + 1)); done
|
||||
echo "$p"
|
||||
}
|
||||
|
||||
random_secret() { openssl rand -base64 64 | tr -d '/+=\n' | head -c "${1:-48}"; }
|
||||
|
||||
cmd_install() {
|
||||
local church="" products="" address="" events_domain="" email="" version="" main=0 user="" api="" web="" ssl=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--products) products="$(printf '%s' "$2" | tr ',' ' ')"; shift 2 ;;
|
||||
--domain) address="$2"; shift 2 ;;
|
||||
--events-domain) events_domain="$2"; shift 2 ;;
|
||||
--email) email="$2"; shift 2 ;;
|
||||
--version) version="$2"; shift 2 ;;
|
||||
--main) main=1; shift ;;
|
||||
--user) user="$2"; shift 2 ;;
|
||||
--api-port) api="$2"; shift 2 ;;
|
||||
--web-port) web="$2"; shift 2 ;;
|
||||
--no-ssl) ssl=0; shift ;;
|
||||
-h|--help) install_usage; return 0 ;;
|
||||
-*) die "Unknown option $1 (crosscode install --help)." ;;
|
||||
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$church" ] || { install_usage; die "Name the church."; }
|
||||
valid_slug "$church" || die "\"$church\" isn't a church name (a-z, 0-9 and -, starting with a letter)."
|
||||
[ -n "$products" ] || die "--products is required (e.g. --products events)."
|
||||
local p
|
||||
for p in $products; do
|
||||
is_known_product "$p" || die "Unknown product \"$p\"."
|
||||
[ "$p" = events ] || die "This version of crosscode can only install events."
|
||||
done
|
||||
[[ "$address" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$ ]] || die "--domain: give the church's address, e.g. hopefamily.co.za."
|
||||
events_domain="${events_domain:-events.$address}"
|
||||
[ "$ssl" = 0 ] || [ -n "$email" ] || die "--email is required for the certificate (or use --no-ssl)."
|
||||
[ -z "$version" ] || [[ "$version" =~ ^events@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version: expected events@x.y.z."
|
||||
[ "$main" = 0 ] || [ -z "$version" ] || die "Use --main or --version, not both."
|
||||
user="${user:-cc-$church}"
|
||||
user="${user:0:32}"
|
||||
require_root
|
||||
[ ! -f "$(church_env_path "$church")" ] || die "$church is already installed here (crosscode status $church). New products for it come with \`crosscode add\` (phase 3)."
|
||||
|
||||
local taken
|
||||
mapfile -t taken < <(used_ports)
|
||||
api="${api:-$(free_port 5000 "${taken[@]}")}"
|
||||
web="${web:-$(free_port 3000 "${taken[@]}" "$api")}"
|
||||
[[ "$api" =~ ^[0-9]+$ && "$web" =~ ^[0-9]+$ && "$api" != "$web" ]] || die "Ports must be two different numbers."
|
||||
|
||||
install_system_packages "$ssl"
|
||||
step "App user ($user)"
|
||||
id "$user" >/dev/null 2>&1 || useradd --create-home --shell /bin/bash "$user"
|
||||
|
||||
CENV=()
|
||||
church_env_set CHURCH "$church"
|
||||
church_env_set PRODUCTS "events"
|
||||
church_env_set ADDRESS "$address"
|
||||
install_events "$church" "$user" "$events_domain" "$api" "$web" "$version" "$main" "$ssl" "$email"
|
||||
church_env_write "$(church_env_path "$church")"
|
||||
|
||||
step "Done"
|
||||
info "DNS (if not set yet): $events_domain → this server (A record, or a CNAME)."
|
||||
info "Open https://$events_domain/setup to create the admin account, then enter the licence key."
|
||||
info "Updates: crosscode deploy $church events"
|
||||
}
|
||||
|
||||
install_system_packages() {
|
||||
local ssl="$1"
|
||||
step "System packages"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -q
|
||||
apt-get install -y -q curl git rsync nginx postgresql postgresql-client openssl build-essential ca-certificates gnupg
|
||||
[ "$ssl" = 0 ] || apt-get install -y -q certbot python3-certbot-nginx
|
||||
# Node 24 is the LTS line supported until April 2028.
|
||||
if ! command -v node >/dev/null || [ "$(node_major)" -lt 24 ]; then
|
||||
step "Node.js 24"
|
||||
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
|
||||
apt-get install -y -q nodejs
|
||||
fi
|
||||
command -v pm2 >/dev/null || npm install -g pm2
|
||||
}
|
||||
|
||||
install_events() {
|
||||
local church="$1" user="$2" domain="$3" api="$4" web="$5" version="$6" main="$7" ssl="$8" email="$9"
|
||||
local dir app db pass url name scheme
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/events.sh"
|
||||
dir="$(church_dir "$church")/events"
|
||||
app="$dir/apps/events"
|
||||
db="$(printf '%s_events' "$church" | tr '-' '_')"
|
||||
name="$church-events"
|
||||
scheme=https
|
||||
[ "$ssl" = 1 ] || scheme=http
|
||||
url="$scheme://$domain"
|
||||
church_env_set EVENTS_DIR "$dir"
|
||||
church_env_set EVENTS_DOMAIN "$domain"
|
||||
church_env_set EVENTS_PM2 "$name-backend $name-frontend"
|
||||
church_env_set EVENTS_PORTS "$api $web"
|
||||
church_env_set EVENTS_DB "$db"
|
||||
church_env_set EVENTS_USER "$user"
|
||||
|
||||
step "Events: code ($dir)"
|
||||
mkdir -p "$(church_dir "$church")"
|
||||
chmod 755 "$CROSSCODE_SITES" "$(church_dir "$church")"
|
||||
if [ ! -d "$dir/.git" ]; then
|
||||
mkdir -p "$dir"
|
||||
chown "$user:$user" "$dir"
|
||||
run_as "$user" "$dir" git clone --quiet "$CROSSCODE_REPO" .
|
||||
fi
|
||||
run_as "$user" "$dir" git fetch --tags --quiet origin
|
||||
if [ "$main" = 1 ]; then
|
||||
version=origin/main
|
||||
elif [ -z "$version" ]; then
|
||||
version="$(latest_tag "$dir" events)"
|
||||
[ -n "$version" ] || die "No events@x.y.z release tags yet (use --version or --main)."
|
||||
fi
|
||||
run_as "$user" "$dir" git checkout -q --detach "$version"
|
||||
info "At $(checkout_ref "$dir" events)"
|
||||
|
||||
step "Events: database ($db)"
|
||||
# Re-running keeps the password already in backend/.env; otherwise a new one.
|
||||
pass=""
|
||||
if [ -f "$app/backend/.env" ]; then
|
||||
pass="$(env_value "$app/backend/.env" DATABASE_URL | sed -nE 's#^postgresql://[^:]+:([^@]+)@.*#\1#p')"
|
||||
fi
|
||||
pass="${pass:-$(random_secret 32)}"
|
||||
sudo -u postgres psql -v ON_ERROR_STOP=1 -q <<SQL
|
||||
DO \$\$ BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '$db') THEN
|
||||
CREATE ROLE "$db" LOGIN PASSWORD '$pass';
|
||||
ELSE
|
||||
ALTER ROLE "$db" WITH LOGIN PASSWORD '$pass';
|
||||
END IF;
|
||||
END \$\$;
|
||||
SQL
|
||||
sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname = '$db'" | grep -q 1 ||
|
||||
sudo -u postgres createdb -O "$db" "$db"
|
||||
|
||||
step "Events: configuration"
|
||||
if [ ! -f "$app/backend/.env" ]; then
|
||||
cat > "$app/backend/.env" <<ENV
|
||||
NODE_ENV=production
|
||||
PORT=$api
|
||||
DATABASE_URL=postgresql://$db:$pass@localhost:5432/$db
|
||||
JWT_SECRET=$(random_secret 64)
|
||||
FRONTEND_URL=$url
|
||||
APP_BASE_URL=$url
|
||||
BACKEND_URL=$url
|
||||
TRUST_PROXY=1
|
||||
APP_TIMEZONE=Africa/Johannesburg
|
||||
ENV
|
||||
info "Wrote backend/.env (keep JWT_SECRET: it also encrypts stored secrets)."
|
||||
else
|
||||
info "backend/.env exists: kept."
|
||||
fi
|
||||
[ -f "$app/frontend/.env.production" ] || echo "NEXT_PUBLIC_API_URL=$url" > "$app/frontend/.env.production"
|
||||
chown "$user:$user" "$app/backend/.env" "$app/frontend/.env.production"
|
||||
chmod 600 "$app/backend/.env"
|
||||
events_ensure_pm2_config "$dir" "$user"
|
||||
|
||||
step "Events: install, migrate, build"
|
||||
events_install_deps "$dir" "$user"
|
||||
events_migrate "$dir" "$user"
|
||||
events_build "$dir" "$user"
|
||||
|
||||
step "Events: PM2"
|
||||
run_as "$user" "$app" pm2 startOrReload ecosystem.config.js
|
||||
run_as "$user" "$app" pm2 save
|
||||
env PATH="$PATH:/usr/bin" pm2 startup systemd -u "$user" --hp "$(getent passwd "$user" | cut -d: -f6)" >/dev/null
|
||||
|
||||
step "Events: nginx ($domain)"
|
||||
install_events_nginx "$name" "$domain" "$api" "$web"
|
||||
if [ "$ssl" = 1 ]; then
|
||||
step "Events: certificate"
|
||||
certbot --nginx -d "$domain" --non-interactive --agree-tos -m "$email" --redirect
|
||||
fi
|
||||
|
||||
step "Events: checking"
|
||||
wait_for_version "$(events_health_url)" "$(events_expected_version "$dir")" 60 ||
|
||||
warn "The backend isn't answering yet: sudo -u $user pm2 logs"
|
||||
}
|
||||
|
||||
install_events_nginx() {
|
||||
local name="$1" domain="$2" api="$3" web="$4"
|
||||
# Only this domain is served by this site (no catch-all), as ROADMAP §8 asks.
|
||||
cat > "/etc/nginx/sites-available/$name" <<NGINX
|
||||
server {
|
||||
listen 80;
|
||||
server_name $domain;
|
||||
client_max_body_size 25m;
|
||||
|
||||
# The API, uploaded files, health and API docs go to the backend; everything else to the site.
|
||||
location ~ ^/(api|uploads|health|docs)(/|\$) {
|
||||
proxy_pass http://127.0.0.1:$api;
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
}
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:$web;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
}
|
||||
}
|
||||
NGINX
|
||||
ln -sf "/etc/nginx/sites-available/$name" "/etc/nginx/sites-enabled/$name"
|
||||
nginx -t
|
||||
systemctl reload nginx
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
# shellcheck shell=bash
|
||||
# crosscode status [<church>]: each product's version, latest release, health and last backup.
|
||||
|
||||
status_usage() {
|
||||
cat <<'EOF'
|
||||
crosscode status [<church>] [--no-fetch]
|
||||
|
||||
Each product's checked-out release, the latest release, and what /health reports (version,
|
||||
database, jobs, last backup), for one church or every church on this server.
|
||||
|
||||
--no-fetch don't fetch tags first (faster; "latest" may be out of date)
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
local church="" fetch=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--no-fetch) fetch=0; shift ;;
|
||||
-h|--help) status_usage; return 0 ;;
|
||||
-*) die "Unknown option $1 (crosscode status --help)." ;;
|
||||
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
require_root
|
||||
local -a churches
|
||||
if [ -n "$church" ]; then
|
||||
churches=("$church")
|
||||
else
|
||||
mapfile -t churches < <(list_churches)
|
||||
[ "${#churches[@]}" -gt 0 ] || { info "No churches on this server ($CROSSCODE_SITES/*/church.env)."; return 0; }
|
||||
fi
|
||||
local c
|
||||
for c in "${churches[@]}"; do status_church "$c" "$fetch"; done
|
||||
}
|
||||
|
||||
status_church() {
|
||||
local church="$1" fetch="$2" p dir user ref latest url json version db jobs backup line
|
||||
load_church "$church"
|
||||
echo
|
||||
step "$church ($(cenv ADDRESS '(no address)'))"
|
||||
# shellcheck disable=SC2046 # PRODUCTS is a space-separated list of names
|
||||
for p in $(in_product_order $(cenv PRODUCTS)); do
|
||||
dir="$(pvar "$p" DIR)"
|
||||
user="$(pvar "$p" USER)"
|
||||
if [ ! -d "$dir/.git" ]; then
|
||||
info "$(printf '%-9s %s' "$p" "missing checkout: $dir")"
|
||||
continue
|
||||
fi
|
||||
if [ "$fetch" = 1 ]; then
|
||||
run_as "$user" "$dir" timeout 20 git fetch --tags --quiet origin 2>/dev/null || true
|
||||
fi
|
||||
ref="$(checkout_ref "$dir" "$p")"
|
||||
latest="$(latest_tag "$dir" "$p")"
|
||||
line="$(printf '%-9s %-16s latest %-16s' "$p" "$ref" "${latest:-none}")"
|
||||
[ -n "$latest" ] && [ "$ref" != "$latest" ] && line="$line (update available)"
|
||||
info "$line"
|
||||
|
||||
if is_supported_product "$p"; then
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/$p.sh"
|
||||
url="$("${p}_health_url")"
|
||||
if json="$(health_json "$url")"; then
|
||||
version="$(printf '%s' "$json" | json_get version)"
|
||||
db="$(printf '%s' "$json" | json_get db)"
|
||||
jobs="$(printf '%s' "$json" | json_get jobs)"
|
||||
backup="$(printf '%s' "$json" | json_get lastBackupAt)"
|
||||
info " health: version ${version:-?}, database ${db:-?}, jobs ${jobs:-?}, last backup ${backup:-never}"
|
||||
else
|
||||
warn " $p isn't answering on $url (pm2 status; pm2 logs)."
|
||||
fi
|
||||
fi
|
||||
status_old_folder "$p"
|
||||
done
|
||||
}
|
||||
|
||||
# After `adopt`, the old folder is kept for 14 days so `adopt --undo` can go back to it.
|
||||
status_old_folder() {
|
||||
local p="$1" old at age
|
||||
old="$(pvar "$p" OLD_DIR)"
|
||||
at="$(pvar "$p" ADOPTED_AT)"
|
||||
[ -n "$old" ] && [ -d "$old" ] || return 0
|
||||
age=$(( ($(date +%s) - $(date -d "$at" +%s 2>/dev/null || date +%s)) / 86400 ))
|
||||
if [ "$age" -ge 14 ]; then
|
||||
warn " The old folder $old is $age days old, past the 14 days kept for \`adopt --undo\`: remove it (rm -rf $old)."
|
||||
else
|
||||
info " Old folder kept for \`adopt --undo\`: $old (adopted $at, $((14 - age)) days left)."
|
||||
fi
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
# shellcheck shell=bash
|
||||
# Cross Events' hooks for the crosscode script (from hope-events' scripts/deploy.sh 2.1.x).
|
||||
# Every hook takes the product's checkout (EVENTS_DIR, a checkout of crosscode-platform) and the
|
||||
# app user, and runs the app's commands as that user. Values come from church.env (CENV).
|
||||
#
|
||||
# Adding a product means adding a file like this one with the same hooks, and its name in
|
||||
# SUPPORTED_PRODUCTS (lib/common.sh).
|
||||
|
||||
events_app() { printf '%s/apps/events' "$1"; }
|
||||
|
||||
events_pm2_names() { pvar events PM2; }
|
||||
events_pm2_config() { printf '%s/ecosystem.config.js' "$(events_app "$1")"; }
|
||||
|
||||
# EVENTS_PORTS="<api> <web>"
|
||||
events_api_port() { local p; read -r p _ <<< "$(pvar events PORTS)"; printf '%s' "${p:-5000}"; }
|
||||
events_web_port() { local p; read -r _ p <<< "$(pvar events PORTS)"; printf '%s' "${p:-3000}"; }
|
||||
events_health_url() { printf 'http://127.0.0.1:%s/health' "$(events_api_port)"; }
|
||||
|
||||
# The version /health reports once this checkout runs (the backend's package.json).
|
||||
events_expected_version() {
|
||||
node -p 'require(process.argv[1]).version' "$(events_app "$1")/backend/package.json"
|
||||
}
|
||||
|
||||
events_backup() {
|
||||
local dir="$1" user="$2"
|
||||
# shellcheck disable=SC2016
|
||||
run_as "$user" "$(events_app "$dir")/backend" node -e '
|
||||
require("dotenv").config();
|
||||
require("./src/utils/backupUtils").runBackup()
|
||||
.then(r => console.log(" " + r.filename))
|
||||
.catch(e => { console.error(" Backup failed: " + e.message); process.exit(1); });'
|
||||
}
|
||||
|
||||
# Only this app's workspaces, never the other products'. --include=dev: the TypeScript and Next
|
||||
# builds need type and build packages even where NODE_ENV=production.
|
||||
events_install_deps() {
|
||||
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend
|
||||
}
|
||||
|
||||
events_migrate() {
|
||||
run_as "$2" "$(events_app "$1")/backend" npm run prisma:deploy
|
||||
}
|
||||
|
||||
events_pending_migrations() {
|
||||
# prisma migrate status exits non-zero when migrations are pending (or the DB can't be read).
|
||||
! run_as "$2" "$(events_app "$1")/backend" npx prisma migrate status >/dev/null 2>&1
|
||||
}
|
||||
|
||||
events_build() {
|
||||
run_as "$2" "$(events_app "$1")/backend" npm run build &&
|
||||
run_as "$2" "$(events_app "$1")/frontend" npm run build
|
||||
}
|
||||
|
||||
# After going back to the previous tag: install and build it again. Migrations aren't undone
|
||||
# (the backup taken first has the database as it was).
|
||||
events_rollback_build() {
|
||||
events_install_deps "$1" "$2" && events_build "$1" "$2"
|
||||
}
|
||||
|
||||
# The install's own PM2 config (not in git). Created from the example the first time, with this
|
||||
# church's PM2 names and web port.
|
||||
events_ensure_pm2_config() {
|
||||
local dir="$1" user="$2" app conf backend frontend
|
||||
app="$(events_app "$dir")"
|
||||
conf="$app/ecosystem.config.js"
|
||||
[ -f "$conf" ] && return 0
|
||||
read -r backend frontend <<< "$(events_pm2_names)"
|
||||
sed -e "s/'hope-events-backend'/'${backend}'/" \
|
||||
-e "s/'hope-events-frontend'/'${frontend}'/" \
|
||||
-e "s/-p 3000/-p $(events_web_port)/" \
|
||||
"$app/ecosystem.config.example.js" > "$conf"
|
||||
chown "$user:$user" "$conf" 2>/dev/null || true
|
||||
info "Created $conf from the example."
|
||||
}
|
||||
|
||||
events_reload() {
|
||||
events_ensure_pm2_config "$1" "$2"
|
||||
run_as "$2" "$(events_app "$1")" pm2 reload ecosystem.config.js --update-env
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bats
|
||||
# adopt's helpers that don't need a server: rewriting the PM2 config, and finding the install's
|
||||
# own data files. Run with `npm run test:scripts`.
|
||||
|
||||
setup() {
|
||||
# shellcheck source=../lib/common.sh
|
||||
source "$BATS_TEST_DIRNAME/../lib/common.sh"
|
||||
# shellcheck source=../lib/adopt.sh
|
||||
source "$BATS_TEST_DIRNAME/../lib/adopt.sh"
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
}
|
||||
|
||||
@test "rewrite_ecosystem points absolute paths at the new app folder" {
|
||||
run rewrite_ecosystem /var/www/hope-events /var/www/sites/hope/events/apps/events <<'EOF'
|
||||
module.exports = { apps: [
|
||||
{ name: 'hope-events-backend', cwd: '/var/www/hope-events/backend', script: 'src/index.js' },
|
||||
{ name: 'hope-events-frontend', cwd: "/var/www/hope-events/frontend", script: 'npm', args: 'start -- -p 3000' },
|
||||
{ name: 'x', cwd: `/var/www/hope-events`, out_file: '/var/www/hope-events2/log' },
|
||||
] };
|
||||
EOF
|
||||
[[ "$output" == *"cwd: '/var/www/sites/hope/events/apps/events/backend'"* ]]
|
||||
[[ "$output" == *'cwd: "/var/www/sites/hope/events/apps/events/frontend"'* ]]
|
||||
[[ "$output" == *'cwd: `/var/www/sites/hope/events/apps/events`'* ]]
|
||||
# A different folder that only starts the same isn't touched.
|
||||
[[ "$output" == *"'/var/www/hope-events2/log'"* ]]
|
||||
[[ "$output" == *"name: 'hope-events-backend'"* ]]
|
||||
}
|
||||
|
||||
@test "rewrite_ecosystem leaves __dirname configs alone" {
|
||||
input="$(cat "$BATS_TEST_DIRNAME/../../apps/events/ecosystem.config.example.js")"
|
||||
run rewrite_ecosystem /var/www/hope-events /var/www/sites/hope/events/apps/events <<< "$input"
|
||||
[ "$output" = "$input" ]
|
||||
}
|
||||
|
||||
@test "rewrite_ecosystem copes with dots and other characters in paths" {
|
||||
run rewrite_ecosystem /opt/hope.events /srv/a\&b <<'EOF'
|
||||
cwd: '/opt/hope.events/backend', other: '/opt/hopexevents/backend'
|
||||
EOF
|
||||
[ "$output" = "cwd: '/srv/a&b/backend', other: '/opt/hopexevents/backend'" ]
|
||||
}
|
||||
|
||||
@test "ignored_files_in lists the install's own data files, not tracked ones" {
|
||||
git init -q "$TMP/old"
|
||||
cd "$TMP/old"
|
||||
mkdir -p backend/data
|
||||
printf 'backend/data/banner.json\n' > .gitignore
|
||||
echo '{}' > backend/data/defaults.json
|
||||
git add . && git -c user.name=t -c user.email=t@t commit -q -m one
|
||||
echo '{}' > backend/data/banner.json
|
||||
run ignored_files_in "$TMP/old" backend/data
|
||||
[ "$output" = "backend/data/banner.json" ]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bats
|
||||
# The crosscode entry script: help, and the argument checks that run before anything needs root.
|
||||
|
||||
setup() {
|
||||
export CROSSCODE_NO_UPDATE=1
|
||||
CC="$BATS_TEST_DIRNAME/../crosscode"
|
||||
}
|
||||
|
||||
@test "help lists the commands" {
|
||||
run bash "$CC" help
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"crosscode deploy <church>"* ]]
|
||||
[[ "$output" == *"crosscode adopt <church> --undo"* ]]
|
||||
}
|
||||
|
||||
@test "help <command> shows that command's options" {
|
||||
run bash "$CC" help deploy
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"--every-church"* ]]
|
||||
run bash "$CC" adopt --help
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"--events-dir"* ]]
|
||||
}
|
||||
|
||||
@test "an unknown command fails" {
|
||||
run bash "$CC" frobnicate
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *'Unknown command "frobnicate"'* ]]
|
||||
}
|
||||
|
||||
@test "the copy it runs from is removed afterwards" {
|
||||
before="$(find /tmp -maxdepth 1 -name 'crosscode.*' 2>/dev/null | wc -l)"
|
||||
run bash "$CC" help
|
||||
after="$(find /tmp -maxdepth 1 -name 'crosscode.*' 2>/dev/null | wc -l)"
|
||||
[ "$before" -eq "$after" ]
|
||||
}
|
||||
|
||||
@test "deploy refuses bad arguments before touching anything" {
|
||||
run bash "$CC" deploy hopefamily events --version events@2.2
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"expected <product>@<x.y.z>"* ]]
|
||||
|
||||
run bash "$CC" deploy hopefamily --version events@2.2.0
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"name events as well"* ]]
|
||||
|
||||
run bash "$CC" deploy hopefamily events --main --version events@2.2.0
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"not both"* ]]
|
||||
|
||||
run bash "$CC" deploy hopefamily calendar
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *'Unknown product "calendar"'* ]]
|
||||
|
||||
run bash "$CC" deploy hopefamily --frobnicate
|
||||
[ "$status" -eq 1 ]
|
||||
|
||||
run bash "$CC" deploy events --every-church
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" != *"doesn't take a church name"* ]]
|
||||
|
||||
run bash "$CC" deploy hopefamily --every-church
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"doesn't take a church name"* ]]
|
||||
}
|
||||
|
||||
@test "install and adopt check their arguments" {
|
||||
run bash "$CC" install Hope --products events --domain hope.co.za --no-ssl
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"isn't a church name"* ]]
|
||||
|
||||
run bash "$CC" install hope --products website --domain hope.co.za --no-ssl
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"can only install events"* ]]
|
||||
|
||||
run bash "$CC" install hope --products events --domain hope.co.za
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"--email is required"* ]]
|
||||
|
||||
run bash "$CC" adopt hope
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"--events-dir is required"* ]]
|
||||
|
||||
run bash "$CC" adopt hope --events-dir /var/www/hope-events --version 2.2.0
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"expected events@x.y.z"* ]]
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
#!/usr/bin/env bats
|
||||
# The parts of the crosscode script that don't need a server: versions, tags, WHATS-NEW.md
|
||||
# requirements, church.env and .env reading. Run with `npm run test:scripts`.
|
||||
|
||||
setup() {
|
||||
# shellcheck source=../lib/common.sh
|
||||
source "$BATS_TEST_DIRNAME/../lib/common.sh"
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
}
|
||||
|
||||
# ── version_ge ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@test "version_ge compares x.y.z numerically" {
|
||||
version_ge 1.2.0 1.2.0
|
||||
version_ge 1.10.0 1.9.9
|
||||
version_ge 2.0.0 1.99.99
|
||||
run version_ge 1.9.0 1.10.0
|
||||
[ "$status" -eq 1 ]
|
||||
run version_ge 2.1.1 2.2.0
|
||||
[ "$status" -eq 1 ]
|
||||
}
|
||||
|
||||
@test "version_ge puts a prerelease below its release" {
|
||||
version_ge 2.2.0 2.2.0-test
|
||||
run version_ge 2.2.0-test 2.2.0
|
||||
[ "$status" -eq 1 ]
|
||||
version_ge 2.2.0-rc2 2.2.0-rc1
|
||||
version_ge 2.2.0-test 2.1.9
|
||||
}
|
||||
|
||||
@test "version_ge refuses something that isn't a version" {
|
||||
run version_ge abc 1.0.0
|
||||
[ "$status" -eq 2 ]
|
||||
}
|
||||
|
||||
# ── tags ────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@test "latest_tag_from takes the newest release of that product only" {
|
||||
run latest_tag_from events <<'EOF'
|
||||
events@2.2.0
|
||||
events@2.10.0
|
||||
events@2.9.3
|
||||
events@3.0.0-test
|
||||
website@9.0.0
|
||||
contracts@1.1.0
|
||||
eventsx@4.0.0
|
||||
EOF
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$output" = "events@2.10.0" ]
|
||||
}
|
||||
|
||||
@test "latest_tag_from is empty without releases" {
|
||||
run latest_tag_from events <<'EOF'
|
||||
events@2.2.0-test
|
||||
contracts@1.0.0
|
||||
EOF
|
||||
[ "$output" = "" ]
|
||||
}
|
||||
|
||||
@test "latest_tag and checkout_ref read a real checkout" {
|
||||
git init -q "$TMP/repo"
|
||||
cd "$TMP/repo"
|
||||
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m one
|
||||
git tag events@2.2.0
|
||||
git tag contracts@1.1.0
|
||||
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m two
|
||||
git tag events@2.2.1
|
||||
git tag events@2.3.0-test
|
||||
[ "$(latest_tag "$TMP/repo" events)" = "events@2.2.1" ]
|
||||
[ "$(checkout_ref "$TMP/repo" events)" = "events@2.2.1" ]
|
||||
git checkout -q --detach events@2.2.0
|
||||
[ "$(checkout_ref "$TMP/repo" events)" = "events@2.2.0" ]
|
||||
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m three
|
||||
[ "$(checkout_ref "$TMP/repo" events)" = "$(git rev-parse --short HEAD)" ]
|
||||
[ "$(tag_version events@2.2.1)" = "2.2.1" ]
|
||||
}
|
||||
|
||||
# ── WHATS-NEW.md requirements ───────────────────────────────────────────────────────────────
|
||||
|
||||
whatsnew() {
|
||||
cat <<'EOF'
|
||||
# What's new in Cross Events
|
||||
|
||||
<!--
|
||||
How this file is used: … Each version is a "## 1.2.3" heading; add "— urgent" …
|
||||
## 9.9.9 — requires accounts 9.9.9
|
||||
-->
|
||||
|
||||
## 3.1.0 — urgent — requires accounts 1.3.0, website v1.1.0
|
||||
|
||||
- Something.
|
||||
|
||||
## 3.0.0 — requires accounts 1.2.0
|
||||
|
||||
- Sign-in moves.
|
||||
|
||||
## [2.4.0] - 2026-12-01 — Requires Website 1.0.0 — urgent
|
||||
|
||||
## 2.3.0 — urgent
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Nothing changes for you.
|
||||
EOF
|
||||
}
|
||||
|
||||
@test "whatsnew_requires reads one requirement" {
|
||||
run whatsnew_requires 3.0.0 < <(whatsnew)
|
||||
[ "$output" = "accounts 1.2.0" ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires reads several, after urgent and with a v prefix" {
|
||||
run whatsnew_requires 3.1.0 < <(whatsnew)
|
||||
[ "${lines[0]}" = "accounts 1.3.0" ]
|
||||
[ "${lines[1]}" = "website 1.1.0" ]
|
||||
[ "${#lines[@]}" -eq 2 ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires ignores case, brackets, dates and a trailing urgent" {
|
||||
run whatsnew_requires 2.4.0 < <(whatsnew)
|
||||
[ "$output" = "website 1.0.0" ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires is empty without requirements, or for a missing version" {
|
||||
run whatsnew_requires 2.3.0 < <(whatsnew)
|
||||
[ "$output" = "" ]
|
||||
run whatsnew_requires 2.2.0 < <(whatsnew)
|
||||
[ "$output" = "" ]
|
||||
run whatsnew_requires 1.0.0 < <(whatsnew)
|
||||
[ "$output" = "" ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires skips headings inside HTML comments" {
|
||||
run whatsnew_requires 9.9.9 < <(whatsnew)
|
||||
[ "$output" = "" ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires handles Windows line endings" {
|
||||
run whatsnew_requires 3.0.0 < <(whatsnew | sed 's/$/\r/')
|
||||
[ "$output" = "accounts 1.2.0" ]
|
||||
}
|
||||
|
||||
@test "whatsnew_requires reads the real Cross Events notes" {
|
||||
run whatsnew_requires 2.1.1 < "$BATS_TEST_DIRNAME/../../apps/events/WHATS-NEW.md"
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$output" = "" ]
|
||||
}
|
||||
|
||||
# ── church.env ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@test "church_env_read takes known keys, quoted or bare, and skips the rest" {
|
||||
cat > "$TMP/church.env" <<'EOF'
|
||||
# a comment
|
||||
CHURCH=hopefamily
|
||||
PRODUCTS="events website"
|
||||
ADDRESS=hopefamily.co.za # the address
|
||||
EVENTS_DIR=/var/www/sites/hopefamily/events
|
||||
EVENTS_PM2='hope-events-backend hope-events-frontend'
|
||||
EVENTS_PORTS="5000 3000" # api web
|
||||
PATH=/tmp/evil
|
||||
SOMETHING_ELSE=1
|
||||
lower=1
|
||||
EOF
|
||||
church_env_read "$TMP/church.env"
|
||||
[ "$(cenv CHURCH)" = hopefamily ]
|
||||
[ "$(cenv PRODUCTS)" = "events website" ]
|
||||
[ "$(cenv ADDRESS)" = hopefamily.co.za ]
|
||||
[ "$(pvar events PM2)" = "hope-events-backend hope-events-frontend" ]
|
||||
[ "$(pvar events PORTS)" = "5000 3000" ]
|
||||
[ "$(pvar events DIR)" = /var/www/sites/hopefamily/events ]
|
||||
[ -z "${CENV[PATH]+x}" ]
|
||||
[ -z "${CENV[SOMETHING_ELSE]+x}" ]
|
||||
[ "$PATH" != /tmp/evil ]
|
||||
[ "$(pvar website DIR /fallback)" = /fallback ]
|
||||
}
|
||||
|
||||
@test "church_env_read handles Windows line endings and fails on a missing file" {
|
||||
printf 'CHURCH=grace\r\nEVENTS_DB=grace_events\r\n' > "$TMP/church.env"
|
||||
church_env_read "$TMP/church.env"
|
||||
[ "$(cenv CHURCH)" = grace ]
|
||||
[ "$(pvar events DB)" = grace_events ]
|
||||
run church_env_read "$TMP/missing.env"
|
||||
[ "$status" -eq 1 ]
|
||||
}
|
||||
|
||||
@test "church_env_write writes a fixed order that reads back the same" {
|
||||
CENV=()
|
||||
church_env_set EVENTS_PORTS "5000 3000"
|
||||
church_env_set ADDRESS hopefamily.co.za
|
||||
church_env_set EVENTS_DIR /var/www/sites/hopefamily/events
|
||||
church_env_set ACCOUNTS_DIR /var/www/sites/hopefamily/accounts
|
||||
church_env_set CHURCH hopefamily
|
||||
church_env_set PRODUCTS "accounts events"
|
||||
church_env_write "$TMP/church.env"
|
||||
run grep -v '^#' "$TMP/church.env"
|
||||
[ "${lines[0]}" = "CHURCH=hopefamily" ]
|
||||
[ "${lines[1]}" = 'PRODUCTS="accounts events"' ]
|
||||
[ "${lines[2]}" = "ADDRESS=hopefamily.co.za" ]
|
||||
[ "${lines[3]}" = "ACCOUNTS_DIR=/var/www/sites/hopefamily/accounts" ]
|
||||
[ "${lines[4]}" = "EVENTS_DIR=/var/www/sites/hopefamily/events" ]
|
||||
[ "${lines[5]}" = 'EVENTS_PORTS="5000 3000"' ]
|
||||
CENV=()
|
||||
church_env_read "$TMP/church.env"
|
||||
[ "$(cenv PRODUCTS)" = "accounts events" ]
|
||||
[ "$(pvar events PORTS)" = "5000 3000" ]
|
||||
[ "${#CENV[@]}" -eq 6 ]
|
||||
}
|
||||
|
||||
@test "church_env_set refuses unknown keys and unsafe values" {
|
||||
run church_env_set PATH /tmp
|
||||
[ "$status" -eq 1 ]
|
||||
run church_env_set EVENTS_DIR '/var/www/$(reboot)'
|
||||
[ "$status" -eq 1 ]
|
||||
run church_env_set EVENTS_DIR 'a"b'
|
||||
[ "$status" -eq 1 ]
|
||||
}
|
||||
|
||||
@test "list_churches lists folders with a church.env" {
|
||||
CROSSCODE_SITES="$TMP/sites"
|
||||
mkdir -p "$TMP/sites/hopefamily" "$TMP/sites/grace" "$TMP/sites/.undone-old"
|
||||
touch "$TMP/sites/hopefamily/church.env" "$TMP/sites/grace/church.env"
|
||||
run list_churches
|
||||
[ "${#lines[@]}" -eq 2 ]
|
||||
[[ "$output" == *hopefamily* ]]
|
||||
[[ "$output" == *grace* ]]
|
||||
}
|
||||
|
||||
@test "in_product_order puts products in deploy order, once each" {
|
||||
run in_product_order app events accounts events
|
||||
[ "${lines[0]}" = accounts ]
|
||||
[ "${lines[1]}" = events ]
|
||||
[ "${lines[2]}" = app ]
|
||||
[ "${#lines[@]}" -eq 3 ]
|
||||
}
|
||||
|
||||
@test "valid_slug" {
|
||||
valid_slug hopefamily
|
||||
valid_slug grace-church2
|
||||
run valid_slug Hope
|
||||
[ "$status" -eq 1 ]
|
||||
run valid_slug ../etc
|
||||
[ "$status" -eq 1 ]
|
||||
run valid_slug 1church
|
||||
[ "$status" -eq 1 ]
|
||||
}
|
||||
|
||||
# ── .env and URLs ───────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@test "env_value, db_name_from_url and host_from_url" {
|
||||
cat > "$TMP/.env" <<'EOF'
|
||||
# DATABASE_URL=postgresql://old
|
||||
DATABASE_URL="postgresql://hope_events:p%40ss@localhost:5432/hope_events?schema=public"
|
||||
PORT=5001
|
||||
FRONTEND_URL=https://events.hopefamily.co.za,https://www.hopefamily.co.za
|
||||
EOF
|
||||
[ "$(env_value "$TMP/.env" PORT)" = 5001 ]
|
||||
[ "$(env_value "$TMP/.env" MISSING)" = "" ]
|
||||
[ "$(db_name_from_url "$(env_value "$TMP/.env" DATABASE_URL)")" = hope_events ]
|
||||
[ "$(host_from_url "$(env_value "$TMP/.env" FRONTEND_URL)")" = events.hopefamily.co.za ]
|
||||
[ "$(host_from_url http://localhost:3000/x)" = localhost ]
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env bats
|
||||
# crosscode deploy against a local git "origin", with stub Events hooks that log what they do
|
||||
# instead of running npm, Prisma or PM2. Covers the checks, requirements, order, rollback and
|
||||
# --every-church. What needs a real server is tested on a VM (EVENTS-2.2-PLAN §6).
|
||||
|
||||
git_q() { git -c user.name=test -c user.email=test@test -c init.defaultBranch=main "$@"; }
|
||||
|
||||
setup() {
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
export CROSSCODE_TEST=1 CROSSCODE_NO_UPDATE=1
|
||||
export CROSSCODE_SITES="$TMP/sites"
|
||||
export CROSSCODE_REPO="$TMP/origin"
|
||||
export LOG="$TMP/log"
|
||||
: > "$LOG"
|
||||
|
||||
# The crosscode script, with stub hooks for Events.
|
||||
export CROSSCODE_HOME="$TMP/tools"
|
||||
mkdir -p "$CROSSCODE_HOME/products"
|
||||
cp -R "$BATS_TEST_DIRNAME/../lib" "$BATS_TEST_DIRNAME/../crosscode" "$CROSSCODE_HOME/"
|
||||
cat > "$CROSSCODE_HOME/products/events.sh" <<'EOF'
|
||||
ref() { git -C "$1" describe --tags --exact-match 2>/dev/null || echo main; }
|
||||
events_backup() { echo "backup $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != backup ]; }
|
||||
events_install_deps() { echo "install $(ref "$1")" >> "$LOG"; }
|
||||
events_migrate() { echo "migrate $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != migrate ]; }
|
||||
events_build() { echo "build $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != build ]; }
|
||||
events_rollback_build() { echo "rollback_build $(ref "$1")" >> "$LOG"; }
|
||||
events_expected_version() { cat "$1/apps/events/VERSION"; }
|
||||
events_reload() { echo "reload $(ref "$1")" >> "$LOG"; }
|
||||
events_health_url() { echo http://stub/health; }
|
||||
wait_for_version() { echo "health $2" >> "$LOG"; [ "${FAIL_HEALTH:-}" != "$2" ]; }
|
||||
EOF
|
||||
|
||||
# origin: events@2.2.0, events@2.2.1, events@2.3.0 (which requires accounts 1.0.0).
|
||||
git_q init -q "$TMP/origin"
|
||||
mkdir -p "$TMP/origin/apps/events"
|
||||
release 2.2.0 "## 2.2.0"
|
||||
release 2.2.1 "## 2.2.1"
|
||||
release 2.3.0 "## 2.3.0 — requires accounts 1.0.0"
|
||||
|
||||
add_church hope events@2.2.0
|
||||
}
|
||||
|
||||
release() {
|
||||
printf '%s\n' "$1" > "$TMP/origin/apps/events/VERSION"
|
||||
printf '# What is new\n\n%s\n\n- Notes.\n' "$2" > "$TMP/origin/apps/events/WHATS-NEW.md"
|
||||
git_q -C "$TMP/origin" add -A
|
||||
git_q -C "$TMP/origin" commit -q -m "events $1"
|
||||
git_q -C "$TMP/origin" tag "events@$1"
|
||||
}
|
||||
|
||||
add_church() {
|
||||
local church="$1" at="$2"
|
||||
mkdir -p "$CROSSCODE_SITES/$church"
|
||||
git_q clone -q "$CROSSCODE_REPO" "$CROSSCODE_SITES/$church/events"
|
||||
git_q -C "$CROSSCODE_SITES/$church/events" checkout -q --detach "$at"
|
||||
cat > "$CROSSCODE_SITES/$church/church.env" <<EOF
|
||||
CHURCH=$church
|
||||
PRODUCTS="events"
|
||||
ADDRESS=$church.co.za
|
||||
EVENTS_DIR=$CROSSCODE_SITES/$church/events
|
||||
EVENTS_USER=$(id -un)
|
||||
EVENTS_PM2="$church-events-backend $church-events-frontend"
|
||||
EVENTS_PORTS="5000 3000"
|
||||
EOF
|
||||
}
|
||||
|
||||
on() { git -C "$CROSSCODE_SITES/$1/events" describe --tags --exact-match 2>/dev/null || echo main; }
|
||||
cc() { bash "$CROSSCODE_HOME/crosscode" "$@"; }
|
||||
|
||||
@test "deploy --check refuses a release whose requirement isn't met, and changes nothing" {
|
||||
run cc deploy hope events --check
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"events 2.3.0 requires accounts 1.0.0"* ]]
|
||||
[[ "$output" == *"Nothing was changed"* ]]
|
||||
[ "$(on hope)" = events@2.2.0 ]
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "deploy to the latest release is refused while its requirement isn't met" {
|
||||
run cc deploy hope events
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"Requirements not met"* ]]
|
||||
[ "$(on hope)" = events@2.2.0 ]
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "deploy --check with a met release says it's ready" {
|
||||
run cc deploy hope events --check --version events@2.2.1
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"events@2.2.0 → events@2.2.1"* ]]
|
||||
[[ "$output" == *"ready to deploy"* ]]
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "deploy runs backup, checkout, install, migrate, build, reload and health, in that order" {
|
||||
run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(on hope)" = events@2.2.1 ]
|
||||
[ "$(cat "$LOG")" = "$(printf '%s\n' 'backup events@2.2.0' 'install events@2.2.1' 'migrate events@2.2.1' 'build events@2.2.1' 'reload events@2.2.1' 'health 2.2.1')" ]
|
||||
[[ "$output" == *"updated events@2.2.0 → events@2.2.1"* ]]
|
||||
}
|
||||
|
||||
@test "a church already on the release is left alone" {
|
||||
run cc deploy hope events --version events@2.2.0
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"already on events@2.2.0"* ]]
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "a failed backup changes nothing" {
|
||||
FAIL_AT=backup run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[ "$(on hope)" = events@2.2.0 ]
|
||||
[[ "$output" == *"failed at the backup"* ]]
|
||||
run grep -q install "$LOG"
|
||||
[ "$status" -ne 0 ]
|
||||
}
|
||||
|
||||
@test "a failed migration goes back to the previous release, without reloading" {
|
||||
FAIL_AT=migrate run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[ "$(on hope)" = events@2.2.0 ]
|
||||
[[ "$output" == *"rolled back to events@2.2.0 (the running version was never stopped)"* ]]
|
||||
grep -qx "rollback_build events@2.2.0" "$LOG"
|
||||
run grep -q reload "$LOG"
|
||||
[ "$status" -ne 0 ]
|
||||
}
|
||||
|
||||
@test "a release that doesn't come up is rolled back, reloaded and checked again" {
|
||||
FAIL_HEALTH=2.2.1 run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[ "$(on hope)" = events@2.2.0 ]
|
||||
[ "$(grep -c reload "$LOG")" -eq 2 ]
|
||||
grep -qx "health 2.2.0" "$LOG"
|
||||
[[ "$output" == *"rolled back to events@2.2.0 and running again"* ]]
|
||||
}
|
||||
|
||||
@test "files changed by hand stop the deploy" {
|
||||
echo "hand edit" >> "$CROSSCODE_SITES/hope/events/apps/events/VERSION"
|
||||
run cc deploy hope events --version events@2.2.1 --check
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"changed or added by hand"* ]]
|
||||
[[ "$output" == *"apps/events/VERSION"* ]]
|
||||
run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "--allow-local-changes deploys with a file added by hand" {
|
||||
echo "notes" > "$CROSSCODE_SITES/hope/events/apps/events/notes.txt"
|
||||
run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[ ! -s "$LOG" ]
|
||||
run cc deploy hope events --version events@2.2.1 --allow-local-changes
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"deploying anyway"* ]]
|
||||
[ "$(on hope)" = events@2.2.1 ]
|
||||
# --check never passes with changes, even with the flag.
|
||||
run cc deploy hope events --check --allow-local-changes
|
||||
[ "$status" -eq 1 ]
|
||||
}
|
||||
|
||||
@test "ignored files (.env, ecosystem.config.js) don't count as changes" {
|
||||
printf '.env\n/apps/events/ecosystem.config.js\n' > "$CROSSCODE_SITES/hope/events/.git/info/exclude"
|
||||
echo "SECRET=1" > "$CROSSCODE_SITES/hope/events/.env"
|
||||
echo "module.exports = {}" > "$CROSSCODE_SITES/hope/events/apps/events/ecosystem.config.js"
|
||||
run cc deploy hope events --version events@2.2.1
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(on hope)" = events@2.2.1 ]
|
||||
}
|
||||
|
||||
@test "a product the church doesn't have is refused; nothing named does nothing" {
|
||||
run cc deploy hope website
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"hope has no website"* ]]
|
||||
run cc deploy hope
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *"Nothing to deploy"* ]]
|
||||
}
|
||||
|
||||
@test "deploy --main checks out the latest main" {
|
||||
release 2.4.0-dev "## 2.4.0-dev"
|
||||
git_q -C "$TMP/origin" tag -d events@2.4.0-dev >/dev/null
|
||||
run cc deploy hope events --main
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(on hope)" = main ]
|
||||
grep -qx "health 2.4.0-dev" "$LOG"
|
||||
}
|
||||
|
||||
@test "deploy --every-church updates each church, one after the other" {
|
||||
add_church grace events@2.2.0
|
||||
run cc deploy --every-church events --version events@2.2.1
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(on hope)" = events@2.2.1 ]
|
||||
[ "$(on grace)" = events@2.2.1 ]
|
||||
[ "$(grep -c '^health 2.2.1' "$LOG")" -eq 2 ]
|
||||
}
|
||||
|
||||
@test "deploy --every-church stops at the first church that fails" {
|
||||
add_church grace events@2.2.0
|
||||
FAIL_AT=build run cc deploy --every-church events --version events@2.2.1
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"Stopped at "* ]]
|
||||
[ "$(grep -c '^backup' "$LOG")" -eq 1 ]
|
||||
}
|
||||
|
||||
@test "unknown church" {
|
||||
run cc deploy nowhere events
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *'No church "nowhere"'* ]]
|
||||
}
|
||||
Reference in New Issue
Block a user