raz / site / Source.raz

410 lines · 17.8 KiB · raw · history · last change de634aad

1(* Source: the static source browser and the releases, built by ladle
2 after Build has made the pages.
3
4 Source [--ladle path] [--url address] [vX.Y.Z=COMMIT ...]
5
6 Run from the repository root, by make site-source. It reads
7 committed main and the existing, checksummed compiler
8 distributions, and writes only site/public/source/ and the header
9 rules at its root. It does not build compilers, create tags, upload
10 files or deploy the site. The layout and the publishing rules are in
11 site/README.md. It needs git, gzip and ladle, which it runs, and
12 Site, Releases and Sha256. *)
13module Source;
14import Sys, Files, Buf, Str, Heap, Fmt, Opt, Site, Releases, Sha256;
15import Commits := Map([]const U8, BOOL, Str.hash, Str.eq);
16import Rels := Vec(Releases.Release);
17import Sizes := Vec(Sized);
18
19const
20 Url = "https://raz.lucela.org/source/"; (* where the browser is, unless --url says *)
21 BeginHeaders = "# BEGIN ladle source\n"; (* the block of ladle's header rules in the root _headers *)
22 EndHeaders = "# END ladle source\n";
23 MaxFiles = 20000; (* files the host takes *)
24 MaxFileBytes = 25 * 1024 * 1024; (* bytes of its largest file *)
25 LadleKey = 1; (* the keys of --ladle and --url, which have no letter *)
26 UrlKey = 2;
27 Table: []Opt.Row = [
28 Opt.usage("", "Source [--ladle path] [--url address] [vX.Y.Z=COMMIT ...]"),
29 Opt.option("", LadleKey, "ladle", "path", "use this ladle instead of the checked-in static executable"),
30 Opt.option("", UrlKey, "url", "address", "the site's absolute /source/ address")];
31
32type
33 (* A file of the site and its size, for the host's limits. *)
34 Sized = record
35 path: []const U8;
36 size: I64;
37 end;
38
39(* ---- the clone ---------------------------------------------------- *)
40
41(* Adds the lines of text, none empty, to the set of commits m. *)
42proc addAll(var m: Commits.Map; text: []const U8);
43var all: [][]const U8; i: INT;
44begin
45 all := Site.lines(text);
46 for i := 0 to LEN(all) - 1 do
47 if LEN(all[i]) > 0 then _ := Commits.put(m, all[i], true); end;
48 end;
49end;
50
51(* Clones main of the repository at root independently into directory,
52 keeping only the tags whose commits it reaches; the clone's path.
53 A deployment checkout can be detached and have no local branch: its
54 commit is named main only inside this temporary published store. *)
55proc prepareStore*(root, directory: []const U8): []const U8;
56var
57 store, ref, tag, reached: []const U8; all: [][]const U8; known: Commits.Map;
58 out, err: Buf.Buf; local, ok: BOOL; i: INT;
59begin
60 store := Site.cat([directory, "/raz.git"]);
61 ref, ok := Releases.mainRef(root);
62 if not ok then Site.die("site build needs main or a detached deployment checkout", []); end;
63 local := ref # "HEAD";
64 if local then
65 Site.must(["git", "clone", "--quiet", "--bare", "--single-branch", "--no-local", "--branch", "main", root, store]);
66 else
67 Site.must(["git", "clone", "--quiet", "--bare", "--single-branch", "--no-local", root, store]);
68 _ := Site.git(store, ["update-ref", "refs/heads/main", Site.git(store, ["rev-parse", "HEAD"])]);
69 _ := Site.git(store, ["symbolic-ref", "HEAD", "refs/heads/main"]);
70 end;
71 Commits.init(known, Heap.heap);
72 addAll(known, Site.git(store, ["rev-list", "main"]));
73 all := Site.lines(Site.git(store, ["tag", "--list"]));
74 for i := 0 to LEN(all) - 1 do
75 tag := all[i];
76 if LEN(tag) > 0 then
77 (* Tags of trees or blobs are not cloneable releases. Ask quietly:
78 such a tag is valid git, simply outside the published history. *)
79 Buf.init(out, Heap.heap);
80 Buf.init(err, Heap.heap);
81 ok := Site.capture(Site.gitArgs(store, ["rev-parse", "--verify", Site.cat(["refs/tags/", tag, "^{commit}"])]),
82 "", [], false, out, err) = 0;
83 reached := Str.trim(Buf.bytes(out));
84 if ok then _, ok := Commits.get(known, reached); end;
85 if not ok then _ := Site.git(store, ["update-ref", "-d", Site.cat(["refs/tags/", tag])]); end;
86 end;
87 end;
88 _ := Site.git(store, ["repack", "-a", "-d", "--max-pack-size=20m"]);
89 _ := Site.git(store, ["update-server-info"]);
90 return store;
91end;
92
93(* ---- checksums ---------------------------------------------------- *)
94
95(* Where a file's published checksum is: its path and .sha256. *)
96proc sumPath(path: []const U8): []const U8;
97begin
98 return Site.cat([path, ".sha256"]);
99end;
100
101(* The SHA-256, as hex, of the file at path. *)
102proc digest(path: []const U8): []const U8;
103var b: Buf.Buf;
104begin
105 Buf.init(b, Heap.heap);
106 Sha256.hex(Site.read(path), b);
107 return Buf.bytes(b);
108end;
109
110(* The published checksum of the file at path, never replaced to fit
111 different bytes; the empty string and why if it isn't a SHA-256 and
112 the file's name. *)
113proc publishedSum(path: []const U8): ([]const U8, []const U8);
114var words: [][]const U8; name: []const U8; i: INT; hex: BOOL;
115begin
116 name := path[Str.findLast(path, "/") + 1..LEN(path)];
117 words := Site.words(Site.read(sumPath(path)));
118 hex := (LEN(words) = 2) and (LEN(words[0]) = 64) and (words[1] = name);
119 if hex then
120 for i := 0 to 63 do
121 hex := hex and (Str.isDigit(words[0][i]) or ((words[0][i] >= 'a') and (words[0][i] <= 'f')));
122 end;
123 end;
124 if not hex then
125 return "", Site.cat([sumPath(path), ": expected SHA-256 and ", name]);
126 end;
127 return words[0], "";
128end;
129
130(* The static builder: the checked-in ladle.gz, whose bytes must have its
131 recorded SHA-256, unpacked to executable, needing no compiler or
132 network; the executable's path, or the empty string and why. It is
133 renamed into place, a new inode: another build may still be running
134 the previous executable, which can't be overwritten on Linux. *)
135proc pinnedLadle*(archive, executable: []const U8): ([]const U8, []const U8);
136var want, why, temporary: []const U8; slash, fd, status: INT;
137begin
138 want, why := publishedSum(archive);
139 if LEN(why) > 0 then return "", why; end;
140 if digest(archive) # want then return "", Site.cat([archive, ": differs from its recorded SHA-256"]); end;
141 slash := Str.findLast(executable, "/");
142 Site.makeDirs(executable[0..slash]);
143 temporary := Site.cat([executable, ".new"]);
144 fd := Sys.create(temporary);
145 if fd < 0 then Site.die("can't make {}", [Fmt.str(temporary)]); end;
146 status := Site.run(["gzip", "-dc", archive], fd);
147 Sys.close(fd);
148 if status # 0 then Site.die("gzip can't unpack {}", [Fmt.str(archive)]); end;
149 if (Sys.chmod(temporary, 1EDH) < 0) or (Sys.rename(temporary, executable) < 0) then
150 Site.die("can't install {}", [Fmt.str(executable)]);
151 end;
152 return executable, "";
153end;
154
155(* ---- the releases ------------------------------------------------- *)
156
157(* Copies the compiler's distribution of version into directory from
158 public/download, checking its published checksum; why, if it differs. *)
159proc compilerArchive(root, version, directory: []const U8): []const U8;
160var name, original, copied, want, why: []const U8;
161begin
162 name := Site.cat(["raz-", version[1..LEN(version)], "-linux-x86_64.tar.gz"]);
163 original := Site.cat([root, "/site/public/download/", name]);
164 want, why := publishedSum(original);
165 if LEN(why) > 0 then return why; end;
166 copied := Site.cat([directory, "/", name]);
167 Site.copy(original, copied);
168 if digest(copied) # want then return Site.cat([original, ": differs from its published SHA-256"]); end;
169 return "";
170end;
171
172(* Archives exactly the commit, with no wall-clock time or file name in
173 gzip's header; why, if it can't. *)
174proc sourceArchive(store, version, commit, directory: []const U8): []const U8;
175var name, prefix: []const U8; fd, tar, zip: INT;
176begin
177 name := Site.cat([directory, "/raz-", version[1..LEN(version)], "-source.tar.gz"]);
178 prefix := Site.cat(["--prefix=raz-", version[1..LEN(version)], "/"]);
179 fd := Sys.create(name);
180 if fd < 0 then Site.die("can't make {}", [Fmt.str(name)]); end;
181 tar, zip := Site.pipeline(["git", "-C", store, "archive", "--format=tar", prefix, commit], ["gzip", "-9n"], fd);
182 Sys.close(fd);
183 if (tar # 0) or (zip # 0) then return Site.cat(["release ", version, ": git archive failed"]); end;
184 return "";
185end;
186
187(* Puts each selected release in directory/<version>/: its commit, its
188 notes if site/release-notes has them, its compiler and its source;
189 why, if one is wrong. *)
190proc stageReleases(root, store, directory: []const U8; selected: []const Releases.Release): []const U8;
191var line: Commits.Map; release, notes, why: []const U8; i: INT; ok: BOOL;
192begin
193 Commits.init(line, Heap.heap);
194 addAll(line, Site.git(store, ["rev-list", "--first-parent", "main"]));
195 Site.makeDirs(directory);
196 for i := 0 to LEN(selected) - 1 do
197 (* Ref resolution is shared with Build. Check against our snapshot
198 too, so a commit made during the build cannot split their histories. *)
199 _, ok := Commits.get(line, selected[i].commit);
200 if not ok then
201 return Site.cat(["release ", selected[i].tag, ": ", selected[i].commit, " is not in the cloned main history"]);
202 end;
203 release := Site.cat([directory, "/", selected[i].tag]);
204 Site.makeDirs(release);
205 Site.write(Site.cat([release, "/commit"]), Site.cat([selected[i].commit, "\n"]));
206 notes := Site.cat([root, "/site/release-notes/", selected[i].tag, ".md"]);
207 if Site.exists(notes) then Site.copy(notes, Site.cat([release, "/notes.md"])); end;
208 why := compilerArchive(root, selected[i].tag, release);
209 if LEN(why) > 0 then return why; end;
210 why := sourceArchive(store, selected[i].tag, selected[i].commit, release);
211 if LEN(why) > 0 then return why; end;
212 end;
213 return "";
214end;
215
216(* Copies only the dumb-HTTP store into output, never configuration or
217 local paths: HEAD, info/refs, objects/info/packs and objects/pack. *)
218proc exportStore(store, output: []const U8);
219var names: [][]const U8; i: INT;
220begin
221 Site.copy(Site.cat([store, "/HEAD"]), Site.cat([output, "/HEAD"]));
222 Site.copy(Site.cat([store, "/info/refs"]), Site.cat([output, "/info/refs"]));
223 Site.copy(Site.cat([store, "/objects/info/packs"]), Site.cat([output, "/objects/info/packs"]));
224 names := Site.dirNames(Site.cat([store, "/objects/pack"]));
225 Site.makeDirs(Site.cat([output, "/objects/pack"]));
226 for i := 0 to LEN(names) - 1 do
227 Site.copy(Site.cat([store, "/objects/pack/", names[i]]), Site.cat([output, "/objects/pack/", names[i]]));
228 end;
229end;
230
231(* ---- headers and limits ------------------------------------------- *)
232
233(* The root header file with our scoped block replaced by the rules ladle
234 generated, prefixed with /source, keeping the host's other rules;
235 and why, if the old block has no end. *)
236proc mergedHeaders(path, generated: []const U8): ([]const U8, []const U8);
237var existing, before, rest, after: []const U8; found: BOOL; b: Buf.Buf; all: [][]const U8; i: INT;
238begin
239 existing := "";
240 if Site.exists(path) then existing := Site.read(path); end;
241 if Str.find(existing, BeginHeaders) >= 0 then
242 before, rest, found := Str.cut(existing, BeginHeaders);
243 _, after, found := Str.cut(rest, EndHeaders);
244 if not found then return "", Site.cat([path, ": source header block has no closing marker"]); end;
245 existing := Site.cat([before, after]);
246 end;
247 Buf.init(b, Heap.heap);
248 Buf.str(b, Str.trimRight(existing));
249 Buf.str(b, "\n\n");
250 Buf.str(b, BeginHeaders);
251 all := Site.lines(generated);
252 if (LEN(all) > 0) and (LEN(all[LEN(all) - 1]) = 0) then all := all[0..LEN(all) - 1]; end;
253 for i := 0 to LEN(all) - 1 do
254 if i > 0 then Buf.add(b, '\n'); end;
255 if Str.hasPrefix(all[i], "/") then Buf.str(b, "/source"); end;
256 Buf.str(b, all[i]);
257 end;
258 Buf.add(b, '\n');
259 Buf.str(b, EndHeaders);
260 return Buf.bytes(b), "";
261end;
262
263(* Adds every file under dir to v with its size, skipping the top-level
264 names in skip. *)
265proc walk(dir: []const U8; skip: [][]const U8; var v: Sizes.Vec);
266var names: [][]const U8; f: Sys.Info; path: []const U8; err, i, k: INT; skipped: BOOL;
267begin
268 names := Site.dirNames(dir);
269 for i := 0 to LEN(names) - 1 do
270 skipped := false;
271 for k := 0 to LEN(skip) - 1 do skipped := skipped or (names[i] = skip[k]); end;
272 if not skipped then
273 path := Site.cat([dir, "/", names[i]]);
274 f, err := Sys.info(path);
275 if (err = 0) and f.dir then walk(path, [], v);
276 elsif (err = 0) and f.file then Sizes.push(v, {path: path, size: f.size});
277 end;
278 end;
279 end;
280end;
281
282(* Measures the complete proposed output: the files of public/ but the
283 old source tree and the root _headers, the new source tree, once,
284 and the new headers. why if one is too big or there are too many;
285 otherwise prints the totals for review against the hosting plan. *)
286proc checkLimits(public, output: []const U8; headers: []const U8): []const U8;
287var v: Sizes.Vec; all: []Sized; total, largest: I64; i: INT; b: Buf.Buf;
288begin
289 Sizes.init(v, Heap.heap);
290 walk(public, ["source", "_headers"], v);
291 walk(output, [], v);
292 Sizes.push(v, {path: Site.cat([public, "/_headers"]), size: I64(LEN(headers))});
293 all := Sizes.all(v);
294 for i := 0 to LEN(all) - 1 do
295 if all[i].size > MaxFileBytes then
296 Buf.init(b, Heap.heap);
297 Fmt.write(b, "{}: {} bytes exceeds the 25 MiB file limit", [Fmt.str(all[i].path), Fmt.int(all[i].size)]);
298 return Buf.bytes(b);
299 end;
300 total := total + all[i].size;
301 if all[i].size > largest then largest := all[i].size; end;
302 end;
303 if LEN(all) > MaxFiles then
304 Buf.init(b, Heap.heap);
305 Fmt.write(b, "site: {} files exceeds the {} file limit", [Fmt.int(LEN(all)), Fmt.int(MaxFiles)]);
306 return Buf.bytes(b);
307 end;
308 Fmt.print("site/public: {} files, {} bytes; largest file {} bytes\n",
309 [Fmt.int(LEN(all)), Fmt.int(total), Fmt.int(largest)]);
310 return "";
311end;
312
313(* ---- the build ---------------------------------------------------- *)
314
315(* Whether url is an HTTP(S) address ending in /source/ with no query or
316 fragment. *)
317proc validUrl(url: []const U8): BOOL;
318var rest: []const U8; slash: INT;
319begin
320 if Str.hasPrefix(url, "https://") then rest := url[8..LEN(url)];
321 elsif Str.hasPrefix(url, "http://") then rest := url[7..LEN(url)];
322 else return false;
323 end;
324 slash := Str.find(rest, "/");
325 return (slash > 0) and (rest[slash..LEN(rest)] = "/source/");
326end;
327
328(* Builds the browser in a temporary directory of build/site/, then
329 replaces public/source with it. A failed checksum, ladle run or
330 host-limit check leaves the previous browser in place: nothing reads
331 that output. The empty string, or why it failed. *)
332proc build(root, ladle, url: []const U8; extra: []const Releases.Release): []const U8;
333var
334 public, work, store, releases, output, headers, why, exe: []const U8; selected: []Releases.Release;
335begin
336 if not validUrl(url) then return "--url must be an HTTP(S) address ending in /source/"; end;
337 public := Site.cat([root, "/site/public"]);
338 if not Site.isDir(public) then return "site/public is missing; run Build first"; end;
339 selected, why := Releases.refs(root, extra); (* completes a shallow deployment checkout before cloning *)
340 if LEN(why) > 0 then return why; end;
341 exe := ladle;
342 if LEN(exe) = 0 then
343 exe, why := pinnedLadle(Site.cat([root, "/site/tools/ladle.gz"]), Site.cat([root, "/build/site/ladle"]));
344 if LEN(why) > 0 then return why; end;
345 end;
346 Site.makeDirs(Site.cat([root, "/build/site"]));
347 work := Site.tempDirIn(Site.cat([root, "/build/site"]));
348 store := prepareStore(root, work);
349 releases := Site.cat([work, "/releases"]);
350 why := stageReleases(root, store, releases, selected);
351 output := Site.cat([work, "/source"]);
352 Site.makeDirs(output);
353 if LEN(why) = 0 then
354 exportStore(store, output);
355 if Site.run([exe, "-u", url, "-r", releases, "-t", Site.cat([root, "/site/source.theme"]), "-o", output, store], 0) # 0 then
356 why := "ladle failed";
357 end;
358 end;
359 if LEN(why) = 0 then
360 headers, why := mergedHeaders(Site.cat([public, "/_headers"]), Site.read(Site.cat([output, "/_headers"])));
361 end;
362 if LEN(why) = 0 then why := checkLimits(public, output, headers); end;
363 if LEN(why) = 0 then
364 _ := Files.removeTree(Site.cat([public, "/source"]));
365 if Sys.rename(output, Site.cat([public, "/source"])) < 0 then Site.die("can't move {}", [Fmt.str(output)]); end;
366 Site.write(Site.cat([public, "/_headers"]), headers);
367 end;
368 _ := Files.removeTree(work);
369 return why;
370end;
371
372(* The vX.Y.Z=COMMIT arguments given to Opt as releases; the empty
373 string and the first wrong word, if one is. *)
374proc readReleases(var p: Opt.Parser; var v: Rels.Vec): []const U8;
375var arg, tag, commit: []const U8; more, found: BOOL;
376begin
377 arg, more := Opt.operand(p);
378 while more do
379 tag, commit, found := Str.cut(arg, "=");
380 if not found or (LEN(commit) = 0) then return Site.cat([arg, ": expected vX.Y.Z=COMMIT"]); end;
381 Rels.push(v, {tag: tag, commit: commit});
382 arg, more := Opt.operand(p);
383 end;
384 return "";
385end;
386
387proc main*;
388var
389 p: Opt.Parser; ladle, url, root, why: []const U8; extra: Rels.Vec; err: INT;
390begin
391 ladle := "";
392 url := Url;
393 Opt.init(p, "Source", Table);
394 while Opt.next(p) do
395 if p.letter = LadleKey then ladle := p.value;
396 elsif p.letter = UrlKey then url := p.value;
397 end;
398 end;
399 Rels.init(extra, Heap.heap);
400 root, err := Sys.workDir();
401 if err < 0 then Site.die("source: no working directory", []); end;
402 root := Site.cat([root]);
403 if LEN(ladle) > 0 then
404 if ladle[0] # '/' then ladle := Site.cat([root, "/", ladle]); end; (* as Path.resolve would *)
405 end;
406 why := readReleases(p, extra);
407 if LEN(why) = 0 then why := build(root, ladle, url, Rels.all(extra)); end;
408 if LEN(why) > 0 then Site.die("source: {}", [Fmt.str(why)]); end;
409end;
410end Source.