on decrease-android-validity help sign in
obelisk/default.nix
358 lines 15 kB history raw
1{ system ? builtins.currentSystem
2, profiling ? false
3, iosSdkVersion ? "10.2"
4, config ? {}
5}:
6let
7 cleanSource = builtins.filterSource (name: _: let baseName = builtins.baseNameOf name; in !(
8 builtins.match "^\\.ghc\\.environment.*" baseName != null ||
9 baseName == "cabal.project.local"
10 ));
12 commandRuntimeDeps = pkgs: with pkgs; [
13 coreutils
14 git
15 nix-prefetch-git
16 openssh
17 ];
19 getReflexPlatform = sys: import ./dep/reflex-platform {
20 inherit iosSdkVersion config;
21 system = sys;
22 enableLibraryProfiling = profiling;
24 nixpkgsOverlays = [
25 (self: super: {
26 obeliskExecutableConfig = import ./lib/executable-config { nixpkgs = pkgs; filterGitSource = cleanSource; };
27 })
28 ];
30 haskellOverlays = [
32 # Fix misc upstream packages
33 (self: super: let
34 pkgs = self.callPackage ({ pkgs }: pkgs) {};
35 in {
36 hnix = pkgs.haskell.lib.dontCheck (self.callCabal2nix "hnix" (pkgs.fetchFromGitHub {
37 owner = "haskell-nix";
38 repo = "hnix";
39 rev = "42afdc21da5d9e076eab57eaa42bfdde938192b8";
40 sha256 = "0psw384dx9bw2dp93xrzw8rd9amvcwgzn64jzzwby7sfspj6k349";
41 }) {});
42 })
44 pkgs.obeliskExecutableConfig.haskellOverlay
46 # Add obelisk packages
47 (self: super: let
48 pkgs = self.callPackage ({ pkgs }: pkgs) {};
49 in {
50 obelisk-executable-config-inject = pkgs.obeliskExecutableConfig.platforms.web.inject self;
52 obelisk-asset-manifest = self.callCabal2nix "obelisk-asset-manifest" (hackGet ./lib/asset + "/manifest") {};
53 obelisk-asset-serve-snap = self.callCabal2nix "obelisk-asset-serve-snap" (hackGet ./lib/asset + "/serve-snap") {};
54 obelisk-backend = self.callCabal2nix "obelisk-backend" (cleanSource ./lib/backend) {};
55 obelisk-cliapp = self.callCabal2nix "obelisk-cliapp" (cleanSource ./lib/cliapp) {};
56 obelisk-command = self.callCabal2nix "obelisk-command" (cleanSource ./lib/command) {};
57 obelisk-frontend = self.callCabal2nix "obelisk-frontend" (cleanSource ./lib/frontend) {};
58 obelisk-run = self.callCabal2nix "obelisk-run" (cleanSource ./lib/run) {};
59 obelisk-route = self.callCabal2nix "obelisk-route" (cleanSource ./lib/route) {};
60 obelisk-selftest = self.callCabal2nix "obelisk-selftest" (cleanSource ./lib/selftest) {};
61 obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (cleanSource ./lib/snap-extras) {};
62 tabulation = self.callCabal2nix "tabulation" (cleanSource ./lib/tabulation) {};
63 })
65 (self: super: let
66 pkgs = self.callPackage ({ pkgs }: pkgs) {};
67 haskellLib = pkgs.haskell.lib;
68 #TODO: Upstream
69 # Modify a Haskell package to add completion scripts for the given
70 # executable produced by it. These completion scripts will be picked up
71 # automatically if the resulting derivation is installed, e.g. by
72 # `nix-env -i`.
73 addOptparseApplicativeCompletionScripts = exeName: pkg: haskellLib.overrideCabal pkg (drv: {
74 postInstall = (drv.postInstall or "") + ''
75 BASH_COMP_DIR="$out/share/bash-completion/completions"
76 mkdir -p "$BASH_COMP_DIR"
77 "$out/bin/${exeName}" --bash-completion-script "$out/bin/${exeName}" >"$BASH_COMP_DIR/ob"
79 ZSH_COMP_DIR="$out/share/zsh/vendor-completions"
80 mkdir -p "$ZSH_COMP_DIR"
81 "$out/bin/${exeName}" --zsh-completion-script "$out/bin/${exeName}" >"$ZSH_COMP_DIR/_ob"
83 FISH_COMP_DIR="$out/share/fish/vendor_completions.d"
84 mkdir -p "$FISH_COMP_DIR"
85 "$out/bin/${exeName}" --fish-completion-script "$out/bin/${exeName}" >"$FISH_COMP_DIR/ob.fish"
86 '';
87 });
88 in {
89 # Dynamic linking with split objects dramatically increases startup time (about
90 # 0.5 seconds on a decent machine with SSD), so we do `justStaticExecutables`.
91 obelisk-command = haskellLib.overrideCabal
92 (addOptparseApplicativeCompletionScripts "ob"
93 (haskellLib.justStaticExecutables super.obelisk-command))
94 (drv: {
95 buildTools = (drv.buildTools or []) ++ [ pkgs.buildPackages.makeWrapper ];
96 postFixup = ''
97 ${drv.postFixup or ""}
98 # Make `ob` reference its runtime dependencies.
99 wrapProgram "$out"/bin/ob --prefix PATH : ${pkgs.lib.makeBinPath (commandRuntimeDeps pkgs)}
100 '';
101 });
102 obelisk-selftest = haskellLib.justStaticExecutables super.obelisk-selftest;
103 })
105 ];
106 };
108 reflex-platform = getReflexPlatform system;
109 inherit (reflex-platform) hackGet nixpkgs;
110 pkgs = nixpkgs;
112 # The haskell environment used to build Obelisk itself, e.g. the 'ob' command
113 ghcObelisk = reflex-platform.ghc;
115 # Development environments for obelisk packages.
116 ghcObeliskEnvs = pkgs.lib.mapAttrs (n: v: reflex-platform.workOn ghcObelisk v) ghcObelisk;
118 inherit (import ./lib/asset/assets.nix { inherit nixpkgs; }) mkAssets;
120 haskellLib = pkgs.haskell.lib;
122in rec {
123 inherit reflex-platform;
124 inherit (reflex-platform) nixpkgs pinBuildInputs;
125 inherit (nixpkgs) lib;
126 pathGit = ./.; # Used in CI by the migration graph hash algorithm to correctly ignore files.
127 path = reflex-platform.filterGit ./.;
128 obelisk = ghcObelisk;
129 obeliskEnvs = ghcObeliskEnvs;
130 command = ghcObelisk.obelisk-command;
131 shell = pinBuildInputs "obelisk-shell" ([command] ++ commandRuntimeDeps pkgs) [];
133 selftest = pkgs.writeScript "selftest" ''
134 #!/usr/bin/env bash
135 set -euo pipefail
137 PATH="${command}/bin:$PATH"
138 export OBELISK_IMPL="${hackGet ./.}"
139 "${ghcObelisk.obelisk-selftest}/bin/obelisk-selftest" +RTS -N -RTS "$@"
140 '';
141 #TODO: Why can't I build ./skeleton directly as a derivation? `nix-build -E ./.` doesn't work
142 skeleton = pkgs.runCommand "skeleton" {
143 dir = builtins.filterSource (path: type: builtins.trace path (baseNameOf path != ".obelisk")) ./skeleton;
144 } ''
145 ln -s "$dir" "$out"
146 '';
147 nullIfAbsent = p: if lib.pathExists p then p else null;
148 #TODO: Avoid copying files within the nix store. Right now, obelisk-asset-manifest-generate copies files into a big blob so that the android/ios static assets can be imported from there; instead, we should get everything lined up right before turning it into an APK, so that copies, if necessary, only exist temporarily.
149 processAssets = { src, packageName ? "obelisk-generated-static", moduleName ? "Obelisk.Generated.Static" }: pkgs.runCommand "asset-manifest" {
150 inherit src;
151 outputs = [ "out" "haskellManifest" "symlinked" ];
152 nativeBuildInputs = [ ghcObelisk.obelisk-asset-manifest ];
153 } ''
154 set -euo pipefail
155 touch "$out"
156 mkdir -p "$symlinked"
157 obelisk-asset-manifest-generate "$src" "$haskellManifest" ${packageName} ${moduleName} "$symlinked"
158 '';
160 compressedJs = frontend: optimizationLevel: pkgs.runCommand "compressedJs" { buildInputs = [ pkgs.closurecompiler ]; } ''
161 mkdir $out
162 cd $out
163 ln -s "${haskellLib.justStaticExecutables frontend}/bin/frontend.jsexe/all.js" all.unminified.js
164 closure-compiler --externs "${reflex-platform.ghcjsExternsJs}" -O ${optimizationLevel} --jscomp_warning=checkVars --create_source_map="all.js.map" --source_map_format=V3 --js_output_file="all.js" all.unminified.js
165 echo "//# sourceMappingURL=all.js.map" >> all.js
166 '';
168 serverModules = {
169 mkBaseEc2 = { hostName, routeHost, enableHttps, adminEmail, ... }: {...}: {
170 imports = [
171 (pkgs.path + /nixos/modules/virtualisation/amazon-image.nix)
172 ];
173 networking = {
174 inherit hostName;
175 firewall.allowedTCPPorts = if enableHttps then [ 80 443 ] else [ 80 ];
176 };
177 security.acme.certs = if enableHttps then {
178 "${routeHost}".email = adminEmail;
179 } else {};
180 ec2.hvm = true;
181 };
183 mkObeliskApp =
184 { exe
185 , routeHost
186 , enableHttps
187 , name ? "backend"
188 , user ? name
189 , group ? user
190 , baseUrl ? "/"
191 , internalPort ? 8000
192 , backendArgs ? "--port=${toString internalPort}"
193 , ...
194 }: {...}: {
195 services.nginx = {
196 enable = true;
197 virtualHosts."${routeHost}" = {
198 enableACME = enableHttps;
199 forceSSL = enableHttps;
200 locations.${baseUrl} = {
201 proxyPass = "http://127.0.0.1:" + toString internalPort;
202 proxyWebsockets = true;
203 };
204 };
205 };
206 systemd.services.${name} = {
207 wantedBy = [ "multi-user.target" ];
208 after = [ "network.target" ];
209 restartIfChanged = true;
210 path = [ pkgs.gnutar ];
211 script = ''
212 ln -sft . '${exe}'/*
213 mkdir -p log
214 exec ./backend ${backendArgs} </dev/null
215 '';
216 serviceConfig = {
217 User = user;
218 KillMode = "process";
219 WorkingDirectory = "~";
220 Restart = "always";
221 RestartSec = 5;
222 };
223 };
224 users = {
225 users.${user} = {
226 description = "${user} service";
227 home = "/var/lib/${user}";
228 createHome = true;
229 isSystemUser = true;
230 group = group;
231 };
232 groups.${group} = {};
233 };
234 };
235 };
237 serverExe = backend: frontend: assets: optimizationLevel: version:
238 pkgs.runCommand "serverExe" {} ''
239 mkdir $out
240 set -eux
241 ln -s "${haskellLib.justStaticExecutables backend}"/bin/* $out/
242 ln -s "${mkAssets assets}" $out/static.assets
243 ln -s ${mkAssets (compressedJs frontend optimizationLevel)} $out/frontend.jsexe.assets
244 echo ${version} > $out/version
245 '';
247 server = { exe, hostName, adminEmail, routeHost, enableHttps, version }@args:
248 let
249 nixos = import (pkgs.path + /nixos);
250 in nixos {
251 system = "x86_64-linux";
252 configuration = {
253 imports = [
254 (serverModules.mkBaseEc2 args)
255 (serverModules.mkObeliskApp args)
256 ];
257 };
258 };
261 # An Obelisk project is a reflex-platform project with a predefined layout and role for each component
262 project = base: projectDefinition:
263 let projectOut = sys: (getReflexPlatform sys).project (args@{ nixpkgs, ... }:
264 let mkProject = { android ? null #TODO: Better error when missing
265 , ios ? null #TODO: Better error when missing
266 , packages ? {}
267 , overrides ? _: _: {}
268 , staticFiles ? base + /static
269 , tools ? _: []
270 , shellToolOverrides ? _: _: {}
271 , withHoogle ? false # Setting this to `true` makes shell reloading far slower
272 , __closureCompilerOptimizationLevel ? "ADVANCED"
273 }:
274 let frontendName = "frontend";
275 backendName = "backend";
276 commonName = "common";
277 staticName = "obelisk-generated-static";
278 staticFilesImpure = if lib.isDerivation staticFiles then staticFiles else toString staticFiles;
279 processedStatic = processAssets { src = staticFiles; };
280 # The packages whose names and roles are defined by this package
281 predefinedPackages = lib.filterAttrs (_: x: x != null) {
282 ${frontendName} = nullIfAbsent (base + "/frontend");
283 ${commonName} = nullIfAbsent (base + "/common");
284 ${backendName} = nullIfAbsent (base + "/backend");
285 };
286 combinedPackages = predefinedPackages // packages;
287 projectOverrides = self: super: {
288 ${staticName} = haskellLib.dontHaddock (self.callCabal2nix staticName processedStatic.haskellManifest {});
289 ${backendName} = haskellLib.addBuildDepend super.${backendName} self.obelisk-run;
290 };
291 totalOverrides = lib.composeExtensions projectOverrides overrides;
292 inherit (lib.strings) hasPrefix;
293 privateConfigDirs = ["config/backend"];
294 injectableConfig = builtins.filterSource (path: _:
295 !(lib.lists.any (x: hasPrefix (toString base + "/" + toString x) (toString path)) privateConfigDirs)
296 );
297 __androidWithConfig = configPath: {
298 ${if android == null then null else frontendName} = {
299 executableName = "frontend";
300 ${if builtins.pathExists staticFiles then "assets" else null} =
301 nixpkgs.obeliskExecutableConfig.platforms.android.inject
302 (injectableConfig configPath)
303 processedStatic.symlinked;
304 } // android;
305 };
306 __iosWithConfig = configPath: {
307 ${if ios == null then null else frontendName} = {
308 executableName = "frontend";
309 ${if builtins.pathExists staticFiles then "staticSrc" else null} =
310 nixpkgs.obeliskExecutableConfig.platforms.ios.inject
311 (injectableConfig configPath)
312 processedStatic.symlinked;
313 } // ios;
314 };
315 in {
316 inherit shellToolOverrides tools withHoogle;
317 overrides = totalOverrides;
318 packages = combinedPackages;
319 shells = {
320 ${if android == null && ios == null then null else "ghcSavedSplices"} = (lib.filter (x: lib.hasAttr x combinedPackages) [
321 commonName
322 frontendName
323 ]);
324 ghc = (lib.filter (x: lib.hasAttr x combinedPackages) [
325 backendName
326 commonName
327 frontendName
328 ]);
329 ghcjs = lib.filter (x: lib.hasAttr x combinedPackages) [
330 frontendName
331 commonName
332 ];
333 };
334 android = __androidWithConfig (base + "/config");
335 ios = __iosWithConfig (base + "/config");
336 passthru = { inherit android ios packages overrides tools shellToolOverrides withHoogle staticFiles staticFilesImpure __closureCompilerOptimizationLevel processedStatic __iosWithConfig __androidWithConfig; };
337 };
338 in mkProject (projectDefinition args));
339 serverOn = sys: version: serverExe
340 (projectOut sys).ghc.backend
341 (projectOut system).ghcjs.frontend
342 (projectOut sys).passthru.staticFiles
343 (projectOut sys).passthru.__closureCompilerOptimizationLevel
344 version;
345 linuxExe = serverOn "x86_64-linux";
346 dummyVersion = "Version number is only available for deployments";
347 in projectOut system // {
348 linuxExeConfigurable = linuxExe;
349 linuxExe = linuxExe dummyVersion;
350 exe = serverOn system dummyVersion;
351 server = args@{ hostName, adminEmail, routeHost, enableHttps, version }:
352 server (args // { exe = linuxExe version; });
353 obelisk = import (base + "/.obelisk/impl") {};
354 };
355 haskellPackageSets = {
356 inherit (reflex-platform) ghc ghcjs;
357 };