@akanjs/devkit 3.2.0 → 3.2.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,6 +32,11 @@ describe("readProcessRssBytes", () => {
32
32
  });
33
33
  });
34
34
 
35
+ interface BuilderStart {
36
+ onBaseBuilt?: (phaseMs: Record<string, number>) => void;
37
+ onReady?: () => void;
38
+ }
39
+
35
40
  describe("Redis tunnels during dev startup", () => {
36
41
  isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "testing" });
37
42
  const track = tempRoots();
@@ -54,7 +59,10 @@ describe("Redis tunnels during dev startup", () => {
54
59
  ({
55
60
  status: "ready",
56
61
  patcherOff: false,
57
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
62
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
63
+ onBaseBuilt?.({});
64
+ onReady?.();
65
+ },
58
66
  send: () => true,
59
67
  stop: () => undefined,
60
68
  }) as unknown as IncrementalBuilderHost;
@@ -101,7 +109,10 @@ describe("a gateway whose replica crash-loops", () => {
101
109
  const readyBuilder = {
102
110
  status: "ready",
103
111
  patcherOff: false,
104
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
112
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
113
+ onBaseBuilt?.({});
114
+ onReady?.();
115
+ },
105
116
  send: () => true,
106
117
  stop: () => undefined,
107
118
  } as unknown as IncrementalBuilderHost;
@@ -151,7 +162,10 @@ describe("a builder request while no builder is running", () => {
151
162
  const stoppedBuilder = {
152
163
  status: "stopped",
153
164
  patcherOff: false,
154
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
165
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
166
+ onBaseBuilt?.({});
167
+ onReady?.();
168
+ },
155
169
  send: () => false,
156
170
  stop: () => undefined,
157
171
  } as unknown as IncrementalBuilderHost;
@@ -208,7 +222,10 @@ describe("the builder's answers and a returning builder", () => {
208
222
  ({
209
223
  status: "ready",
210
224
  patcherOff: false,
211
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
225
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
226
+ onBaseBuilt?.({});
227
+ onReady?.();
228
+ },
212
229
  send: (message: BuilderMessage) => {
213
230
  sent.push(message);
214
231
  return true;
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import { Logger } from "akanjs/common";
2
4
  import type { BuilderMessage } from "akanjs/server";
3
5
  import type { App } from "../commandDecorators";
@@ -21,6 +23,7 @@ import {
21
23
  } from "./devHostPolicy";
22
24
  import { DevIdleSuspend } from "./devIdleSuspend";
23
25
  import { DevRecycler } from "./devRecycler";
26
+ import { DevStartTimeline } from "./devStartTimeline";
24
27
  import { ProcessRss } from "./processRss";
25
28
 
26
29
  export class AkanAppHost {
@@ -31,6 +34,8 @@ export class AkanAppHost {
31
34
  #lastDevState: DevHostState | null = null;
32
35
  readonly #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
33
36
  #stopping = false;
37
+ //? `pending`: a start is building its first artifact and nothing is on disk; `built`: it is; `settled`: no start runs.
38
+ #firstArtifact: "pending" | "built" | "settled" = "settled";
34
39
  #builderMessageQueue: Promise<void> = Promise.resolve();
35
40
  readonly #backendGraph: BackendImportGraph;
36
41
  readonly #statuses: DevBuildStatusBoard;
@@ -41,6 +46,7 @@ export class AkanAppHost {
41
46
  readonly #builder: DevBuilder;
42
47
  readonly #idle: DevIdleSuspend;
43
48
  readonly #recycler: DevRecycler;
49
+ readonly #timeline: DevStartTimeline;
44
50
  constructor(
45
51
  private readonly app: App,
46
52
  {
@@ -58,17 +64,23 @@ export class AkanAppHost {
58
64
  const isStopping = () => this.#stopping;
59
65
  const statuses = new DevBuildStatusBoard(logger);
60
66
  this.#statuses = statuses;
67
+ this.#timeline = new DevStartTimeline(logger);
61
68
  this.#backend = new DevBackend(
62
69
  app,
63
70
  { env, stdio, logger, statuses, graph },
64
71
  {
65
72
  isStopping,
66
- emit: (state, detail) => this.#emitDevEvent(state, detail),
73
+ emit: (state, detail) => {
74
+ if (state === "ready") this.#timeline.mark("backendReady");
75
+ this.#emitDevEvent(state, detail);
76
+ },
67
77
  beforeSpawn: () => {
78
+ this.#timeline.mark("backendSpawned");
68
79
  // Before the spawn: the new backend numbers its requests from 1 again, so old answers must not reach it.
69
80
  this.#requests.startGeneration();
70
81
  this.#requests.discard("the backend restarted while the builder was away");
71
82
  },
83
+ awaitsArtifact: () => this.#firstArtifact === "pending",
72
84
  toBuilder: (message) => this.#requests.send(message),
73
85
  },
74
86
  );
@@ -99,7 +111,16 @@ export class AkanAppHost {
99
111
  isStopping,
100
112
  onMessage: (message) => this.#enqueueBuilderMessage(message),
101
113
  onAway: () => this.#gap.open("builder replacement"),
102
- onReady: () => this.#requests.flush(),
114
+ onReady: () => {
115
+ this.#timeline.mark("builderReady");
116
+ this.#requests.flush();
117
+ },
118
+ onBaseBuilt: (phaseMs) => {
119
+ this.#timeline.baseBuilt(phaseMs);
120
+ //? A builder retried inside one start wrote the artifact again, under a backend that booted on the first.
121
+ if (this.#firstArtifact === "built") this.#backend.scheduleRestart({ files: [], roles: [] });
122
+ else if (this.#firstArtifact === "pending") this.#firstArtifact = "built";
123
+ },
103
124
  onRestartReady: () => {
104
125
  this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
105
126
  this.#backend.replay();
@@ -154,13 +175,29 @@ export class AkanAppHost {
154
175
  async start() {
155
176
  if (this.#backend.running) await this.#backend.stop();
156
177
  if (this.#builder.current) this.#builder.stop();
157
- const [redisHost] = await Promise.all([
158
- this.#prepareDatabase("redis"),
159
- this.#backendGraph.refresh(),
160
- this.#builder.start(),
161
- ]);
162
- Object.assign(this.env, { REDIS_HOST: redisHost });
163
- this.#backend.start();
178
+ this.#timeline.begin();
179
+ const artifactFile = path.join(this.app.cwdPath, ".akan/artifact/base-artifact.json");
180
+ //? Beside the build only when nothing is on disk: the backend would boot on an artifact an earlier start left.
181
+ this.#firstArtifact = fs.existsSync(artifactFile) ? "settled" : "pending";
182
+ const prepared = Promise.all([this.#prepareDatabase("redis"), this.#backendGraph.refresh()]).then(([redisHost]) => {
183
+ Object.assign(this.env, { REDIS_HOST: redisHost });
184
+ if (this.#firstArtifact !== "settled") this.#backend.start();
185
+ });
186
+ try {
187
+ await Promise.all([this.#builder.start(), prepared]);
188
+ } catch (error) {
189
+ this.#firstArtifact = "settled";
190
+ if (!this.#stopping) await this.#backend.stop();
191
+ throw error;
192
+ }
193
+ const artifactMissing = this.#firstArtifact === "pending" && !fs.existsSync(artifactFile);
194
+ this.#firstArtifact = "settled";
195
+ //? The boot build failed and its builder waits for the fix: a backend holding out for the artifact serves no API.
196
+ if (artifactMissing && !this.#stopping) {
197
+ await this.#backend.restarting;
198
+ await this.#backend.stop();
199
+ }
200
+ if (!this.#backend.running) this.#backend.start();
164
201
  this.#idle.arm();
165
202
  return this;
166
203
  }
@@ -44,6 +44,7 @@ type Boot = "ready" | "exit" | "hold" | "starting";
44
44
  interface BuilderStartOptions {
45
45
  onExit?: () => void;
46
46
  onReady?: () => void;
47
+ onBaseBuilt?: (phaseMs: Record<string, number>) => void;
47
48
  onRestartReady?: () => void;
48
49
  onAway?: () => void;
49
50
  }
@@ -54,12 +55,15 @@ interface FakeBuilder {
54
55
  recycled: string[];
55
56
  stopped: number;
56
57
  toHost: (message: BuilderMessage) => void;
58
+ baseBuilt: (phaseMs?: Record<string, number>) => void;
59
+ exit: () => void;
57
60
  ready: () => void;
58
61
  away: () => void;
59
62
  restartReady: () => void;
60
63
  }
61
64
 
62
65
  interface FakeBackend {
66
+ awaitsArtifact: boolean;
63
67
  sent: BuilderMessage[];
64
68
  signals: string[];
65
69
  lingers: boolean;
@@ -69,6 +73,7 @@ interface FakeBackend {
69
73
  }
70
74
 
71
75
  interface BackendSpawnOptions {
76
+ env?: Record<string, string>;
72
77
  ipc: (message: BuilderMessage) => void;
73
78
  onExit?: (proc: unknown, code: number | null, signal: string | null) => void;
74
79
  }
@@ -100,6 +105,11 @@ const fakeBuilder = (toHost: (message: BuilderMessage) => void, boot: Boot) => {
100
105
  recycled: [],
101
106
  stopped: 0,
102
107
  toHost,
108
+ baseBuilt: (phaseMs = {}) => options.onBaseBuilt?.(phaseMs),
109
+ exit: () => {
110
+ builder.status = "stopped";
111
+ options.onExit?.();
112
+ },
103
113
  ready: () => {
104
114
  builder.status = "ready";
105
115
  options.onReady?.();
@@ -124,8 +134,10 @@ const fakeBuilder = (toHost: (message: BuilderMessage) => void, boot: Boot) => {
124
134
  if (boot === "exit") {
125
135
  builder.status = "stopped";
126
136
  options.onExit?.();
127
- } else if (boot === "ready") builder.ready();
128
- else {
137
+ } else if (boot === "ready") {
138
+ builder.baseBuilt();
139
+ builder.ready();
140
+ } else {
129
141
  builder.status = "starting";
130
142
  if (boot === "starting") options.onReady?.();
131
143
  }
@@ -163,6 +175,7 @@ const fakeBackends = () => {
163
175
  queueMicrotask(() => options.onExit?.(proc, code, signal));
164
176
  };
165
177
  const backend: FakeBackend = {
178
+ awaitsArtifact: options.env?.AKAN_DEV_AWAIT_ARTIFACT === "1",
166
179
  sent: [],
167
180
  signals: [],
168
181
  lingers: false,
@@ -681,6 +694,26 @@ describe("AkanAppHost start and stop", () => {
681
694
  expect(dev.events.slice(seen)).toEqual([]);
682
695
  });
683
696
 
697
+ test("says where a start's time went in one line, once the builder and the backend are both ready", async () => {
698
+ const dev = await devHost(["hold"]);
699
+ const starting = dev.host.start();
700
+ expect(await until(() => dev.builders.length === 1)).toBe(true);
701
+ dev.builder().baseBuilt({ runtime: 1, routes: 2, styles: 3, dictionary: 4, pages: 5, total: 15 });
702
+ dev.builder().ready();
703
+ await starting;
704
+ const timelines = () => dev.logs.filter((line) => line.startsWith("ready in "));
705
+ expect(timelines()).toEqual([]);
706
+
707
+ readyBackend(dev);
708
+
709
+ expect(timelines()).toHaveLength(1);
710
+ expect(timelines()[0]).toContain("base build 15 [runtime 1 · routes 2 · styles 3 · dictionary 4 · pages 5]");
711
+ expect(timelines()[0]).toMatch(/prepare \d+ · builder \d+: spawn \d+ .* · backend \d+ · first artifact at \d+\)$/);
712
+
713
+ dev.backend().say({ type: "backend-ready", pid: 1 });
714
+ expect(timelines()).toHaveLength(1);
715
+ });
716
+
684
717
  test("a second start replaces the backend and the builder the first one started", async () => {
685
718
  const dev = await startedHost();
686
719
 
@@ -691,6 +724,177 @@ describe("AkanAppHost start and stop", () => {
691
724
  });
692
725
  });
693
726
 
727
+ describe("AkanAppHost boots the backend beside the first base build", () => {
728
+ isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "local" });
729
+
730
+ const building = async (boots: Boot[] = ["hold"]) => {
731
+ const dev = await devHost(boots);
732
+ const outcome = { error: null as unknown, settled: false };
733
+ const starting = dev.host.start().then(
734
+ () => void Object.assign(outcome, { settled: true }),
735
+ (error: unknown) => void Object.assign(outcome, { error, settled: true }),
736
+ );
737
+ return { dev, starting, outcome };
738
+ };
739
+ const artifactOf = (dev: DevHost) => path.join(dev.root, "apps/demo/.akan/artifact/base-artifact.json");
740
+ const quiet = () => Bun.sleep(60);
741
+
742
+ test("starts the backend while the builder still builds, told to hold its web surface for the artifact", async () => {
743
+ const { dev, starting, outcome } = await building();
744
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
745
+ expect(dev.backend().awaitsArtifact).toBe(true);
746
+ expect(outcome.settled).toBe(false);
747
+
748
+ dev.builder().baseBuilt();
749
+ dev.builder().ready();
750
+ await starting;
751
+ readyBackend(dev);
752
+
753
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([[]]);
754
+ expect(dev.lastState()).toBe("ready");
755
+ });
756
+
757
+ test("a backend ready before the builder has its requests held, and gets its answers once the builder is ready", async () => {
758
+ const { dev, starting } = await building();
759
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
760
+ dev.builder().baseBuilt();
761
+ readyBackend(dev);
762
+ expect(dev.lastState()).toBe("ready");
763
+ dev.backend().say({ type: "build-graph", id: 7 });
764
+ await quiet();
765
+ expect(dev.builder().sent).toEqual([]);
766
+ expect(dev.backend().sent).toEqual([]);
767
+
768
+ dev.builder().ready();
769
+ await starting;
770
+
771
+ expect(sentOf(dev.builder().sent, "build-graph")).toHaveLength(1);
772
+ expect(dev.backends).toHaveLength(1);
773
+ });
774
+
775
+ test("a builder ready before the backend keeps what it built meanwhile, and the backend gets it at its ready", async () => {
776
+ const { dev, starting } = await building();
777
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
778
+ dev.builder().baseBuilt();
779
+ dev.builder().ready();
780
+ await starting;
781
+ dev.builder().toHost(pages(3));
782
+ dev.builder().toHost({ type: "build-status", data: status(3, false) });
783
+ await quiet();
784
+ expect(dev.backend().sent).toEqual([]);
785
+
786
+ readyBackend(dev);
787
+
788
+ expect(sentOf(dev.backend().sent, "pages-updated")).toEqual([pages(3)]);
789
+ expect(statusesOf(dev.backend().sent)).toContainEqual(status(3, false));
790
+ });
791
+
792
+ test("a save that restarts the backend during start-up replaces it with one that no longer waits", async () => {
793
+ const { dev, starting } = await building();
794
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
795
+ dev.builder().baseBuilt();
796
+ dev.builder().ready();
797
+ await starting;
798
+
799
+ dev.builder().toHost(invalidate(2, ["restart-backend"]));
800
+
801
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
802
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"], []]);
803
+ expect(dev.backend().awaitsArtifact).toBe(false);
804
+ });
805
+
806
+ test("a boot build that wrote no artifact gets a backend that serves the API without waiting for one", async () => {
807
+ const { dev, starting } = await building();
808
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
809
+
810
+ dev.builder().ready();
811
+ await starting;
812
+
813
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"], []]);
814
+ expect(dev.backends.map((backend) => backend.awaitsArtifact)).toEqual([true, false]);
815
+ });
816
+
817
+ test("a builder that never comes up takes the waiting backend down with the failed start", async () => {
818
+ const { dev, starting, outcome } = await building(["hold", "exit", "exit"]);
819
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
820
+
821
+ dev.builder().exit();
822
+ await starting;
823
+
824
+ expect(outcome.error).toBeInstanceOf(Error);
825
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"]]);
826
+ await quiet();
827
+ expect(dev.backends).toHaveLength(1);
828
+ });
829
+
830
+ test("a backend that dies while the builder builds comes back still waiting for the artifact", async () => {
831
+ const { dev, starting } = await building();
832
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
833
+
834
+ dev.backend().crash();
835
+
836
+ expect(await until(() => dev.backends.length === 2, (backendRecoveryPolicy.min ?? 0) + 2_000)).toBe(true);
837
+ expect(dev.backend().awaitsArtifact).toBe(true);
838
+ dev.builder().baseBuilt();
839
+ dev.builder().ready();
840
+ await starting;
841
+ expect(dev.backends).toHaveLength(2);
842
+ expect(dev.backend().signals).toEqual([]);
843
+ });
844
+
845
+ test("a builder retried inside one start restarts a backend that booted on the artifact the first try wrote", async () => {
846
+ const { dev, starting } = await building();
847
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
848
+ dev.builder().baseBuilt();
849
+
850
+ dev.builder().baseBuilt();
851
+
852
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
853
+ expect(dev.backends.map((backend) => backend.awaitsArtifact)).toEqual([true, false]);
854
+ dev.builder().ready();
855
+ await starting;
856
+ });
857
+
858
+ test("a stop during start-up signals the waiting backend once, stops the builder, and starts nothing after", async () => {
859
+ const { dev, starting, outcome } = await building();
860
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
861
+
862
+ await dev.host.stop();
863
+ await starting;
864
+
865
+ expect(outcome.error).toBeInstanceOf(Error);
866
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"]]);
867
+ expect(dev.builder().stopped).toBeGreaterThanOrEqual(1);
868
+ await quiet();
869
+ expect(dev.backends).toHaveLength(1);
870
+ });
871
+
872
+ test("a stop before the backend was spawned never spawns it", async () => {
873
+ const { dev, starting } = await building();
874
+
875
+ await dev.host.stop();
876
+ await starting;
877
+ await quiet();
878
+
879
+ expect(dev.backends).toEqual([]);
880
+ });
881
+
882
+ test("an artifact already on disk keeps the backend behind the builder, so it never boots on the old one", async () => {
883
+ const dev = await devHost(["hold"]);
884
+ await writeText(artifactOf(dev), "{}\n");
885
+ const starting = dev.host.start();
886
+ expect(await until(() => dev.builders.length === 1)).toBe(true);
887
+ await quiet();
888
+ expect(dev.backends).toEqual([]);
889
+
890
+ dev.builder().ready();
891
+ await starting;
892
+
893
+ expect(dev.backends).toHaveLength(1);
894
+ expect(dev.backend().awaitsArtifact).toBe(false);
895
+ });
896
+ });
897
+
694
898
  describe("AkanAppHost on a fake clock", () => {
695
899
  isolateEnv({
696
900
  AKAN_PUBLIC_REPO_NAME: "repo",
@@ -30,6 +30,7 @@ interface DevBackendLinks {
30
30
  isStopping: () => boolean;
31
31
  emit: (state: DevHostState, detail?: string) => void;
32
32
  beforeSpawn: () => void;
33
+ awaitsArtifact: () => boolean;
33
34
  toBuilder: (message: BuilderMessage) => void;
34
35
  }
35
36
 
@@ -129,7 +130,8 @@ export class DevBackend {
129
130
  const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
130
131
  cwd: this.#app.workspace.workspaceRoot,
131
132
  stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
132
- env: this.#env,
133
+ //? The first base build is still running: the backend boots beside it and holds its web surface for the artifact.
134
+ env: this.#links.awaitsArtifact() ? { ...this.#env, AKAN_DEV_AWAIT_ARTIFACT: "1" } : this.#env,
133
135
  ipc: (msg: BuilderMessage) => {
134
136
  if (!msg || typeof msg !== "object") return;
135
137
  if (msg.type === "backend-ready") {
@@ -17,6 +17,7 @@ interface DevBuilderLinks {
17
17
  onMessage: (message: BuilderMessage) => void;
18
18
  onAway: () => void;
19
19
  onReady: () => void;
20
+ onBaseBuilt: (phaseMs: Record<string, number>) => void;
20
21
  onRestartReady: () => void;
21
22
  onStartFailed: () => void;
22
23
  onStop: () => void;
@@ -81,7 +82,7 @@ export class DevBuilder {
81
82
  this.#host = builder;
82
83
  try {
83
84
  await this.#waitForReady(attempt, { announceBootState });
84
- this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms — starting backend`);
85
+ this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms`);
85
86
  return this.#host;
86
87
  } catch (err) {
87
88
  lastError = err;
@@ -187,6 +188,9 @@ export class DevBuilder {
187
188
  settle(resolve);
188
189
  this.#links.onReady();
189
190
  },
191
+ onBaseBuilt: (phaseMs) => {
192
+ this.#links.onBaseBuilt(phaseMs);
193
+ },
190
194
  onRestartReady: () => {
191
195
  this.#links.onRestartReady();
192
196
  },
@@ -0,0 +1,115 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { Logger } from "akanjs/common";
3
+ import { DevStartTimeline } from "./devStartTimeline";
4
+
5
+ const timeline = () => {
6
+ const lines: string[] = [];
7
+ const clock = { at: 0 };
8
+ const logger = { info: (line: string) => void lines.push(line) } as unknown as Logger;
9
+ return { lines, clock, timeline: new DevStartTimeline(logger, () => clock.at) };
10
+ };
11
+
12
+ const phases = { runtime: 70, routes: 200, styles: 900, dictionary: 6, pages: 500, total: 1700 };
13
+
14
+ describe("DevStartTimeline", () => {
15
+ test("names every phase of a start in one line, once the builder and the backend are both ready", () => {
16
+ const { lines, clock, timeline: start } = timeline();
17
+ clock.at = 800;
18
+ start.begin();
19
+ clock.at = 2700;
20
+ start.baseBuilt(phases);
21
+ start.mark("backendSpawned");
22
+ clock.at = 2900;
23
+ start.mark("builderReady");
24
+ expect(lines).toEqual([]);
25
+ clock.at = 3200;
26
+ start.mark("backendReady");
27
+
28
+ expect(lines).toEqual([
29
+ "ready in 3200ms (prepare 800 · builder 2100: spawn 200 + base build 1700 [runtime 70 · routes 200 · styles 900 · dictionary 6 · pages 500] + watch 200 · backend 500 · first artifact at 2700)",
30
+ ]);
31
+ });
32
+
33
+ test("says what a backend spawned beside the build took once the artifact was there", () => {
34
+ const { lines, clock, timeline: start } = timeline();
35
+ clock.at = 800;
36
+ start.begin();
37
+ clock.at = 850;
38
+ start.mark("backendSpawned");
39
+ clock.at = 2700;
40
+ start.baseBuilt(phases);
41
+ clock.at = 2730;
42
+ start.mark("builderReady");
43
+ clock.at = 2950;
44
+ start.mark("backendReady");
45
+
46
+ expect(lines).toHaveLength(1);
47
+ expect(lines[0]).toStartWith("ready in 2950ms (prepare 800 · builder 1930: spawn 200 + base build 1700 [");
48
+ expect(lines[0]).toEndWith("+ watch 30 · backend 2100 (250 after the artifact) · first artifact at 2700)");
49
+ });
50
+
51
+ test("reports at the builder's ready when the backend was ready first", () => {
52
+ const { lines, clock, timeline: start } = timeline();
53
+ start.begin();
54
+ clock.at = 100;
55
+ start.mark("backendSpawned");
56
+ clock.at = 400;
57
+ start.mark("backendReady");
58
+ expect(lines).toEqual([]);
59
+ clock.at = 2000;
60
+ start.baseBuilt(phases);
61
+ clock.at = 2100;
62
+ start.mark("builderReady");
63
+
64
+ expect(lines).toHaveLength(1);
65
+ expect(lines[0]).toStartWith("ready in 2100ms (prepare 0 · builder 2100: spawn 300 + base build 1700 [");
66
+ expect(lines[0]).toEndWith("+ watch 100 · backend 300 · first artifact at 2000)");
67
+ });
68
+
69
+ test("leaves the build's parts out when the boot build wrote no artifact", () => {
70
+ const { lines, clock, timeline: start } = timeline();
71
+ start.begin();
72
+ clock.at = 900;
73
+ start.mark("builderReady");
74
+ start.mark("backendSpawned");
75
+ clock.at = 1300;
76
+ start.mark("backendReady");
77
+
78
+ expect(lines).toEqual(["ready in 1300ms (prepare 0 · builder 900 · backend 400)"]);
79
+ });
80
+
81
+ test("times a backend replaced before it was ready from its last spawn", () => {
82
+ const { lines, clock, timeline: start } = timeline();
83
+ start.begin();
84
+ start.mark("builderReady");
85
+ start.mark("backendSpawned");
86
+ clock.at = 700;
87
+ start.mark("backendSpawned");
88
+ clock.at = 1000;
89
+ start.mark("backendReady");
90
+
91
+ expect(lines).toEqual(["ready in 1000ms (prepare 0 · builder 0 · backend 300)"]);
92
+ });
93
+
94
+ test("says nothing after its one line until the next start, and nothing before the first", () => {
95
+ const { lines, clock, timeline: start } = timeline();
96
+ start.mark("builderReady");
97
+ start.mark("backendReady");
98
+ expect(lines).toEqual([]);
99
+
100
+ start.begin();
101
+ start.mark("builderReady");
102
+ start.mark("backendReady");
103
+ clock.at = 50;
104
+ start.mark("backendSpawned");
105
+ start.mark("backendReady");
106
+ expect(lines).toHaveLength(1);
107
+
108
+ start.begin();
109
+ start.mark("builderReady");
110
+ clock.at = 80;
111
+ start.mark("backendReady");
112
+ expect(lines).toHaveLength(2);
113
+ expect(lines[1]).toBe("ready in 80ms (prepare 50 · builder 0)");
114
+ });
115
+ });
@@ -0,0 +1,69 @@
1
+ import type { Logger } from "akanjs/common";
2
+
3
+ type StartMark = "started" | "baseBuilt" | "builderReady" | "backendSpawned" | "backendReady";
4
+
5
+ const BASE_BUILD_PARTS = ["runtime", "routes", "styles", "dictionary", "pages"];
6
+
7
+ export class DevStartTimeline {
8
+ readonly #logger: Logger;
9
+ readonly #now: () => number;
10
+ #marks: Partial<Record<StartMark, number>> = {};
11
+ #basePhaseMs: Partial<Record<string, number>> = {};
12
+ #reported = true;
13
+
14
+ constructor(logger: Logger, now: () => number = () => performance.now()) {
15
+ this.#logger = logger;
16
+ this.#now = now;
17
+ }
18
+
19
+ begin(): void {
20
+ this.#marks = { started: this.#now() };
21
+ this.#basePhaseMs = {};
22
+ this.#reported = false;
23
+ }
24
+
25
+ baseBuilt(phaseMs: Record<string, number>): void {
26
+ if (this.#reported || this.#marks.baseBuilt !== undefined) return;
27
+ this.#basePhaseMs = phaseMs;
28
+ this.#marks.baseBuilt = this.#now();
29
+ }
30
+
31
+ mark(mark: Exclude<StartMark, "started" | "baseBuilt">): void {
32
+ if (this.#reported) return;
33
+ if (mark === "backendSpawned") this.#marks.backendSpawned = this.#now();
34
+ else this.#marks[mark] ??= this.#now();
35
+ this.#report();
36
+ }
37
+
38
+ #report(): void {
39
+ const { started, baseBuilt, builderReady, backendSpawned, backendReady } = this.#marks;
40
+ if (started === undefined || builderReady === undefined || backendReady === undefined) return;
41
+ this.#reported = true;
42
+ const ms = (value: number) => Math.round(value).toString();
43
+ //? The clock counts from the start of the process, so the first mark is what the CLI spent before the host.
44
+ const parts = [`prepare ${ms(started)}`, `builder ${ms(builderReady - started)}${this.#builderParts()}`];
45
+ if (backendSpawned !== undefined) {
46
+ //? Spawned beside the build, most of its time is the wait for the artifact: what it took after that is its own.
47
+ const afterArtifact =
48
+ baseBuilt !== undefined && backendSpawned < baseBuilt && baseBuilt <= backendReady
49
+ ? ` (${ms(backendReady - baseBuilt)} after the artifact)`
50
+ : "";
51
+ parts.push(`backend ${ms(backendReady - backendSpawned)}${afterArtifact}`);
52
+ }
53
+ if (baseBuilt !== undefined) parts.push(`first artifact at ${ms(baseBuilt)}`);
54
+ this.#logger.info(`ready in ${ms(Math.max(builderReady, backendReady))}ms (${parts.join(" · ")})`);
55
+ }
56
+
57
+ #builderParts(): string {
58
+ const { started, baseBuilt, builderReady } = this.#marks;
59
+ if (started === undefined || baseBuilt === undefined || builderReady === undefined) return "";
60
+ const total = this.#basePhaseMs.total ?? 0;
61
+ const base = BASE_BUILD_PARTS.flatMap((part) => {
62
+ const partMs = this.#basePhaseMs[part];
63
+ return partMs === undefined ? [] : [`${part} ${Math.round(partMs)}`];
64
+ });
65
+ const spawn = Math.max(0, Math.round(baseBuilt - started - total));
66
+ const watch = Math.max(0, Math.round(builderReady - baseBuilt));
67
+ return `: spawn ${spawn} + base build ${Math.round(total)} [${base.join(" · ")}] + watch ${watch}`;
68
+ }
69
+ }