on ae@obeliskenvs-tabulation help sign in
obelisk/default.nix
379 lines 16 kB history raw
1{ system ? builtins.currentSystem
2, profiling ? false
3, iosSdkVersion ? "10.2"
4, config ? {}
5, reflex-platform-func ? import ./dep/reflex-platform
6}:
7let
8 reflex-platform = getReflexPlatform { inherit system; };
9 inherit (reflex-platform) hackGet nixpkgs;
10 pkgs = nixpkgs;
12 inherit (import dep/gitignore.nix { inherit (nixpkgs) lib; }) gitignoreSource;
14 getReflexPlatform = { system, enableLibraryProfiling ? profiling }: reflex-platform-func {
15 inherit iosSdkVersion config system enableLibraryProfiling;
17 nixpkgsOverlays = [
18 (import ./nixpkgs-overlays)
19 ];
21 haskellOverlays = [
22 (import ./haskell-overlays/misc-deps.nix { inherit hackGet; })
23 pkgs.obeliskExecutableConfig.haskellOverlay
24 (import ./haskell-overlays/obelisk.nix)
25 (import ./haskell-overlays/tighten-ob-exes.nix)
26 ];
27 };
29 # The haskell environment used to build Obelisk itself, e.g. the 'ob' command
30 ghcObelisk = reflex-platform.ghc;
32 # Development environments for obelisk packages.
33 ghcObeliskEnvs = pkgs.lib.mapAttrs (n: v: reflex-platform.workOn ghcObelisk v) ghcObelisk;
35 inherit (import ./lib/asset/assets.nix { inherit nixpkgs; }) mkAssets;
37 haskellLib = pkgs.haskell.lib;
39in rec {
40 inherit reflex-platform;
41 inherit (reflex-platform) nixpkgs pinBuildInputs;
42 inherit (nixpkgs) lib;
43 pathGit = ./.; # Used in CI by the migration graph hash algorithm to correctly ignore files.
44 path = reflex-platform.filterGit ./.;
45 obelisk = ghcObelisk;
46 obeliskEnvs = pkgs.lib.filterAttrs (k: _: k == "tabulation" || pkgs.lib.strings.hasPrefix "obelisk-" k) ghcObeliskEnvs; #TODO: use thunkSet https://github.com/reflex-frp/reflex-platform/pull/671
47 command = ghcObelisk.obelisk-command;
48 shell = pinBuildInputs "obelisk-shell" ([command] ++ command.commandRuntimeDeps);
50 selftest = pkgs.writeScript "selftest" ''
51 #!${pkgs.runtimeShell}
52 set -euo pipefail
54 PATH="${command}/bin:$PATH"
55 cd ${./.}
56 "${ghcObelisk.obelisk-selftest}/bin/obelisk-selftest" +RTS -N -RTS "$@"
57 '';
58 skeleton = pkgs.runCommand "skeleton" {
59 dir = builtins.filterSource (path: type: builtins.trace path (baseNameOf path != ".obelisk")) ./skeleton;
60 } ''
61 ln -s "$dir" "$out"
62 '';
63 nullIfAbsent = p: if lib.pathExists p then p else null;
64 #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.
65 processAssets = { src, packageName ? "obelisk-generated-static", moduleName ? "Obelisk.Generated.Static" }: pkgs.runCommand "asset-manifest" {
66 inherit src;
67 outputs = [ "out" "haskellManifest" "symlinked" ];
68 nativeBuildInputs = [ ghcObelisk.obelisk-asset-manifest ];
69 } ''
70 set -euo pipefail
71 touch "$out"
72 mkdir -p "$symlinked"
73 obelisk-asset-manifest-generate "$src" "$haskellManifest" ${packageName} ${moduleName} "$symlinked"
74 '';
76 compressedJs = frontend: optimizationLevel: pkgs.runCommand "compressedJs" {} ''
77 mkdir $out
78 cd $out
79 # TODO profiling + static shouldn't break and need an ad-hoc workaround like that
80 ln -s "${haskellLib.justStaticExecutables frontend}/bin/frontend.jsexe/all.js" all.unminified.js
81 ${if optimizationLevel == null then ''
82 ln -s all.unminified.js all.js
83 '' else ''
84 ${pkgs.closurecompiler}/bin/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
85 echo "//# sourceMappingURL=all.js.map" >> all.js
86 ''}
87 '';
89 serverModules = {
90 mkBaseEc2 = { nixosPkgs, ... }: {...}: {
91 imports = [
92 (nixosPkgs.path + /nixos/modules/virtualisation/amazon-image.nix)
93 ];
94 ec2.hvm = true;
95 };
97 mkDefaultNetworking = { adminEmail, enableHttps, hostName, routeHost, ... }: {...}: {
98 networking = {
99 inherit hostName;
100 firewall.allowedTCPPorts = if enableHttps then [ 80 443 ] else [ 80 ];
101 };
103 # `amazon-image.nix` already sets these but if the user provides their own module then
104 # forgetting these can cause them to lose access to the server!
105 # https://github.com/NixOS/nixpkgs/blob/fab05f17d15e4e125def4fd4e708d205b41d8d74/nixos/modules/virtualisation/amazon-image.nix#L133-L136
106 services.openssh.enable = true;
107 services.openssh.permitRootLogin = "prohibit-password";
109 security.acme.certs = if enableHttps then {
110 "${routeHost}".email = adminEmail;
111 } else {};
113 security.acme.${if enableHttps then "acceptTerms" else null} = true;
114 };
116 mkObeliskApp =
117 { exe
118 , routeHost
119 , enableHttps
120 , name ? "backend"
121 , user ? name
122 , group ? user
123 , baseUrl ? "/"
124 , internalPort ? 8000
125 , backendArgs ? "--port=${toString internalPort}"
126 , ...
127 }: {...}: {
128 services.nginx = {
129 enable = true;
130 virtualHosts."${routeHost}" = {
131 enableACME = enableHttps;
132 forceSSL = enableHttps;
133 locations.${baseUrl} = {
134 proxyPass = "http://127.0.0.1:" + toString internalPort;
135 proxyWebsockets = true;
136 };
137 };
138 };
139 systemd.services.${name} = {
140 wantedBy = [ "multi-user.target" ];
141 after = [ "network.target" ];
142 restartIfChanged = true;
143 path = [ pkgs.gnutar ];
144 script = ''
145 ln -sft . '${exe}'/*
146 mkdir -p log
147 exec ./backend ${backendArgs} </dev/null
148 '';
149 serviceConfig = {
150 User = user;
151 KillMode = "process";
152 WorkingDirectory = "~";
153 Restart = "always";
154 RestartSec = 5;
155 };
156 };
157 users = {
158 users.${user} = {
159 description = "${user} service";
160 home = "/var/lib/${user}";
161 createHome = true;
162 isSystemUser = true;
163 group = group;
164 };
165 groups.${group} = {};
166 };
167 };
168 };
170 inherit mkAssets;
172 serverExe = backend: frontend: assets: optimizationLevel: version:
173 pkgs.runCommand "serverExe" {} ''
174 mkdir $out
175 set -eux
176 ln -s "${if profiling then backend else haskellLib.justStaticExecutables backend}"/bin/* $out/
177 ln -s "${mkAssets assets}" $out/static.assets
178 ln -s ${mkAssets (compressedJs frontend optimizationLevel)} $out/frontend.jsexe.assets
179 echo ${version} > $out/version
180 '';
182 server = { exe, hostName, adminEmail, routeHost, enableHttps, version, module ? serverModules.mkBaseEc2 }@args:
183 let
184 nixos = import (pkgs.path + /nixos);
185 in nixos {
186 system = "x86_64-linux";
187 configuration = {
188 imports = [
189 (module { inherit exe hostName adminEmail routeHost enableHttps version; nixosPkgs = pkgs; })
190 (serverModules.mkDefaultNetworking args)
191 (serverModules.mkObeliskApp args)
192 ./acme.nix # Backport of ACME upgrades from 20.03
193 ];
195 # Backport of ACME upgrades from 20.03
196 disabledModules = [
197 (pkgs.path + /nixos/modules/security/acme.nix)
198 ];
199 nixpkgs.overlays = [
200 (self: super: {
201 lego = (import (builtins.fetchTarball {
202 url = https://github.com/NixOS/nixpkgs-channels/archive/70717a337f7ae4e486ba71a500367cad697e5f09.tar.gz;
203 sha256 = "1sbmqn7yc5iilqnvy9nvhsa9bx6spfq1kndvvis9031723iyymd1";
204 }) {}).lego;
205 })
206 ];
207 };
208 };
210 # An Obelisk project is a reflex-platform project with a predefined layout and role for each component
211 project = base': projectDefinition:
212 let
213 projectOut = { system, enableLibraryProfiling ? profiling }: let reflexPlatformProject = (getReflexPlatform { inherit system enableLibraryProfiling; }).project; in reflexPlatformProject (args@{ nixpkgs, ... }:
214 let
215 inherit (lib.strings) hasPrefix;
216 mkProject =
217 { android ? null #TODO: Better error when missing
218 , ios ? null #TODO: Better error when missing
219 , packages ? {}
220 , overrides ? _: _: {}
221 , staticFiles ? null
222 , tools ? _: []
223 , shellToolOverrides ? _: _: {}
224 , withHoogle ? false # Setting this to `true` makes shell reloading far slower
225 , __closureCompilerOptimizationLevel ? "ADVANCED" # Set this to `null` to skip the closure-compiler step
226 , __withGhcide ? false
227 }:
228 let
229 allConfig = nixpkgs.lib.makeExtensible (self: {
230 base = base';
231 inherit args;
232 userSettings = {
233 inherit android ios packages overrides tools shellToolOverrides withHoogle __closureCompilerOptimizationLevel __withGhcide;
234 staticFiles = if staticFiles == null then self.base + /static else staticFiles;
235 };
236 frontendName = "frontend";
237 backendName = "backend";
238 commonName = "common";
239 staticName = "obelisk-generated-static";
240 staticFilesImpure = let fs = self.userSettings.staticFiles; in if lib.isDerivation fs then fs else toString fs;
241 processedStatic = processAssets { src = self.userSettings.staticFiles; };
242 # The packages whose names and roles are defined by this package
243 predefinedPackages = lib.filterAttrs (_: x: x != null) {
244 ${self.frontendName} = nullIfAbsent (self.base + "/frontend");
245 ${self.commonName} = nullIfAbsent (self.base + "/common");
246 ${self.backendName} = nullIfAbsent (self.base + "/backend");
247 };
248 shellPackages = {};
249 combinedPackages = self.predefinedPackages // self.userSettings.packages // self.shellPackages;
250 projectOverrides = self': super': {
251 ${self.staticName} = haskellLib.dontHaddock (self'.callCabal2nix self.staticName self.processedStatic.haskellManifest {});
252 ${self.backendName} = haskellLib.addBuildDepend super'.${self.backendName} self'.obelisk-run;
253 };
254 totalOverrides = lib.composeExtensions self.projectOverrides self.userSettings.overrides;
255 privateConfigDirs = ["config/backend"];
256 injectableConfig = builtins.filterSource (path: _:
257 !(lib.lists.any (x: hasPrefix (toString self.base + "/" + toString x) (toString path)) self.privateConfigDirs)
258 );
259 __androidWithConfig = configPath: {
260 ${if self.userSettings.android == null then null else self.frontendName} = {
261 executableName = "frontend";
262 ${if builtins.pathExists self.userSettings.staticFiles then "assets" else null} =
263 nixpkgs.obeliskExecutableConfig.platforms.android.inject
264 (self.injectableConfig configPath)
265 self.processedStatic.symlinked;
266 } // self.userSettings.android;
267 };
268 __iosWithConfig = configPath: {
269 ${if self.userSettings.ios == null then null else self.frontendName} = {
270 executableName = "frontend";
271 ${if builtins.pathExists self.userSettings.staticFiles then "staticSrc" else null} =
272 nixpkgs.obeliskExecutableConfig.platforms.ios.inject
273 (self.injectableConfig configPath)
274 self.processedStatic.symlinked;
275 } // self.userSettings.ios;
276 };
278 shells-ghc = builtins.attrNames (self.predefinedPackages // self.shellPackages);
280 shells-ghcjs = [
281 self.frontendName
282 self.commonName
283 ];
285 shells-ghcSavedSplices = [
286 self.commonName
287 self.frontendName
288 ];
290 shellToolOverrides = lib.composeExtensions
291 self.userSettings.shellToolOverrides
292 (if self.userSettings.__withGhcide
293 then (import ./haskell-overlays/ghcide.nix)
294 else (_: _: {})
295 );
297 project = reflexPlatformProject ({...}: self.projectConfig);
298 projectConfig = {
299 inherit (self) shellToolOverrides;
300 inherit (self.userSettings) tools withHoogle;
301 overrides = self.totalOverrides;
302 packages = self.combinedPackages;
303 shells = {
304 ${if self.userSettings.android == null && self.userSettings.ios == null then null else "ghcSavedSplices"} =
305 lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghcSavedSplices;
306 ghc = lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghc;
307 ghcjs = lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghcjs;
308 };
309 android = self.__androidWithConfig (self.base + "/config");
310 ios = self.__iosWithConfig (self.base + "/config");
312 passthru = {
313 __unstable__.self = allConfig;
314 inherit (self)
315 staticFilesImpure processedStatic
316 __iosWithConfig __androidWithConfig
317 ;
318 inherit (self.userSettings)
319 android ios overrides packages shellToolOverrides staticFiles tools withHoogle
320 __closureCompilerOptimizationLevel
321 ;
322 };
323 };
324 });
325 in allConfig;
326 in (mkProject (projectDefinition args)).projectConfig);
327 mainProjectOut = projectOut { inherit system; };
328 serverOn = projectInst: version: serverExe
329 projectInst.ghc.backend
330 mainProjectOut.ghcjs.frontend
331 projectInst.passthru.staticFiles
332 projectInst.passthru.__closureCompilerOptimizationLevel
333 version;
334 linuxExe = serverOn (projectOut { system = "x86_64-linux"; });
335 dummyVersion = "Version number is only available for deployments";
336 in mainProjectOut // {
337 __unstable__.profiledObRun = let
338 profiled = projectOut { inherit system; enableLibraryProfiling = true; };
339 exeSource = builtins.toFile "ob-run.hs" ''
340 {-# LANGUAGE NoImplicitPrelude #-}
341 {-# LANGUAGE PackageImports #-}
342 module Main where
344 -- Explicitly import Prelude from base lest there be multiple modules called Prelude
345 import "base" Prelude (IO, (++), read)
347 import "base" Control.Exception (finally)
348 import "reflex" Reflex.Profiled (writeProfilingData)
349 import "base" System.Environment (getArgs)
351 import qualified "obelisk-run" Obelisk.Run
352 import qualified Frontend
353 import qualified Backend
355 main :: IO ()
356 main = do
357 [portStr, assets, profFileName] <- getArgs
358 Obelisk.Run.run (read portStr) (Obelisk.Run.runServeAsset assets) Backend.backend Frontend.frontend
359 `finally` writeProfilingData (profFileName ++ ".rprof")
360 '';
361 in nixpkgs.runCommand "ob-run" {
362 buildInputs = [ (profiled.ghc.ghcWithPackages (p: [p.backend p.frontend])) ];
363 } ''
364 cp ${exeSource} ob-run.hs
365 mkdir -p $out/bin
366 ghc -x hs -prof -fno-prof-auto -threaded ob-run.hs -o $out/bin/ob-run
367 '';
369 linuxExeConfigurable = linuxExe;
370 linuxExe = linuxExe dummyVersion;
371 exe = serverOn mainProjectOut dummyVersion;
372 server = args@{ hostName, adminEmail, routeHost, enableHttps, version, module ? serverModules.mkBaseEc2 }:
373 server (args // { exe = linuxExe version; });
374 obelisk = import (base' + "/.obelisk/impl") {};
375 };
376 haskellPackageSets = {
377 inherit (reflex-platform) ghc ghcjs;
378 };