123 lines
7.1 KiB
TypeScript
123 lines
7.1 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, asc, 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-274: no link and nothing is coming up now, while the last update failed or the link has
|
|
* been awaited longer than `LINK_WAIT_MS` — «Готовим ссылку» would be a lie, show an error.
|
|
*/
|
|
stalled: 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;
|
|
|
|
/** PEP-274: how long «Готовим ссылку на продукт» stays honest without a link. */
|
|
export const LINK_WAIT_MS = 60 * 60_000;
|
|
|
|
/** PEP-274: the Home pill — the system story about the link is older than `LINK_WAIT_MS`. */
|
|
export const productLinkStalled = (fix: { at: number } | null, now = Date.now()): boolean => !!fix && now - fix.at > LINK_WAIT_MS;
|
|
|
|
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 broken = !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back");
|
|
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;
|
|
let stalled = false;
|
|
if (!live && !check && !deploying) {
|
|
// PEP-274: the wait started with the earliest of: the system story, the first update, the first accepted story.
|
|
const [first] = await db.select({ at: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(asc(releases.id)).limit(1);
|
|
const [firstDone] = await db.select({ at: sql<number>`min(${tasks.updatedAt})` }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)));
|
|
const doneAt = firstDone?.at == null ? null : Number(firstDone.at);
|
|
const starts = [open?.at, first?.at.getTime(), doneAt].filter((x): x is number => typeof x === "number" && Number.isFinite(x));
|
|
const waitFrom = starts.length ? Math.min(...starts) : null;
|
|
stalled = broken || (waitFrom != null && Date.now() - waitFrom > LINK_WAIT_MS);
|
|
}
|
|
return {
|
|
live,
|
|
check,
|
|
doneStories: done.length,
|
|
fix,
|
|
broken,
|
|
preparing: !live && !check && (deploying || !!fix),
|
|
stalled,
|
|
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;
|
|
}
|