Repository navigation
Expand file tree
/
Copy pathflake.nix
More file actions
2541 lines (2375 loc) · 126 KB
/
Copy pathflake.nix
File metadata and controls
2541 lines (2375 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
description = "Hyperion - A Minecraft game engine";
nixConfig = {
extra-substituters = [ "https://cache.ix.dev" ];
extra-trusted-public-keys = [
"ix-workspace:JuAaeOPfR3GL3nUICpEz/88/+S3BzGF3L6bPYFy0GwI="
];
# cargoUnit content-addresses every crate unit, so a source change that does
# not change a crate's output stops the rebuild there instead of at the root.
extra-experimental-features = [ "ca-derivations" ];
};
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
index = {
url = "github:indexable-inc/index";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, rust-overlay, index, ... }:
let
forAllSystems = nixpkgs.lib.genAttrs [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
# rust-toolchain.toml is the one place the version lives; rustup users and
# CI already read it, so the flake reads it too rather than restating it.
rustChannel = (nixpkgs.lib.importTOML ./rust-toolchain.toml).toolchain.channel;
# Raising this is what keeps the proxy from running out of sockets once a
# few thousand bots connect.
fileDescriptors = "32768";
clippyArgs = "--all-targets --all-features";
mkSystem = system:
let
pkgs = import nixpkgs {
inherit system;
overlays = [ (import rust-overlay) ];
};
inherit (pkgs) lib;
rustWith = components: pkgs.rust-bin.fromRustupToolchain {
channel = rustChannel;
inherit components;
};
# Anything derived from Mojang's server jar is unfree under their EULA,
# so it gets an instance whose unfree allowance is narrowed to exactly
# those derivations. Flipping allowUnfree on the shared instance would
# quietly relax the policy for the whole flake.
minecraftPkgs = import nixpkgs {
inherit system;
config.allowUnfreePredicate =
pkg: nixpkgs.lib.hasPrefix "minecraft-" (nixpkgs.lib.getName pkg);
};
rustToolchain = rustWith [ "rustfmt" "clippy" "rust-src" ];
rustWithMiri = rustWith [ "rustfmt" "clippy" "rust-src" "miri" ];
rustWithCoverage = rustWith [ "rustfmt" "clippy" "rust-src" "llvm-tools-preview" ];
minecraft = import ./nix/minecraft-data.nix {
pkgs = minecraftPkgs;
rustfmt = rustToolchain;
};
# Split out because it is the only pipeline that runs the server
# rather than reading data out of it, and it is the only one whose
# output is checked by a Rust test rather than compiled into one.
differential = import ./nix/differential.nix {
pkgs = minecraftPkgs;
inherit (minecraft) jdk serverClasspath pin;
};
# Styling is a field on a component, never characters in a string.
# See the file: the type covers the seam, this covers the one
# spelling a type cannot.
textGate = import ./nix/text.nix {
inherit pkgs;
sources = {
smashSource = ./events/smash/src;
protoSource = ./crates/hyperion-minecraft-proto/src;
};
};
# One harness behind both the `nix run` gates and the sandboxed
# checks, so the two cannot drift.
e2e = import ./nix/e2e.nix {
inherit pkgs lib fileDescriptors;
sources = {
root = ./.;
tools = ./tools;
protoSource = ./crates/hyperion-minecraft-proto/src;
# The scripted clients resolve registry ids to names through
# this, the same file build.rs reads.
protocolJson = ./crates/hyperion-minecraft-proto/protocol.json;
kitSkins = ./events/smash/skins;
genmap = ./crates/hyperion-genmap/src/lib.rs;
};
};
cargoTools = [
pkgs.cargo-deny
pkgs.cargo-machete
pkgs.cargo-nextest
pkgs.cargo-watch
];
nativeBuildInputs = [
pkgs.cmake
pkgs.pkg-config
];
# What it takes to build this repository, named once. `devShells.default`
# below installs it, and so does the `hyperion-dev` fleet node
# (nix/fleet/dev.nix), so a VM built to develop hyperion on cannot come
# up with a different compiler than `nix develop` hands a contributor.
devEnvironment = {
packages = nativeBuildInputs ++ cargoTools ++ [ rustToolchain ];
rustSrcPath = "${rustToolchain}/lib/rustlib/src/rust/library";
};
# Every dev command carries the tools it needs, so `nix run .#lint`
# works on a machine with nothing but nix installed.
mkScript = name: { text, deps ? [ ], toolchain ? rustToolchain }:
pkgs.writeShellApplication {
inherit name text;
runtimeInputs = [ toolchain ] ++ deps;
};
# Signature checking, and nothing else, so this stays a small closure
# a `nix flake check` can afford.
kitSkinPython = pkgs.python3.withPackages (python: [ python.cryptography ]);
# The client scripts, plus the rule they are held to. Narrow on
# purpose: a check whose input is the whole tree reruns on every
# commit and stops being cheap.
wireAssertionSource = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./nix/verify-wire-assertions.py
./tools
];
};
# The files the skin check reads: the payloads, Mojang's keys, and the
# kit sources that declare which payload is whose. Narrow on purpose,
# so editing an unrelated Rust file does not rebuild the check.
kitSkinSource = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./nix/verify-kit-skins.py
./nix/verify-kit-skin-images.py
./events/smash/skins
./events/smash/src/module/kits
];
};
# Every Rust source, every manifest, and the formatting rules. Narrow
# on purpose: `cargo fmt` reads nothing else, so a change to a world,
# a document or a nix file must not rerun it.
rustfmtSource =
let
formatted =
dir:
lib.fileset.fileFilter (file: file.hasExt "rs" || file.name == "Cargo.toml") dir;
in
lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
(formatted ./crates)
(formatted ./events)
(formatted ./tools)
./Cargo.toml
./rustfmt.toml
];
};
# Every kit's skin image, fetched from the url its signed payload names
# and pinned by hash in textures.lock.json. Fixed-output so the image
# gate stays offline and store-cached: the fetch happens once, here,
# not inside the sandboxed check and not on every run.
kitSkinImages =
let
lock = lib.importJSON ./events/smash/skins/textures.lock.json;
in
pkgs.runCommand "hyperion-kit-skin-images" { } (
lib.concatStringsSep "\n" (
[ "mkdir -p $out" ]
++ lib.mapAttrsToList (
mob: entry:
"cp ${pkgs.fetchurl { inherit (entry) url; hash = entry.sha256; }} $out/${mob}.png"
) lock
)
);
checkScripts = lib.mapAttrs mkScript {
# `flecs_ecs_sys`'s default features include `regenerate_binding`,
# whose build script writes bindgen output into its own source
# directory -- inside the shared cargo registry every checkout on
# the machine reads. Cargo unifies features across the graph, so one
# dependency pulling the sys crate with default features corrupts
# that copy for everyone. `flecs_ecs` sets default-features = false;
# this fails the moment anything reintroduces them. See ENG-10307.
hot-reload-registry-guard.text = ''
tree=$(cargo tree -p hyperion-hot-reload -e features -i flecs_ecs_sys)
if grep -q 'regenerate_binding' <<<"$tree"; then
echo "FAIL: flecs_ecs_sys resolved with regenerate_binding." >&2
echo "Its build script writes into the shared cargo registry." >&2
grep -n 'regenerate_binding' <<<"$tree" >&2
exit 1
fi
echo "ok: flecs_ecs_sys has no regenerate_binding in the resolved graph"
'';
fmt.text = ''cargo fmt --all "$@"'';
# Every kit's skin has to be one the client will show to other
# players, and that means Mojang-signed: an unsigned `textures`
# property renders for its wearer and for nobody else. See
# `events/smash/skins/README.md` for where the client enforces it.
check-kit-skins = {
deps = [
kitSkinPython
pkgs.git
];
text = ''
root="$(git rev-parse --show-toplevel)"
exec python3 "$root/nix/verify-kit-skins.py"
'';
};
# Repin every kit's skin image by hash after a skin changes. Impure
# (it reaches Mojang's texture host), which is why it is a command
# and not a check; the check that reads its output is offline.
sync-kit-skin-textures = {
deps = [
pkgs.python3
pkgs.nix
pkgs.git
];
text = ''
root="$(git rev-parse --show-toplevel)"
exec python3 "$root/nix/sync-kit-skin-textures.py"
'';
};
lint.text = ''cargo clippy ${clippyArgs} -- -D warnings'';
lint-fix.text = ''
cargo clippy --fix --allow-dirty --allow-staged ${clippyArgs} -- -D warnings
'';
test = {
deps = [ pkgs.cargo-nextest ];
text = ''cargo nextest run "$@"'';
};
# How much of the game the tests actually check, as a number.
#
# A mutant is a deliberate change to the source: a `<` flipped to
# `<=`, a function body replaced with a constant. A mutant the suite
# still passes with is a line the tests execute without checking, so
# the surviving count measures verification rather than coverage --
# `nix run .#test` staying green while a mutant lives is exactly
# what this catches and what a coverage percentage cannot.
#
# Scope and exclusions live in `.cargo/mutants.toml`, next to the
# reasons for them. The budget is here because it is a policy
# question rather than a configuration one.
#
# Raising MUTANT_BUDGET is a change to how much of the game is
# checked, so it needs the same argument in a pull request that
# deleting a test would. A mutant genuinely not worth killing gets
# an exclusion in `mutants.toml` with a reason beside it instead.
#
# Roughly fifteen minutes on four cores; not part of `nix flake
# check`, which only builds this script.
mutants = {
deps = [
pkgs.cargo-mutants
pkgs.cargo-nextest
pkgs.coreutils
pkgs.git
];
text = ''
budget="''${MUTANT_BUDGET:-0}"
root="$(git rev-parse --show-toplevel)"
cd "$root"
out="''${MUTANT_OUTPUT:-$root/target/mutants}"
rc=0
cargo mutants --test-tool nextest -j "$(nproc)" --output "$out" "$@" || rc=$?
# 0 is a clean sweep and 2 is "some survived", which is the
# normal case and is judged against the budget below. Anything
# else is cargo-mutants itself failing, and that is not a
# verdict on the tests.
case "$rc" in
0 | 2) ;;
*)
echo "cargo-mutants exited $rc, which is a tool failure rather than a result" >&2
exit "$rc"
;;
esac
missed="$(wc -l < "$out/mutants.out/missed.txt" | tr -d ' ')"
caught="$(wc -l < "$out/mutants.out/caught.txt" | tr -d ' ')"
echo "mutants: $caught killed, $missed survived (budget $budget)"
if [ "$missed" -gt "$budget" ]; then
echo "" >&2
echo "FAIL: $missed mutants survived, which is more than the budget of $budget." >&2
echo "Each line below is a change to the source that every test still passes with." >&2
echo "" >&2
cat "$out/mutants.out/missed.txt" >&2
exit 1
fi
if [ "$missed" -lt "$budget" ]; then
echo "The budget is now loose by $((budget - missed)). Lower MUTANT_BUDGET in flake.nix to hold the ground."
fi
'';
};
# The unbounded version of the decoder fuzz that `nix run .#test`
# runs a fixed slice of.
#
# The gate runs four thousand cases from seed zero, the same four
# thousand every time, because a check that fuzzes differently on
# every run fails for somebody else on a case they cannot get back.
# This walks the seed base forward instead and does not stop, which
# is the same generator searching rather than checking. Leave it
# running; a failure prints the seed, and the seed is enough to
# reproduce the case in the one-second version.
fuzz = {
deps = [
pkgs.cargo-nextest
pkgs.git
];
text = ''
root="$(git rev-parse --show-toplevel)"
cd "$root"
export HYPERION_FUZZ_SEEDS="''${HYPERION_FUZZ_SEEDS:-4096}"
export HYPERION_FUZZ_CASES="''${HYPERION_FUZZ_CASES:-256}"
base="''${HYPERION_FUZZ_SEED_BASE:-0}"
batch=$(( HYPERION_FUZZ_SEEDS ))
echo "fuzzing the packet decoder from seed $base, $batch seeds a round; ctrl-c to stop"
while :; do
export HYPERION_FUZZ_SEED_BASE="$base"
# One line: a backslash continuation is literal inside a Nix
# indented string and reaches the shell as a stray argument.
if ! cargo nextest run -p hyperion-minecraft-proto --no-capture -E 'binary(decode_fuzz)' "$@"; then
echo "" >&2
echo "a case in seeds $base..$(( base + batch )) broke the decoder." >&2
echo "reproduce it with the gate-sized run:" >&2
echo " HYPERION_FUZZ_SEED_BASE=$base HYPERION_FUZZ_SEEDS=$batch HYPERION_FUZZ_CASES=$HYPERION_FUZZ_CASES nix run .#test -- -p hyperion-minecraft-proto" >&2
exit 1
fi
base=$(( base + batch ))
done
'';
};
# Only tests whose name contains "miri" run under it; the rest are
# far too slow to interpret.
miri = {
deps = [ pkgs.cargo-nextest ];
toolchain = rustWithMiri;
text = ''
export MIRIFLAGS='-Zmiri-tree-borrows -Zmiri-ignore-leaks'
cargo miri nextest run miri "$@"
'';
};
deny = {
deps = [ pkgs.cargo-deny ];
text = ''cargo deny check "$@"'';
};
unused-deps = {
deps = [ pkgs.cargo-machete ];
text = ''cargo machete'';
};
doc.text = ''cargo doc --workspace --no-deps --all-features "$@"'';
coverage = {
deps = [ pkgs.cargo-llvm-cov ];
toolchain = rustWithCoverage;
text = ''
cargo llvm-cov --all-features --workspace --branch \
--lcov --output-path lcov.info "$@"
'';
};
};
# The three cheap checks run together and every one of them reports
# before the run fails, so a single push can fix all of them.
ci = mkScript "ci" {
text = ''
pids=()
"${lib.getExe checkScripts.fmt}" --check & pids+=("$!")
"${lib.getExe checkScripts.unused-deps}" & pids+=("$!")
"${lib.getExe checkScripts.deny}" & pids+=("$!")
status=0
for pid in "''${pids[@]}"; do
wait "$pid" || status=1
done
[ "$status" -eq 0 ]
"${lib.getExe checkScripts.lint}"
"${lib.getExe checkScripts.test}"
"${lib.getExe checkScripts.doc}"
'';
};
certsDir = ".hyperion-dev-certs";
# Defaults, not constants: HYPERION_PLAYER_PORT and
# HYPERION_SERVER_PORT override them, and process-compose's own API
# port moves with them. Two checkouts on one machine otherwise fight
# over all three, and the loser dies on "address already in use".
gameServerPort = 35565;
proxyPort = 25565;
# How far each end to end gate's default ports sit above those two.
#
# One attribute set rather than a number written into each gate's
# script, because two gates claiming one offset is invisible where the
# numbers are apart: `completions-e2e` and `smash-selector-e2e` both
# said 4000 for weeks (ENG-10834), and on darwin, where a build shares
# the host's loopback, the loser of that race fails with "address
# already in use" from a gate it has nothing to do with. Collected
# here, `e2ePortsDistinct` below can say so at eval time.
e2eOffsets = {
e2e = 1000;
smash-e2e = 2000;
smash-map-e2e = 3000;
smash-selector-e2e = 4000;
smash-identity-e2e = 5000;
completions-e2e = 6000;
smash-hotbar-e2e = 7000;
smash-hud-e2e = 8000;
smash-skin-e2e = 8500;
smash-bow-e2e = 8700;
bedwars-bow-e2e = 9000;
# Not 10000: gameServerPort - proxyPort == 10000, so an offset of
# 10000 aliases this gate's player port onto the base game-server
# port (35565), which a running dev server or `nix run .#run` holds.
# Kept under 10000 so every player port stays below that base, the
# invariant the offsets 1000..9000 already rely on. See ENG-10933.
oob-move-e2e = 9500;
};
# The accounts `smash-hud-e2e` runs its `Admin` commands as.
#
# `/serverload` is `Admin` and nothing lets a client give itself a
# group, so the three clients that need it are named to the server as
# configuration before it starts, exactly as an operator would name
# their own administrators (`hyperion_permission::seed`). The gate
# used to promote itself with `/perms set`, which worked only while
# that command was gated at `Normal`: ENG-10871.
#
# The ids and the configuration naming them come off one list,
# because a client logging in under an id nobody configured is not an
# administrator and nothing says so: the failure surfaces much later
# as `/serverload` doing nothing.
hudAdmins =
let
uuids = [
"0be9a1d4-5c00-4e6a-9d21-6a5a1e0000a1"
"0be9a1d4-5c00-4e6a-9d21-6a5a1e0000a2"
"0be9a1d4-5c00-4e6a-9d21-6a5a1e0000a3"
];
in
{
env.HYPERION_PERMISSIONS = lib.concatMapStringsSep "," (uuid: "${uuid}=Admin") uuids;
clientArgs = lib.concatMap (uuid: [
"--admin-uuid"
uuid
]) uuids;
};
# The lobby `smash-e2e` and `smash-selector-e2e` run against, which
# is deliberately not the one the product ships.
#
# The gate's ability sweep changes kits, and a committed match
# refuses to, so the sweep needs a roster the lobby will not start
# on. That roster also needs at least two players in it, because
# `hurts_target` and `heals_caster` are claims about a second body.
# Production runs 2/4 so two people can start a game, and under 2/4
# no roster is both things at once. So the gate states the lobby it
# needs rather than inferring one, and `smash-match.py` checks it got
# it: the run fails if the lobby leaves the hub mid-sweep. Before
# this, the harness had `min_players - 1` written into it and the
# numbers moved out from under it (#1019).
#
# Both thresholds and not only the minimum: `full_players` is what
# decides the three-quarters band, which is the one that actually
# fired. At 2/4 three players satisfy `3 * 4 >= 4 * 3` and the sweep
# died 0.6 seconds in. These are the pre-#1019 numbers, under which
# three players start nothing even by the old band order, so this
# gate does not depend on the `countdown_for` fix that shipped
# alongside it.
#
# `smash-selector-e2e` needs the same thing for the same reason: its
# hub checks run on three clients, which #1019 also put above the
# threshold, and its last check fills the lobby on purpose and so
# needs to know what full is.
smashGateLobby = {
sweepClients = 3;
env = {
SMASH_MIN_PLAYERS = 4;
SMASH_FULL_PLAYERS = 8;
};
};
# The roster that fills the gate's lobby, read off the threshold
# rather than written twice.
smashGateFullClients = toString smashGateLobby.env.SMASH_FULL_PLAYERS;
# `env` as shell, for the gates that are scripts rather than checks.
exportsFor =
env:
lib.concatStringsSep "\n" (
lib.mapAttrsToList (
name: value: "export ${name}=${lib.escapeShellArg (toString value)}"
) env
);
# Two gates on one offset, as a build failure rather than as a race.
#
# An eval-time check and not a runtime one: the failure it catches is a
# number, it costs nothing to look at, and the alternative is finding
# out from whichever unlucky gate lost the port. The names are reported
# rather than only the count, because "two gates collide" is not
# actionable and "these two gates collide" is.
e2ePortsDistinct =
let
offsets = lib.attrValues e2eOffsets;
duplicated = lib.filter (
offset: lib.length (lib.filter (other: other == offset) offsets) > 1
) offsets;
colliding = lib.filter (name: lib.elem e2eOffsets.${name} duplicated) (
lib.attrNames e2eOffsets
);
in
pkgs.runCommand "hyperion-e2e-ports-distinct" { } (
if duplicated == [ ] then
''
echo "ok: ${toString (lib.length offsets)} end to end gates, ${
toString (lib.length offsets)
} distinct port offsets"
touch "$out"
''
else
''
echo "FAIL: these gates claim the same port offset: ${
lib.concatStringsSep ", " colliding
}" >&2
echo "Every gate in e2eOffsets needs its own number, or two of" >&2
echo "them running at once fight over one port and the loser" >&2
echo "fails with address already in use." >&2
exit 1
''
);
# `hyperion`'s `test-util` feature stays a test-only feature.
#
# It exists so `smash`'s adapter tests can build a readable `Compose`
# (ENG-11475). Off by default and enabled by `smash` under
# `[dev-dependencies]`, which keeps it out of every normal build --
# but nothing about a cargo feature *enforces* that, and one careless
# `features = [ "test-util" ]` in a real `[dependencies]` entry makes
# it load-bearing in production, after which removing it is a
# breaking change. A convention nobody checks is a convention that
# has already been broken somewhere.
#
# Read off the raw manifests rather than `cargo metadata`, so this
# answers from the source of truth and needs no build to evaluate.
testUtilIsDevOnly =
let
members = (lib.importTOML ./Cargo.toml).workspace.members;
# Everything a normal `cargo build` would consult. `dev-dependencies`
# is deliberately absent: that is the one table allowed to ask.
shippingTables = [
"dependencies"
"build-dependencies"
];
manifestOf = member: lib.importTOML (./. + "/${member}/Cargo.toml");
# `[target.'cfg(..)'.dependencies]` ships too, so it is folded in
# rather than trusted to be empty.
# Flattened *before* the null filter, not after: the target branch
# produces a list per target, so filtering first leaves nulls
# nested inside and hands `mapAttrsToList` a null.
tablesOf =
manifest:
lib.filter (table: table != null) (
lib.flatten (
map (name: manifest.${name} or null) shippingTables
++ lib.mapAttrsToList (
_: target: map (name: target.${name} or null) shippingTables
) (manifest.target or { })
)
);
# `hyperion = { workspace = true, features = [..] }` is a set;
# `hyperion = "1.0"` is a string and cannot ask for a feature.
asksFor = entry: lib.isAttrs entry && lib.elem "test-util" (entry.features or [ ]);
offendersIn =
member:
let
named = lib.flatten (
map (table: lib.mapAttrsToList (name: entry: { inherit name entry; }) table) (
tablesOf (manifestOf member)
)
);
in
map (found: "${member} -> ${found.name}") (lib.filter (found: asksFor found.entry) named);
offenders = lib.flatten (map offendersIn members);
# The other half of the guarantee, and the half a manifest scan
# cannot see. Under resolver 1 a dev-dependency's features are
# unified into the normal build too, so `smash`'s
# `[dev-dependencies]` entry would put `test-util` in the server
# binary with every manifest above still reading correctly --
# this check green, the thing it protects broken. Verified as
# well as asserted: `cargo tree -p smash -e features
# --no-dev-dependencies` mentions test-util zero times, and with
# dev-dependencies once.
resolver = (lib.importTOML ./Cargo.toml).workspace.resolver or "1";
resolverIsFine = resolver == "2" || resolver == "3";
in
pkgs.runCommand "hyperion-test-util-is-dev-only" { } (
if !resolverIsFine then
''
echo "FAIL: workspace.resolver is ${resolver}." >&2
echo "Resolver 1 unifies dev-dependency features into the normal" >&2
echo "build, so smash's test-only hyperion feature would land in" >&2
echo "the server binary and the manifest scan below would still" >&2
echo "pass. Keep it at 2 or later." >&2
exit 1
''
else if offenders == [ ] then
''
echo "ok: ${
toString (lib.length members)
} workspace members, no shipping dependency enables test-util, resolver ${resolver}"
touch "$out"
''
else
''
echo "FAIL: test-util is enabled outside [dev-dependencies]:" >&2
${lib.concatMapStringsSep "\n" (o: ''echo " ${o}" >&2'') offenders}
echo "" >&2
echo "That feature exists for tests and is off by default. Enabling" >&2
echo "it from a shipping table puts test-only helpers in the server" >&2
echo "binary and makes removing them a breaking change." >&2
exit 1
''
);
# Every directory under events/ is a game server crate, so the set of
# events is read from the tree rather than listed here. A new event
# directory becomes a `nix run .#<event>` app with no flake edit.
events = lib.attrNames (
lib.filterAttrs (_: type: type == "directory") (builtins.readDir ./events)
);
# One process-compose definition, parameterized by event name: the
# game server runs that event's crate and nothing selects it at run
# time, so `nix run .#smash` and `nix run .#bedwars` are the same
# stack with the event fixed rather than one generic stack behind an
# environment variable.
#
# Generated rather than committed as YAML: the ports and cert paths
# then have one source of truth shared with the standalone apps above.
# Commands are single-line: a backslash continuation is literal in a
# Nix indented string, survives into the YAML, and reaches the shell
# as a stray argument rather than a line join.
mkProcessComposeConfig = event: (pkgs.formats.yaml { }).generate "process-compose-${event}.yaml" {
version = "0.5";
processes = {
game-server = {
command = "cargo run --profile \"$\{HYPERION_PROFILE:-dev}\" -p ${event} -- --ip 0.0.0.0 --port \"$\{HYPERION_SERVER_PORT:-${toString gameServerPort}}\" --root-ca-cert ${certsDir}/root_ca.crt --cert ${certsDir}/server.crt --private-key ${certsDir}/server_private_key.pem";
availability.restart = "on_failure";
};
proxy = {
command = "ulimit -Sn ${fileDescriptors}; exec cargo run --profile \"$\{HYPERION_PROFILE:-dev}\" --bin hyperion-proxy -- --server 127.0.0.1:\"$\{HYPERION_SERVER_PORT:-${toString gameServerPort}}\" --root-ca-cert ${certsDir}/root_ca.crt --cert ${certsDir}/proxy.crt --private-key ${certsDir}/proxy_private_key.pem 0.0.0.0:\"$\{HYPERION_PLAYER_PORT:-${toString proxyPort}}\"";
# Started, not healthy: a TCP readiness probe would connect and
# immediately disconnect every few seconds, and the game server
# logs an error for each half-open connection. The proxy already
# retries until the game server answers.
depends_on.game-server.condition = "process_started";
availability.restart = "on_failure";
};
};
};
# Each event gets a `nix run .#<event>` app that boots that same stack
# with the event fixed: certificates first if missing, then the game
# server and proxy under process-compose. One generator over the
# events list rather than a copy per event, so a new event directory
# gets a run app for free and there is nothing to keep in sync.
mkDevStack = event: {
deps = [ pkgs.process-compose pkgs.git ];
text = ''
root="$(git rev-parse --show-toplevel)"
certs="$root/${certsDir}"
if [ ! -f "$certs/root_ca.crt" ]; then
echo "no dev certificates yet; generating them" >&2
"${lib.getExe runners.certs}"
fi
cd "$root"
# process-compose's own API port has to move with the game
# ports, or a second checkout dies on 8080 before either process
# starts.
api_port="''${HYPERION_PC_PORT:-$(( 8080 + ''${HYPERION_PLAYER_PORT:-${toString proxyPort}} - ${toString proxyPort} ))}"
echo "event: ${event} | players: 0.0.0.0:''${HYPERION_PLAYER_PORT:-${toString proxyPort}} | game server: 127.0.0.1:''${HYPERION_SERVER_PORT:-${toString gameServerPort}}"
exec process-compose --config ${mkProcessComposeConfig event} --port "$api_port" "$@"
'';
};
eventDevStacks = lib.genAttrs events mkDevStack;
runners = lib.mapAttrs mkScript (eventDevStacks // {
# Builds four successive versions of the demo game module and drives
# one running world through all of them. Being a nix app is what
# makes the single-compiler precondition structural rather than a
# convention: `repr(Rust)` has no stable ABI, so a host and a module
# built by different rustc versions disagree about the layout of
# every type they share.
hot-reload-demo = {
deps = [ pkgs.cmake pkgs.pkg-config ];
text = ''exec ./crates/hyperion-hot-reload/demo.sh "$@"'';
};
# The game server and the proxy authenticate to each other with
# mTLS, so a fresh clone cannot run until a CA and two leaf certs
# exist. That is the only thing between `git clone` and a running
# server, so it is a command rather than a page of README.
certs = {
deps = [ pkgs.openssl pkgs.git ];
text = ''
root="$(git rev-parse --show-toplevel)"
dir="$root/${certsDir}"
if [ -f "$dir/root_ca.crt" ] && [ "''${1:-}" != "--force" ]; then
echo "dev certificates already present in ${certsDir}"
echo "regenerate with: nix run .#certs -- --force"
exit 0
fi
mkdir -p "$dir"
cd "$dir"
openssl req -new -nodes -newkey rsa:2048 -keyout root_ca.pem \
-x509 -out root_ca.crt -days 365 -subj '/CN=hyperion-dev-ca'
for who in server proxy; do
openssl req -nodes -newkey rsa:2048 \
-keyout "''${who}_private_key.pem" -out "$who.csr" \
-subj "/CN=hyperion-dev-$who"
# The SAN must cover the address the peer dials or the
# handshake fails with "certificate not valid for name".
openssl x509 -req -in "$who.csr" -CA root_ca.crt -CAkey root_ca.pem \
-CAcreateserial -out "$who.crt" -days 365 -sha256 \
-extfile <(printf 'subjectAltName=DNS:localhost,IP:127.0.0.1')
rm -f "$who.csr"
done
rm -f root_ca.srl
echo "wrote throwaway dev certificates to ${certsDir}"
echo "local development only -- never deploy these"
'';
};
proxy = {
deps = [ pkgs.git ];
text = ''
certs="$(git rev-parse --show-toplevel)/${certsDir}"
ulimit -Sn ${fileDescriptors}
exec cargo run --profile release-full --bin hyperion-proxy -- \
--server 127.0.0.1:35565 \
--root-ca-cert "$certs/root_ca.crt" \
--cert "$certs/proxy.crt" \
--private-key "$certs/proxy_private_key.pem" \
0.0.0.0:25565
'';
};
bots.text = ''
ulimit -Sn ${fileDescriptors}
exec cargo run --release -p rust-mc-bot -- \
"''${1:-127.0.0.1:25565}" "''${2:-100}"
'';
# Joins a running server with the real Minecraft client and says
# whether a player reached the world.
#
# Everything else in this file reads the wire; this reads the game.
# The distance between the two is not theoretical: the scripted
# client passed for a week while every real client was dropped
# during registry loading, because the scripted one does not load
# registries. It cannot run in CI, since it needs a launcher, an
# account and a GPU, so it is a command a person runs before saying
# an address works.
real-client = {
deps = [ pkgs.bash ];
text = ''exec ./tools/real-client-join.sh "$@"'';
};
# Boots the whole stack, drives a scripted 26.2 client through it,
# and exits with that client's verdict.
#
# This is the only check that reads the wire the way a player does.
# Every other gate reads the source: `nix run .#test` proves a
# packet encodes to the bytes a test says it should, and stays green
# while the server sends that packet under a number from a different
# protocol version. A client is what notices.
#
# Ports come from the environment and default off the dev ports, so
# a run does not fight a `nix run .#bedwars` stack open in another terminal.
e2e = {
deps = [
pkgs.git
e2e.driver
];
text = ''
root="$(git rev-parse --show-toplevel)"
cd "$root"
# The event and the client that drives it move together, so
# `smash-e2e` sets both and this stays the bedwars gate. Two
# apps rather than one with a flag, because the useful thing to
# type is one word.
event="''${HYPERION_EVENT:-bedwars}"
profile="''${HYPERION_PROFILE:-dev}"
# cargo, not the store: what a person debugging wants is the
# code in their working tree, rebuilt incrementally. The check
# of the same name hands the same driver two store paths, and
# that is the only difference between them.
# `HYPERION_E2E_GAME_SERVER_ARGS` is the `nix run` twin of
# `mkCheck`'s `gameServerArgs`: extra flags for the server,
# for trying a gate's configuration by hand before writing it
# down.
export HYPERION_E2E_GAME_SERVER="cargo run --profile $profile -p $event -- ''${HYPERION_E2E_GAME_SERVER_ARGS:-}"
export HYPERION_E2E_PROXY="cargo run --profile $profile --bin hyperion-proxy --"
export HYPERION_E2E_CLIENT="''${HYPERION_E2E_CLIENT:-tools/client-26.2.py --name e2e}"
# Certificates from the store rather than `nix run .#certs`, so
# a fresh clone runs this without a setup step first.
export HYPERION_E2E_CERTS="${e2e.certs}"
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.e2e)}}"
exec hyperion-e2e-driver "$@"
'';
};
# The same gate on smash. bedwars is joinable with one client, so
# `e2e` drives one; a smash match needs `min_players` of them at
# once, which is why the client is a different program rather than
# the same one with a flag.
#
# Ports default off the `e2e` ones rather than sharing them, so the
# two gates can run side by side.
smash-e2e = {
deps = [ pkgs.git ];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT="tools/smash-match.py --sweep-clients ${toString smashGateLobby.sweepClients}"
${exportsFor smashGateLobby.env}
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.smash-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.smash-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};
# The same gate again, driving a client that clicks the hub's kit
# podiums instead of playing the match.
#
# Separate from `smash-e2e` because it answers the question that
# comes before it. `smash-e2e` needs kits to already be picked and
# picks them by typing `/kit`; this one asks whether a player who
# never types anything can pick a mob by right-clicking it, and
# whether the game says so when the mob is somebody else's. Its
# ports default off the others again so every gate can run at once.
smash-selector-e2e = {
deps = [ pkgs.git ];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT="tools/smash-selector.py --full-clients ${smashGateFullClients}"
${exportsFor smashGateLobby.env}
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.smash-selector-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.smash-selector-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};
# The same gate again, driving a client that reads blocks rather
# than positions.
#
# Separate from `smash-e2e` rather than folded into it because the
# two answer different questions and fail for different reasons.
# `smash-e2e` asks whether a match happens; this asks whether the
# world the match happens in is the one the map files describe, and
# whether the kill plane each of them declares is the height the
# game actually kills at. Its ports default off `smash-e2e`'s again
# so all three gates can run at once.
smash-map-e2e = {
deps = [
pkgs.process-compose
pkgs.git
pkgs.python3
];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT=tools/smash-map-check.py
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.smash-map-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.smash-map-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};
# The same gate again, driving a client that types rather than
# walks.
#
# `smash-e2e` and `smash-map-e2e` both prove things about a world.
# This one never leaves the hub: it reads the command graph the
# server sends on join and then presses tab, which is the whole of
# the completion path and touches nothing else.
#
# +6000 and not +4000, which is what it claimed until ENG-10834:
# `smash-selector-e2e` claims that offset too, so running the two
# side by side had one of them lose the port to the other. On darwin
# a build shares the host's loopback, so the loser fails with
# "address already in use" from a gate it has nothing to do with.
# Every offset in this file is now distinct, which the check below
# is what says.
completions-e2e = {
deps = [ pkgs.git ];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT=tools/completions-check.py
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.completions-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.completions-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};
# The same gate again, driving a client that asks who a player is
# rather than what they can do: two connections under one IGN,
# whether a dig is refused, and whether the profile the other
# player receives carries the kit's mob. Ports default off
# `completions-e2e`'s so all five gates can run side by side.
smash-identity-e2e = {
deps = [
pkgs.git
pkgs.python3
];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT=tools/identity-check.py
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.smash-identity-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.smash-identity-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};
# What every other player sees of a player who put on a kit: the
# committed skin, its Mojang signature, and the skin-overlay mask
# with the hat bit set. Separate from `smash-identity-e2e` because
# it reads the entity metadata as well as the tab list, and it is
# the regression gate for the skin and hat bugs.
smash-skin-e2e = {
deps = [
pkgs.git
pkgs.python3
];
text = ''
export HYPERION_EVENT=smash
export HYPERION_E2E_CLIENT=tools/skin-check.py
export HYPERION_PLAYER_PORT="''${HYPERION_PLAYER_PORT:-${toString (proxyPort + e2eOffsets.smash-skin-e2e)}}"
export HYPERION_SERVER_PORT="''${HYPERION_SERVER_PORT:-${toString (gameServerPort + e2eOffsets.smash-skin-e2e)}}"
exec "${lib.getExe runners.e2e}" "$@"
'';
};