peppa/packages/core/src/product.ts

100 lines
5.6 KiB
TypeScript

// PEP-111: «Ваш продукт» — where the result of the project lives, in words for a product
// manager: the working version everyone sees (prod), the version to check (staging), or the
// fact that the project is not deployed as a site at all.
import { getVersion, proposedCount } from "./task-origin.ts";
import { m as tr } from "@peppa/shared/i18n";
import { formatTaskKey } from "@peppa/shared";
import { projects, releases, tasks, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { openProductLinkTask } from "./product-link.ts";
export interface ProductVersion {
url: string;
at: Date;
/** Story keys that went into it. */
stories: string[];
}
export interface ProjectProduct {
/** The working product, open to everyone. */
live: ProductVersion | null;
/** The version to check before showing it to everyone — only when newer than `live`. */
check: ProductVersion | null;
/** Stories accepted so far (a product without a site still has results). */
doneStories: number;
/** PEP-145: the open system story «Продукт должен открываться по ссылке». */
fix: { key: string; working: boolean } | null;
/** PEP-145: the last update of the version to check did not come up (the earlier one still runs). */
broken: boolean;
/** PEP-145: no link yet, but it is on its way — an update is running or the system story is open. */
preparing: boolean;
/** PEP-145: a screenshot of the first page (taken on a story's version to check, PEP-44). */
shot: { releaseId: number; n: number } | null;
/** PEP-197: everything a person asked for in this version is accepted and nothing is broken. */
versionDone: boolean;
/** PEP-197: stories the factory suggested that wait for the owner. */
proposed: number;
}
/** An update that reported «начато» and nothing since is not «идёт» for ever. */
const DEPLOYING_MS = 30 * 60_000;
export async function projectProduct(db: Db, projectId: number): Promise<ProjectProduct> {
const latest = async (env: "prod" | "staging") =>
(await db.select().from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))).orderBy(desc(releases.id)).limit(1))[0];
const [prod, staging] = [await latest("prod"), await latest("staging")];
const version = (r: NonNullable<typeof prod>): ProductVersion | null => (r.host ? { url: `https://${r.host}`, at: r.updatedAt ?? r.createdAt, stories: r.tasks } : null);
const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)));
const live = prod ? version(prod) : null;
const check = staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null;
const recent = await db.select({ status: releases.status, createdAt: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(5);
const deploying = recent.some((r) => r.status === "deploying" && Date.now() - r.createdAt.getTime() < DEPLOYING_MS);
const lastFinished = recent.find((r) => r.status !== "deploying" && r.status !== "removed");
const open = await openProductLinkTask(db, projectId);
const [project] = open ? await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)) : [];
const [shot] = await db
.select({ id: releases.id, screenshots: releases.screenshots })
.from(releases)
.where(and(eq(releases.projectId, projectId), eq(releases.env, "preview"), sql`json_array_length(${releases.screenshots}) > 0`))
.orderBy(desc(releases.id))
.limit(1);
const fix = open && project ? { key: formatTaskKey(project.key, open.number), working: open.status !== "backlog" } : null;
return {
live,
check,
doneStories: done.length,
fix,
broken: !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back"),
preparing: !live && !check && (deploying || !!fix),
versionDone: !!(await getVersion(db, projectId))?.doneAt,
proposed: await proposedCount(db, projectId),
shot: shot ? { releaseId: shot.id, n: Math.max(0, shot.screenshots.findIndex((s) => s.path === "/")) } : null,
};
}
/**
* PEP-145: the «Посмотреть» line for a message about an accepted story — the product link, if
* the project has one ("" otherwise). The new version takes a few minutes to come up.
*/
export async function productLookLine(db: Db, projectId: number): Promise<string> {
const product = (await productUrls(db, [projectId])).get(projectId);
return product ? `\n${tr("Продукт обновится через несколько минут: {url}", { url: product.url })}` : "";
}
/** Product links of several projects at once (the Home page): projectId → URL of the best version. */
export async function productUrls(db: Db, projectIds: number[]): Promise<Map<number, { url: string; live: boolean }>> {
const out = new Map<number, { url: string; live: boolean }>();
if (!projectIds.length) return out;
const rows = await db
.select({ projectId: releases.projectId, env: releases.env, host: releases.host })
.from(releases)
.where(and(inArray(releases.projectId, projectIds), inArray(releases.env, ["prod", "staging"]), eq(releases.status, "healthy")))
.orderBy(desc(releases.id));
for (const r of rows) {
if (!r.host) continue;
const cur = out.get(r.projectId);
if (!cur || (!cur.live && r.env === "prod")) out.set(r.projectId, { url: `https://${r.host}`, live: r.env === "prod" });
}
return out;
}